<commit_before>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wextended-offsetof"

#include "SceneGraph.h"
#include "../volume/AMRVolume.h"
#include "../volume/Volume.h"
// hdf
#include "hdf5.h"
// ospcommon
#include "ospcommon/range.h"
#include "ospcommon/box.h"

// core ospray
#include "ospray/common/OSPCommon.h"

namespace ospray {
  namespace amr {

    //! stores AMR Level data
    struct Level
    {
      Level(int _levelID) : levelID(_levelID){}

      int levelID;
      // apparently, the refinement factor of this level
      double dt;
      /*! the 'outputGhost' variable, specifying the number of ghost cells on
       * all sides */
      vec3i numGhostCells;

      inline vec3i boxSize(const int boxID) const
      {
        return boxes[boxID].size() + 1;
      }

      inline double getValue(int boxID, int compID, const vec3i &coordNoGhost)
      {
        assert(compID >= 0);
        const vec3i sizeNoGhosts   = boxSize(boxID);
        const vec3i sizeWithGhosts = sizeNoGhosts + 2 * numGhostCells;
        size_t brickOfs            = offsets[boxID] +
                          compID * (size_t)sizeWithGhosts.x *
                              (size_t)sizeWithGhosts.y *
                              (size_t)sizeWithGhosts.z;
        const vec3i coordWithGhosts = coordNoGhost + numGhostCells;
        return data[brickOfs + coordWithGhosts.x +
                    sizeWithGhosts.x * (coordWithGhosts.y +
                                        sizeWithGhosts.y * coordWithGhosts.z)];
      }

      std::vector<box3i> boxes;
      std::vector<int64_t> offsets;
      std::vector<double> data;

      box3f getWorldBounds(const int boxID) const;
      box3f getWorldBounds() const;
    };

    //! struct AMR used for storing intermediate AMR representation for
    //!   file loading
    struct AMR
    {
      std::vector<Level *> level;
      //! array of component names
      std::vector<std::string> component;

      std::string voxelType="float"; // for now only floats are created by importer

      static AMR *parse(const std::string &fileName, int maxLevel = 1 << 30);
      box3f getWorldBounds() const;
    };

    //! parses out level data from hdf5 files
    void parseBoxes(hid_t file, Level *level)
    {
      char dataName[1000];
      sprintf(dataName, "level_%i/boxes", level->levelID);
      hid_t data = H5Dopen(file, dataName, H5P_DEFAULT);
      if (data < 0)
        throw std::runtime_error("does not exist");
      hid_t space        = H5Dget_space(data);
      const size_t nDims = H5Sget_simple_extent_ndims(space);
      hsize_t *dims = STACK_BUFFER(hsize_t, nDims);
      H5Sget_simple_extent_dims(space, dims, nullptr);
      size_t numBoxes = dims[0];

      // create compound data type for a box
      hid_t boxType = H5Tcreate(H5T_COMPOUND, sizeof(box3i));

      H5Tinsert(boxType, "lo_i", HOFFSET(box3i, lower.x), H5T_NATIVE_INT);
      H5Tinsert(boxType, "lo_j", HOFFSET(box3i, lower.y), H5T_NATIVE_INT);
      H5Tinsert(boxType, "lo_k", HOFFSET(box3i, lower.z), H5T_NATIVE_INT);
      H5Tinsert(boxType, "hi_i", HOFFSET(box3i, upper.x), H5T_NATIVE_INT);
      H5Tinsert(boxType, "hi_j", HOFFSET(box3i, upper.y), H5T_NATIVE_INT);
      H5Tinsert(boxType, "hi_k", HOFFSET(box3i, upper.z), H5T_NATIVE_INT);

      level->boxes.resize(numBoxes);
      H5Dread(data, boxType, H5S_ALL, H5S_ALL, H5P_DEFAULT, &level->boxes[0]);
      H5Dclose(data);
    }

    //! parses out refinement levels for amr data
    void parseOffsets(hid_t file, Level *level)
    {
      char dataName[1000];
      sprintf(dataName, "level_%i/data:offsets=0", level->levelID);
      hid_t data = H5Dopen(file, dataName, H5P_DEFAULT);
      if (data < 0)
        throw std::runtime_error("does not exist");
      hid_t space        = H5Dget_space(data);
      const size_t nDims = H5Sget_simple_extent_ndims(space);
      hsize_t *dims = STACK_BUFFER(hsize_t, nDims);
      H5Sget_simple_extent_dims(space, dims, nullptr);
      size_t numOffsets = dims[0];

      level->offsets.resize(numOffsets);
      H5Dread(data,
              H5T_NATIVE_INT64,
              H5S_ALL,
              H5S_ALL,
              H5P_DEFAULT,
              &level->offsets[0]);
      H5Dclose(data);
    }

    //! parse scalar data from hdf5 file
    void parseData(hid_t file, Level *level)
    {
      char dataName[1000];
      sprintf(dataName, "level_%i/data:datatype=0", level->levelID);
      hid_t data         = H5Dopen(file, dataName, H5P_DEFAULT);
      hid_t space        = H5Dget_space(data);
      const size_t nDims = H5Sget_simple_extent_ndims(space);
      hsize_t *dims = STACK_BUFFER(hsize_t, nDims);
      H5Sget_simple_extent_dims(space, dims, nullptr);
      size_t numData = dims[0];

      level->data.resize(numData);
      H5Dread(data,
              H5T_NATIVE_DOUBLE,
              H5S_ALL,
              H5S_ALL,
              H5P_DEFAULT,
              &level->data[0]);

      H5Dclose(data);
    }

    //! parse attributes in hdf5 amr data
    void parseDataAttributes(hid_t file,
                             Level *level,
                             const std::string &levelName)
    {
      const std::string dataAttrName =
          "/" + levelName + "/" + "data_attributes";
      hid_t attr_ghost = H5Aopen_by_name(
          file, dataAttrName.c_str(), "outputGhost", H5P_DEFAULT, H5P_DEFAULT);
      hid_t ghostType  = H5Aget_type(attr_ghost);
      H5Aread(attr_ghost, ghostType, &level->numGhostCells);
      H5Aclose(attr_ghost);
    }

    //! parse individual level in amr data
    void parseLevel(hid_t file, Level *level)
    {
      char levelName[1000];
      sprintf(levelName, "level_%i", level->levelID);
      hid_t attr_dt =
          H5Aopen_by_name(file, levelName, "dx", H5P_DEFAULT, H5P_DEFAULT);
      H5Aread(attr_dt, H5T_NATIVE_DOUBLE, &level->dt);
      H5Aclose(attr_dt);

      parseDataAttributes(file, level, levelName);
      parseBoxes(file, level);
      parseData(file, level);
      parseOffsets(file, level);

      ospLogF(1) << "read input level #" << level->levelID << ", cellWidth is "
                 << level->dt << std::endl;
    }

    //! parse hdf5 file
    AMR *AMR::parse(const std::string &fileName, int maxLevel)
    {
      AMR *cd           = new AMR;
      char *maxLevelEnv = getenv("AMR_MAX_LEVEL");
      if (maxLevelEnv) {
        maxLevel = atoi(maxLevelEnv);
      } else {
      }
      hid_t file = H5Fopen(fileName.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
      if (!file)
        throw std::runtime_error("could not open AMR HDF file '" + fileName +
                                 "'");

      // read components ...
      int numComponents = -1;
      {
        hid_t attr_num_components = H5Aopen_by_name(
            file, "/", "num_components", H5P_DEFAULT, H5P_DEFAULT);
        H5Aread(attr_num_components, H5T_NATIVE_INT, &numComponents);
        H5Aclose(attr_num_components);
      }
      if (numComponents < 1)
        throw std::runtime_error("could not parse num components");
      for (ssize_t i = 0; i < numComponents; i++) {
        char compName[10000];
        sprintf(compName, "component_%li", i);

        hid_t att        = H5Aopen_name(file, compName);
        hid_t ftype      = H5Aget_type(att);

        size_t len = H5Tget_size(ftype);
        char *comp = STACK_BUFFER(char, (len + 1));
        comp[len] = 0;

        hid_t type = H5Tget_native_type(ftype, H5T_DIR_ASCEND);
        H5Aread(att, type, comp);
        H5Aclose(att);

        cd->component.push_back(comp);
      }

      unsigned long long numObjectsInFile;
      H5Gget_num_objs(file, &numObjectsInFile);

      for (size_t objID = 0; objID < numObjectsInFile; objID++) {
        const int MAX_NAME_SIZE = 1000;
        char name[MAX_NAME_SIZE];
        H5Gget_objname_by_idx(file, objID, name, MAX_NAME_SIZE);

        if (objID == 0) {
          if (strcmp(name, "Chombo_global")) {
            std::cout << name << std::endl;
            throw std::runtime_error(
                "missing 'Chombo_global' object - apparently this is not a "
                "chombo file!?");
          }
          continue;
        }
        int levelID;
        int rc = sscanf(name, "level_%d", &levelID);
        if (rc == 1) {
          if (levelID > maxLevel) {
            ospLogF(1) << "#osp:amr: skipping amr level #" << levelID
                       << " as instructed by amr_MAX_LEVEL envvar" << std::endl;
            continue;
          }

          Level *level = new Level(levelID);
          parseLevel(file, level);
          cd->level.push_back(level);
          continue;
        }
        ospLogF(1) << "#osp:qtv:amr: unknown HDF5 block '" << name << "'"
                   << std::endl;
      }

      H5Fclose(file);
      return cd;
    }

    //! get bounds for leaf level
    box3f Level::getWorldBounds(const int boxID) const
    {
      return box3f(float(dt) * vec3f(boxes[boxID].lower),
                   float(dt) * vec3f(boxes[boxID].upper + vec3i(1)));
    }

    //! get bounds for a level
    box3f Level::getWorldBounds() const
    {
      box3f bounds = getWorldBounds(0);
      for (size_t i = 1; i < boxes.size(); i++)
        bounds.extend(getWorldBounds(i));
      return bounds;
    }

    //! get bounds of enditre amr struct
    box3f AMR::getWorldBounds() const
    {
      box3f bounds = empty;
      for (size_t i = 0; i < level.size(); i++)
        bounds.extend(level[i]->getWorldBounds());
      return bounds;
    }

  }  // ::ospray::amr

  namespace sg {

    //! parse Chombo hdf5 file into AMRVolume node
    void parseAMRChomboFile(std::shared_ptr<sg::AMRVolume> &node,
                            const FileName &fileName,
                            const std::string &desiredComponent = "",
                            const range1f *clampRange = nullptr,
                            int maxLevel = 1 << 30)
    {
      amr::AMR *amr = ospray::amr::AMR::parse(fileName.str(), maxLevel);
      assert(!amr->level.empty());

      box3i rootLevelBounds = empty;
      for (size_t i = 0; i < amr->level[0]->boxes.size(); i++)
        rootLevelBounds.extend(amr->level[0]->boxes[i]);
      assert(rootLevelBounds.lower == vec3i(0));

      node->child("bounds") = amr->getWorldBounds();
      (*node)["voxelType"] = amr->voxelType;

      node->componentID = -1;
      for (size_t i = 0; i < amr->component.size(); i++) {
        if (amr->component[i] == desiredComponent) {
          node->componentID = i;
        }
      }
      if (node->componentID < 0) {
        if (desiredComponent == "") {
          ospLogF(1) << "no component specified - defaulting to component 0"
                     << std::endl;
          node->componentID = 0;
        } else
          throw std::runtime_error("could not find desird component '" +
                                   desiredComponent + "'");
      }

      for (size_t levelID = 0; levelID < amr->level.size(); levelID++) {
        amr::Level *level = amr->level[levelID];
        ospLogF(1) << " - level: " << levelID << " : " << level->boxes.size()
                   << " boxes" << std::endl;
        for (size_t brickID = 0; brickID < level->boxes.size(); brickID++) {
          AMRVolume::BrickInfo bi;
          bi.box   = level->boxes[brickID];
          bi.dt    = level->dt;
          bi.level = levelID;

          node->brickInfo.push_back(bi);

          size_t numValues = bi.size().product();
          float *f         = new float[numValues];
          node->brickPtrs.push_back(f);
          for (int iz = 0; iz < bi.size().z; iz++)
            for (int iy = 0; iy < bi.size().y; iy++)
              for (int ix = 0; ix < bi.size().x; ix++) {
                vec3i coord(ix, iy, iz);
                double v = level->getValue(brickID, node->componentID, coord);
                if (clampRange)
                  v = clampRange->clamp(v);
                node->valueRange.extend(v);
                *f++ = v;
              }
        }
        level->data.clear();
      }
      ospLogF(1) << "found " << node->brickInfo.size() << " bricks"
                 << std::endl;
    }

    // Import HDF5 CHOMBO files ///////////////////////////////////////////////

    void importCHOMBO(std::shared_ptr<Node> world, const FileName &fileName)
    {
      auto node = sg::createNode("amr", "AMRVolume")->nodeAs<sg::AMRVolume>();
      parseAMRChomboFile(node, fileName);
      node->child("transferFunction")["valueRange"] = node->valueRange.toVec2f();
      world->add(node);
    }

  }  // ::ospray::sg
}  // ::ospray

#pragma clang diagnostic pop
<commit_msg>fix missed CHOMBO importer function signature change<commit_after>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wextended-offsetof"

#include "SceneGraph.h"
#include "../volume/AMRVolume.h"
#include "../volume/Volume.h"
// hdf
#include "hdf5.h"
// ospcommon
#include "ospcommon/range.h"
#include "ospcommon/box.h"

// core ospray
#include "ospray/common/OSPCommon.h"

namespace ospray {
  namespace amr {

    //! stores AMR Level data
    struct Level
    {
      Level(int _levelID) : levelID(_levelID){}

      int levelID;
      // apparently, the refinement factor of this level
      double dt;
      /*! the 'outputGhost' variable, specifying the number of ghost cells on
       * all sides */
      vec3i numGhostCells;

      inline vec3i boxSize(const int boxID) const
      {
        return boxes[boxID].size() + 1;
      }

      inline double getValue(int boxID, int compID, const vec3i &coordNoGhost)
      {
        assert(compID >= 0);
        const vec3i sizeNoGhosts   = boxSize(boxID);
        const vec3i sizeWithGhosts = sizeNoGhosts + 2 * numGhostCells;
        size_t brickOfs            = offsets[boxID] +
                          compID * (size_t)sizeWithGhosts.x *
                              (size_t)sizeWithGhosts.y *
                              (size_t)sizeWithGhosts.z;
        const vec3i coordWithGhosts = coordNoGhost + numGhostCells;
        return data[brickOfs + coordWithGhosts.x +
                    sizeWithGhosts.x * (coordWithGhosts.y +
                                        sizeWithGhosts.y * coordWithGhosts.z)];
      }

      std::vector<box3i> boxes;
      std::vector<int64_t> offsets;
      std::vector<double> data;

      box3f getWorldBounds(const int boxID) const;
      box3f getWorldBounds() const;
    };

    //! struct AMR used for storing intermediate AMR representation for
    //!   file loading
    struct AMR
    {
      std::vector<Level *> level;
      //! array of component names
      std::vector<std::string> component;

      std::string voxelType="float"; // for now only floats are created by importer

      static AMR *parse(const std::string &fileName, int maxLevel = 1 << 30);
      box3f getWorldBounds() const;
    };

    //! parses out level data from hdf5 files
    void parseBoxes(hid_t file, Level *level)
    {
      char dataName[1000];
      sprintf(dataName, "level_%i/boxes", level->levelID);
      hid_t data = H5Dopen(file, dataName, H5P_DEFAULT);
      if (data < 0)
        throw std::runtime_error("does not exist");
      hid_t space        = H5Dget_space(data);
      const size_t nDims = H5Sget_simple_extent_ndims(space);
      hsize_t *dims = STACK_BUFFER(hsize_t, nDims);
      H5Sget_simple_extent_dims(space, dims, nullptr);
      size_t numBoxes = dims[0];

      // create compound data type for a box
      hid_t boxType = H5Tcreate(H5T_COMPOUND, sizeof(box3i));

      H5Tinsert(boxType, "lo_i", HOFFSET(box3i, lower.x), H5T_NATIVE_INT);
      H5Tinsert(boxType, "lo_j", HOFFSET(box3i, lower.y), H5T_NATIVE_INT);
      H5Tinsert(boxType, "lo_k", HOFFSET(box3i, lower.z), H5T_NATIVE_INT);
      H5Tinsert(boxType, "hi_i", HOFFSET(box3i, upper.x), H5T_NATIVE_INT);
      H5Tinsert(boxType, "hi_j", HOFFSET(box3i, upper.y), H5T_NATIVE_INT);
      H5Tinsert(boxType, "hi_k", HOFFSET(box3i, upper.z), H5T_NATIVE_INT);

      level->boxes.resize(numBoxes);
      H5Dread(data, boxType, H5S_ALL, H5S_ALL, H5P_DEFAULT, &level->boxes[0]);
      H5Dclose(data);
    }

    //! parses out refinement levels for amr data
    void parseOffsets(hid_t file, Level *level)
    {
      char dataName[1000];
      sprintf(dataName, "level_%i/data:offsets=0", level->levelID);
      hid_t data = H5Dopen(file, dataName, H5P_DEFAULT);
      if (data < 0)
        throw std::runtime_error("does not exist");
      hid_t space        = H5Dget_space(data);
      const size_t nDims = H5Sget_simple_extent_ndims(space);
      hsize_t *dims = STACK_BUFFER(hsize_t, nDims);
      H5Sget_simple_extent_dims(space, dims, nullptr);
      size_t numOffsets = dims[0];

      level->offsets.resize(numOffsets);
      H5Dread(data,
              H5T_NATIVE_INT64,
              H5S_ALL,
              H5S_ALL,
              H5P_DEFAULT,
              &level->offsets[0]);
      H5Dclose(data);
    }

    //! parse scalar data from hdf5 file
    void parseData(hid_t file, Level *level)
    {
      char dataName[1000];
      sprintf(dataName, "level_%i/data:datatype=0", level->levelID);
      hid_t data         = H5Dopen(file, dataName, H5P_DEFAULT);
      hid_t space        = H5Dget_space(data);
      const size_t nDims = H5Sget_simple_extent_ndims(space);
      hsize_t *dims = STACK_BUFFER(hsize_t, nDims);
      H5Sget_simple_extent_dims(space, dims, nullptr);
      size_t numData = dims[0];

      level->data.resize(numData);
      H5Dread(data,
              H5T_NATIVE_DOUBLE,
              H5S_ALL,
              H5S_ALL,
              H5P_DEFAULT,
              &level->data[0]);

      H5Dclose(data);
    }

    //! parse attributes in hdf5 amr data
    void parseDataAttributes(hid_t file,
                             Level *level,
                             const std::string &levelName)
    {
      const std::string dataAttrName =
          "/" + levelName + "/" + "data_attributes";
      hid_t attr_ghost = H5Aopen_by_name(
          file, dataAttrName.c_str(), "outputGhost", H5P_DEFAULT, H5P_DEFAULT);
      hid_t ghostType  = H5Aget_type(attr_ghost);
      H5Aread(attr_ghost, ghostType, &level->numGhostCells);
      H5Aclose(attr_ghost);
    }

    //! parse individual level in amr data
    void parseLevel(hid_t file, Level *level)
    {
      char levelName[1000];
      sprintf(levelName, "level_%i", level->levelID);
      hid_t attr_dt =
          H5Aopen_by_name(file, levelName, "dx", H5P_DEFAULT, H5P_DEFAULT);
      H5Aread(attr_dt, H5T_NATIVE_DOUBLE, &level->dt);
      H5Aclose(attr_dt);

      parseDataAttributes(file, level, levelName);
      parseBoxes(file, level);
      parseData(file, level);
      parseOffsets(file, level);

      ospLogF(1) << "read input level #" << level->levelID << ", cellWidth is "
                 << level->dt << std::endl;
    }

    //! parse hdf5 file
    AMR *AMR::parse(const std::string &fileName, int maxLevel)
    {
      AMR *cd           = new AMR;
      char *maxLevelEnv = getenv("AMR_MAX_LEVEL");
      if (maxLevelEnv) {
        maxLevel = atoi(maxLevelEnv);
      } else {
      }
      hid_t file = H5Fopen(fileName.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
      if (!file)
        throw std::runtime_error("could not open AMR HDF file '" + fileName +
                                 "'");

      // read components ...
      int numComponents = -1;
      {
        hid_t attr_num_components = H5Aopen_by_name(
            file, "/", "num_components", H5P_DEFAULT, H5P_DEFAULT);
        H5Aread(attr_num_components, H5T_NATIVE_INT, &numComponents);
        H5Aclose(attr_num_components);
      }
      if (numComponents < 1)
        throw std::runtime_error("could not parse num components");
      for (ssize_t i = 0; i < numComponents; i++) {
        char compName[10000];
        sprintf(compName, "component_%li", i);

        hid_t att        = H5Aopen_name(file, compName);
        hid_t ftype      = H5Aget_type(att);

        size_t len = H5Tget_size(ftype);
        char *comp = STACK_BUFFER(char, (len + 1));
        comp[len] = 0;

        hid_t type = H5Tget_native_type(ftype, H5T_DIR_ASCEND);
        H5Aread(att, type, comp);
        H5Aclose(att);

        cd->component.push_back(comp);
      }

      unsigned long long numObjectsInFile;
      H5Gget_num_objs(file, &numObjectsInFile);

      for (size_t objID = 0; objID < numObjectsInFile; objID++) {
        const int MAX_NAME_SIZE = 1000;
        char name[MAX_NAME_SIZE];
        H5Gget_objname_by_idx(file, objID, name, MAX_NAME_SIZE);

        if (objID == 0) {
          if (strcmp(name, "Chombo_global")) {
            std::cout << name << std::endl;
            throw std::runtime_error(
                "missing 'Chombo_global' object - apparently this is not a "
                "chombo file!?");
          }
          continue;
        }
        int levelID;
        int rc = sscanf(name, "level_%d", &levelID);
        if (rc == 1) {
          if (levelID > maxLevel) {
            ospLogF(1) << "#osp:amr: skipping amr level #" << levelID
                       << " as instructed by amr_MAX_LEVEL envvar" << std::endl;
            continue;
          }

          Level *level = new Level(levelID);
          parseLevel(file, level);
          cd->level.push_back(level);
          continue;
        }
        ospLogF(1) << "#osp:qtv:amr: unknown HDF5 block '" << name << "'"
                   << std::endl;
      }

      H5Fclose(file);
      return cd;
    }

    //! get bounds for leaf level
    box3f Level::getWorldBounds(const int boxID) const
    {
      return box3f(float(dt) * vec3f(boxes[boxID].lower),
                   float(dt) * vec3f(boxes[boxID].upper + vec3i(1)));
    }

    //! get bounds for a level
    box3f Level::getWorldBounds() const
    {
      box3f bounds = getWorldBounds(0);
      for (size_t i = 1; i < boxes.size(); i++)
        bounds.extend(getWorldBounds(i));
      return bounds;
    }

    //! get bounds of enditre amr struct
    box3f AMR::getWorldBounds() const
    {
      box3f bounds = empty;
      for (size_t i = 0; i < level.size(); i++)
        bounds.extend(level[i]->getWorldBounds());
      return bounds;
    }

  }  // ::ospray::amr

  namespace sg {

    //! parse Chombo hdf5 file into AMRVolume node
    void parseAMRChomboFile(std::shared_ptr<sg::AMRVolume> &node,
                            const FileName &fileName,
                            const std::string &desiredComponent = "",
                            const range1f *clampRange = nullptr,
                            int maxLevel = 1 << 30)
    {
      amr::AMR *amr = ospray::amr::AMR::parse(fileName.str(), maxLevel);
      assert(!amr->level.empty());

      box3i rootLevelBounds = empty;
      for (size_t i = 0; i < amr->level[0]->boxes.size(); i++)
        rootLevelBounds.extend(amr->level[0]->boxes[i]);
      assert(rootLevelBounds.lower == vec3i(0));

      node->child("bounds") = amr->getWorldBounds();
      (*node)["voxelType"] = amr->voxelType;

      node->componentID = -1;
      for (size_t i = 0; i < amr->component.size(); i++) {
        if (amr->component[i] == desiredComponent) {
          node->componentID = i;
        }
      }
      if (node->componentID < 0) {
        if (desiredComponent == "") {
          ospLogF(1) << "no component specified - defaulting to component 0"
                     << std::endl;
          node->componentID = 0;
        } else
          throw std::runtime_error("could not find desird component '" +
                                   desiredComponent + "'");
      }

      for (size_t levelID = 0; levelID < amr->level.size(); levelID++) {
        amr::Level *level = amr->level[levelID];
        ospLogF(1) << " - level: " << levelID << " : " << level->boxes.size()
                   << " boxes" << std::endl;
        for (size_t brickID = 0; brickID < level->boxes.size(); brickID++) {
          AMRVolume::BrickInfo bi;
          bi.box   = level->boxes[brickID];
          bi.dt    = level->dt;
          bi.level = levelID;

          node->brickInfo.push_back(bi);

          size_t numValues = bi.size().product();
          float *f         = new float[numValues];
          node->brickPtrs.push_back(f);
          for (int iz = 0; iz < bi.size().z; iz++)
            for (int iy = 0; iy < bi.size().y; iy++)
              for (int ix = 0; ix < bi.size().x; ix++) {
                vec3i coord(ix, iy, iz);
                double v = level->getValue(brickID, node->componentID, coord);
                if (clampRange)
                  v = clampRange->clamp(v);
                node->valueRange.extend(v);
                *f++ = v;
              }
        }
        level->data.clear();
      }
      ospLogF(1) << "found " << node->brickInfo.size() << " bricks"
                 << std::endl;
    }

    // Import HDF5 CHOMBO files ///////////////////////////////////////////////

    void importCHOMBO(const std::shared_ptr<Node> &world,
                      const FileName &fileName)
    {
      auto node = sg::createNode("amr", "AMRVolume")->nodeAs<sg::AMRVolume>();
      parseAMRChomboFile(node, fileName);
      node->child("transferFunction")["valueRange"] = node->valueRange.toVec2f();
      world->add(node);
    }

  }  // ::ospray::sg
}  // ::ospray

#pragma clang diagnostic pop
<|endoftext|>


<commit_before>//
//  Starcounter Lisp
//
//  Cons.cpp
//
//  The Cons from Lisp. A Cons is a pair with a left and a right value.
//  The left value is the first value of a list and the right value is the rest of the list.
//  (aka car,cdr).
//
//  Created by Joachim Wester on 22/04/16.
//  Copyright © 2016 Starcounter AB.
//

#include "Cons.hpp"

void CONS::Print() {
    if (Pointer == 0) {
        std::cout << "()";
    }
    else {
        std::cout << " (";
        GetCons()->Car.Print();
        std::cout << " . ";
        GetCons()->Cdr.Print();
        std::cout << ")";
    }
}

// Snoc is the reverse of Cons. Stolen from Emacs terminology. Bang! is because
// this should only be done on mutable lists.
CONS CONS::SnocBANG( VALUE elem ) {
    CONS previousTail;
    auto x = previousTail.__allocateCons( elem, NIL() );
    GetCons()->Cdr = previousTail;
    return CONS(x);
}

Cons* CONS::__allocateCons( VALUE car, VALUE cdr ) {
        auto c = new Cons(car,cdr); // TODO! GC
        Pointer = (uint64_t)c;
    return c;
}
<commit_msg>Done for tonight<commit_after>//
//  Starcounter Lisp
//
//  Cons.cpp
//
//  The Cons from Lisp. A Cons is a pair with a left and a right value.
//  The left value is the first value of a list and the right value is the rest of the list.
//  (aka car,cdr).
//
//  Created by Joachim Wester on 22/04/16.
//  Copyright © 2016 Starcounter AB.
//

#include "Cons.hpp"

void CONS::Print() {
    if (Pointer == 0) {
        std::cout << "()";
    }
    else {
        std::cout << "(";
        GetCons()->Car.Print();
        std::cout << " . ";
        GetCons()->Cdr.Print();
        std::cout << ")";
    }
}

// Snoc is the reverse of Cons. Stolen from Emacs terminology. Bang! is because
// this should only be done on mutable lists.
CONS CONS::SnocBANG( VALUE elem ) {
    CONS previousTail;
    auto x = previousTail.__allocateCons( elem, NIL() );
    GetCons()->Cdr = previousTail;
    return CONS(x);
}

Cons* CONS::__allocateCons( VALUE car, VALUE cdr ) {
        auto c = new Cons(car,cdr); // TODO! GC
        Pointer = (uint64_t)c;
    return c;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fragmenthandler2.cxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/core/fragmenthandler2.hxx"

using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::xml::sax::SAXException;
using ::com::sun::star::xml::sax::XFastAttributeList;
using ::com::sun::star::xml::sax::XFastContextHandler;

namespace oox {
namespace core {

// ============================================================================

FragmentHandler2::FragmentHandler2( XmlFilterBase& rFilter, const OUString& rFragmentPath ) :
    FragmentHandler( rFilter, rFragmentPath )
{
}

FragmentHandler2::~FragmentHandler2()
{
}

ContextHandler& FragmentHandler2::queryContextHandler()
{
    return *this;
}

// com.sun.star.xml.sax.XFastDocumentHandler interface --------------------

void SAL_CALL FragmentHandler2::startDocument() throw( SAXException, RuntimeException )
{
    initializeImport();
}

void SAL_CALL FragmentHandler2::endDocument() throw( SAXException, RuntimeException )
{
    finalizeImport();
}

// com.sun.star.xml.sax.XFastContextHandler interface -------------------------

Reference< XFastContextHandler > SAL_CALL FragmentHandler2::createFastChildContext(
        sal_Int32 nElement, const Reference< XFastAttributeList >& rxAttribs ) throw( SAXException, RuntimeException )
{
    return implCreateChildContext( nElement, rxAttribs );
}

void SAL_CALL FragmentHandler2::startFastElement(
        sal_Int32 nElement, const Reference< XFastAttributeList >& rxAttribs ) throw( SAXException, RuntimeException )
{
    implStartCurrentContext( nElement, rxAttribs );
}

void SAL_CALL FragmentHandler2::characters( const OUString& rChars ) throw( SAXException, RuntimeException )
{
    implCharacters( rChars );
}

void SAL_CALL FragmentHandler2::endFastElement( sal_Int32 nElement ) throw( SAXException, RuntimeException )
{
    implEndCurrentContext( nElement );
}

// oox.core.ContextHandler interface ------------------------------------------

ContextHandlerRef FragmentHandler2::createRecordContext( sal_Int32 nRecId, RecordInputStream& rStrm )
{
    return implCreateRecordContext( nRecId, rStrm );
}

void FragmentHandler2::startRecord( sal_Int32 nRecId, RecordInputStream& rStrm )
{
    implStartRecord( nRecId, rStrm );
}

void FragmentHandler2::endRecord( sal_Int32 nRecId )
{
    implEndRecord( nRecId );
}

// oox.core.ContextHandler2Helper interface -----------------------------------

ContextWrapper FragmentHandler2::onCreateContext( sal_Int32, const AttributeList& )
{
    return false;
}

void FragmentHandler2::onStartElement( const AttributeList& )
{
}

void FragmentHandler2::onEndElement( const OUString& )
{
}

ContextWrapper FragmentHandler2::onCreateRecordContext( sal_Int32, RecordInputStream& )
{
    return false;
}

void FragmentHandler2::onStartRecord( RecordInputStream& )
{
}

void FragmentHandler2::onEndRecord()
{
}

// oox.core.FragmentHandler2 interface ----------------------------------------

void FragmentHandler2::initializeImport()
{
}

void FragmentHandler2::finalizeImport()
{
}

// ============================================================================

} // namespace core
} // namespace oox

<commit_msg>INTEGRATION: CWS xmlfilter06 (1.3.6); FILE MERGED 2008/06/25 14:58:38 dr 1.3.6.2: import chart data point labels and trendline label 2008/05/27 10:40:34 dr 1.3.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fragmenthandler2.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/core/fragmenthandler2.hxx"

using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::xml::sax::SAXException;
using ::com::sun::star::xml::sax::XFastAttributeList;
using ::com::sun::star::xml::sax::XFastContextHandler;

namespace oox {
namespace core {

// ============================================================================

FragmentHandler2::FragmentHandler2( XmlFilterBase& rFilter, const OUString& rFragmentPath, bool bEnableTrimSpace ) :
    FragmentHandler( rFilter, rFragmentPath ),
    ContextHandler2Helper( bEnableTrimSpace )
{
}

FragmentHandler2::~FragmentHandler2()
{
}

ContextHandler& FragmentHandler2::queryContextHandler()
{
    return *this;
}

// com.sun.star.xml.sax.XFastDocumentHandler interface --------------------

void SAL_CALL FragmentHandler2::startDocument() throw( SAXException, RuntimeException )
{
    initializeImport();
}

void SAL_CALL FragmentHandler2::endDocument() throw( SAXException, RuntimeException )
{
    finalizeImport();
}

// com.sun.star.xml.sax.XFastContextHandler interface -------------------------

Reference< XFastContextHandler > SAL_CALL FragmentHandler2::createFastChildContext(
        sal_Int32 nElement, const Reference< XFastAttributeList >& rxAttribs ) throw( SAXException, RuntimeException )
{
    return implCreateChildContext( nElement, rxAttribs );
}

void SAL_CALL FragmentHandler2::startFastElement(
        sal_Int32 nElement, const Reference< XFastAttributeList >& rxAttribs ) throw( SAXException, RuntimeException )
{
    implStartCurrentContext( nElement, rxAttribs );
}

void SAL_CALL FragmentHandler2::characters( const OUString& rChars ) throw( SAXException, RuntimeException )
{
    implCharacters( rChars );
}

void SAL_CALL FragmentHandler2::endFastElement( sal_Int32 nElement ) throw( SAXException, RuntimeException )
{
    implEndCurrentContext( nElement );
}

// oox.core.ContextHandler interface ------------------------------------------

ContextHandlerRef FragmentHandler2::createRecordContext( sal_Int32 nRecId, RecordInputStream& rStrm )
{
    return implCreateRecordContext( nRecId, rStrm );
}

void FragmentHandler2::startRecord( sal_Int32 nRecId, RecordInputStream& rStrm )
{
    implStartRecord( nRecId, rStrm );
}

void FragmentHandler2::endRecord( sal_Int32 nRecId )
{
    implEndRecord( nRecId );
}

// oox.core.ContextHandler2Helper interface -----------------------------------

ContextWrapper FragmentHandler2::onCreateContext( sal_Int32, const AttributeList& )
{
    return false;
}

void FragmentHandler2::onStartElement( const AttributeList& )
{
}

void FragmentHandler2::onEndElement( const OUString& )
{
}

ContextWrapper FragmentHandler2::onCreateRecordContext( sal_Int32, RecordInputStream& )
{
    return false;
}

void FragmentHandler2::onStartRecord( RecordInputStream& )
{
}

void FragmentHandler2::onEndRecord()
{
}

// oox.core.FragmentHandler2 interface ----------------------------------------

void FragmentHandler2::initializeImport()
{
}

void FragmentHandler2::finalizeImport()
{
}

// ============================================================================

} // namespace core
} // namespace oox

<|endoftext|>


<commit_before><commit_msg>-Werror,-Wunused-variable<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sharedocdlg.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2008-03-11 07:47:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

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

#include <osl/security.hxx>
#include <svtools/sharecontrolfile.hxx>
#include <svtools/useroptions.hxx>

#include <docsh.hxx>

#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
#include <com/sun/star/document/XDocumentProperties.hpp>

#include "sharedocdlg.hxx"
#include "sharedocdlg.hrc"
#include "scresid.hxx"
#include "docsh.hxx"
#include "viewdata.hxx"

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

//=============================================================================
// class ScShareDocumentDlg
//=============================================================================

ScShareDocumentDlg::ScShareDocumentDlg( Window* pParent, ScViewData* pViewData )
    :ModalDialog( pParent, ScResId( RID_SCDLG_SHAREDOCUMENT ) )
    ,maCbShare            ( this, ScResId( CB_SHARE ) )
    ,maFtWarning          ( this, ScResId( FT_WARNING ) )
    ,maFlUsers            ( this, ScResId( FL_USERS ) )
    ,maFtUsers            ( this, ScResId( FT_USERS ) )
    ,maLbUsers            ( this, ScResId( LB_USERS ) )
    ,maFlEnd              ( this, ScResId( FL_END ) )
    ,maBtnHelp            ( this, ScResId( BTN_HELP ) )
    ,maBtnOK              ( this, ScResId( BTN_OK ) )
    ,maBtnCancel          ( this, ScResId( BTN_CANCEL ) )
    ,maStrTitleName       ( ScResId( STR_TITLE_NAME ) )
    ,maStrTitleAccessed   ( ScResId( STR_TITLE_ACCESSED ) )
    ,maStrNoUserData      ( ScResId( STR_NO_USER_DATA ) )
    ,maStrUnkownUser      ( ScResId( STR_UNKNOWN_USER ) )
    ,maStrExclusiveAccess ( ScResId( STR_EXCLUSIVE_ACCESS ) )
    ,mpViewData           ( pViewData )
    ,mpDocShell           ( NULL )
{
    DBG_ASSERT( mpViewData, "ScShareDocumentDlg CTOR: mpViewData is null!" );
    mpDocShell = ( mpViewData ? mpViewData->GetDocShell() : NULL );
    DBG_ASSERT( mpDocShell, "ScShareDocumentDlg CTOR: mpDocShell is null!" );

    FreeResource();

    bool bIsDocShared = ( mpDocShell ? mpDocShell->IsDocShared() : false );
    maCbShare.Check( bIsDocShared );
    maCbShare.SetToggleHdl( LINK( this, ScShareDocumentDlg, ToggleHandle ) );
    maFtWarning.Enable( bIsDocShared );

    long nTabs[] = { 2, 10, 122 };
    maLbUsers.SetTabs( nTabs );

    String aHeader( maStrTitleName );
    aHeader += '\t';
    aHeader += maStrTitleAccessed;
    maLbUsers.InsertHeaderEntry( aHeader, HEADERBAR_APPEND, HIB_LEFT | HIB_LEFTIMAGE | HIB_VCENTER );
    maLbUsers.SetSelectionMode( NO_SELECTION );

    UpdateView();
}

ScShareDocumentDlg::~ScShareDocumentDlg()
{
}

IMPL_LINK( ScShareDocumentDlg, ToggleHandle, void*, EMPTYARG )
{
    maFtWarning.Enable( maCbShare.IsChecked() );

    return 0;
}

bool ScShareDocumentDlg::IsShareDocumentChecked() const
{
    return maCbShare.IsChecked();
}

void ScShareDocumentDlg::UpdateView()
{
    if ( !mpDocShell )
    {
        return;
    }

    if ( mpDocShell->IsDocShared() )
    {
        try
        {
            ::svt::ShareControlFile aControlFile( mpDocShell->GetSharedFileUrl() );
            uno::Sequence< uno::Sequence< ::rtl::OUString > > aUsersData = aControlFile.GetUsersData();
            const uno::Sequence< ::rtl::OUString >* pUsersData = aUsersData.getConstArray();
            sal_Int32 nLength = aUsersData.getLength();

            if ( nLength > 0 )
            {
                sal_Int32 nUnknownUser = 1;

                for ( sal_Int32 i = 0; i < nLength; ++i )
                {
                    if ( pUsersData[i].getLength() != SHARED_ENTRYSIZE )
                    {
                        continue;
                    }

                    String aUser = pUsersData[i][SHARED_OOOUSERNAME_ID];
                    aUser.EraseLeadingAndTrailingChars();
                    if ( aUser.Len() == 0 )
                    {
                        aUser = pUsersData[i][SHARED_SYSUSERNAME_ID];
                        aUser.EraseLeadingAndTrailingChars();
                    }
                    if ( aUser.Len() == 0 )
                    {
                        aUser = maStrUnkownUser;
                        aUser += ' ';
                        aUser += String::CreateFromInt32( nUnknownUser++ );
                    }

                    String aDateTime = pUsersData[i][SHARED_EDITTIME_ID];

                    String aString( aUser );
                    aString += '\t';
                    aString += aDateTime;
                    maLbUsers.InsertEntry( aString, NULL );
                }
            }
            else
            {
                maLbUsers.InsertEntry( maStrNoUserData, NULL );
            }
        }
        catch ( uno::Exception& )
        {
            DBG_ERROR( "ScShareDocumentDlg::UpdateView(): caught exception\n" );
            maLbUsers.Clear();
            maLbUsers.InsertEntry( maStrNoUserData, NULL );
        }
    }
    else
    {
        // get OOO user name
        SvtUserOptions aUserOpt;
        String aUser = aUserOpt.GetFirstName();
        aUser += ' ';
        aUser += aUserOpt.GetLastName();
        aUser.EraseLeadingAndTrailingChars();
        if ( aUser.Len() == 0 )
        {
            // get sys user name
            ::rtl::OUString aUserName;
            ::osl::Security aSecurity;
            aSecurity.getUserName( aUserName );
            aUser = aUserName;
            aUser.EraseLeadingAndTrailingChars();
        }
        if ( aUser.Len() == 0 )
        {
            // unknown user name
            aUser = maStrUnkownUser;
        }
        aUser += ' ';
        aUser += maStrExclusiveAccess;
        String aString( aUser );
        aString += '\t';

        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(mpDocShell->GetModel(), uno::UNO_QUERY_THROW);
        uno::Reference<document::XDocumentProperties> xDocProps = xDPS->getDocumentProperties();

        util::DateTime uDT(xDocProps->getModificationDate());
        Date d(uDT.Day, uDT.Month, uDT.Year);
        Time t(uDT.Hours, uDT.Minutes, uDT.Seconds, uDT.HundredthSeconds);
        DateTime aDateTime(d,t);

        aString += ScGlobal::pLocaleData->getDate( aDateTime );
        aString += ' ';
        aString += ScGlobal::pLocaleData->getTime( aDateTime, FALSE );

        maLbUsers.InsertEntry( aString, NULL );
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.3.34); FILE MERGED 2008/03/31 17:16:06 rt 1.3.34.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: sharedocdlg.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

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

#include <osl/security.hxx>
#include <svtools/sharecontrolfile.hxx>
#include <svtools/useroptions.hxx>

#include <docsh.hxx>

#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
#include <com/sun/star/document/XDocumentProperties.hpp>

#include "sharedocdlg.hxx"
#include "sharedocdlg.hrc"
#include "scresid.hxx"
#include "docsh.hxx"
#include "viewdata.hxx"

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

//=============================================================================
// class ScShareDocumentDlg
//=============================================================================

ScShareDocumentDlg::ScShareDocumentDlg( Window* pParent, ScViewData* pViewData )
    :ModalDialog( pParent, ScResId( RID_SCDLG_SHAREDOCUMENT ) )
    ,maCbShare            ( this, ScResId( CB_SHARE ) )
    ,maFtWarning          ( this, ScResId( FT_WARNING ) )
    ,maFlUsers            ( this, ScResId( FL_USERS ) )
    ,maFtUsers            ( this, ScResId( FT_USERS ) )
    ,maLbUsers            ( this, ScResId( LB_USERS ) )
    ,maFlEnd              ( this, ScResId( FL_END ) )
    ,maBtnHelp            ( this, ScResId( BTN_HELP ) )
    ,maBtnOK              ( this, ScResId( BTN_OK ) )
    ,maBtnCancel          ( this, ScResId( BTN_CANCEL ) )
    ,maStrTitleName       ( ScResId( STR_TITLE_NAME ) )
    ,maStrTitleAccessed   ( ScResId( STR_TITLE_ACCESSED ) )
    ,maStrNoUserData      ( ScResId( STR_NO_USER_DATA ) )
    ,maStrUnkownUser      ( ScResId( STR_UNKNOWN_USER ) )
    ,maStrExclusiveAccess ( ScResId( STR_EXCLUSIVE_ACCESS ) )
    ,mpViewData           ( pViewData )
    ,mpDocShell           ( NULL )
{
    DBG_ASSERT( mpViewData, "ScShareDocumentDlg CTOR: mpViewData is null!" );
    mpDocShell = ( mpViewData ? mpViewData->GetDocShell() : NULL );
    DBG_ASSERT( mpDocShell, "ScShareDocumentDlg CTOR: mpDocShell is null!" );

    FreeResource();

    bool bIsDocShared = ( mpDocShell ? mpDocShell->IsDocShared() : false );
    maCbShare.Check( bIsDocShared );
    maCbShare.SetToggleHdl( LINK( this, ScShareDocumentDlg, ToggleHandle ) );
    maFtWarning.Enable( bIsDocShared );

    long nTabs[] = { 2, 10, 122 };
    maLbUsers.SetTabs( nTabs );

    String aHeader( maStrTitleName );
    aHeader += '\t';
    aHeader += maStrTitleAccessed;
    maLbUsers.InsertHeaderEntry( aHeader, HEADERBAR_APPEND, HIB_LEFT | HIB_LEFTIMAGE | HIB_VCENTER );
    maLbUsers.SetSelectionMode( NO_SELECTION );

    UpdateView();
}

ScShareDocumentDlg::~ScShareDocumentDlg()
{
}

IMPL_LINK( ScShareDocumentDlg, ToggleHandle, void*, EMPTYARG )
{
    maFtWarning.Enable( maCbShare.IsChecked() );

    return 0;
}

bool ScShareDocumentDlg::IsShareDocumentChecked() const
{
    return maCbShare.IsChecked();
}

void ScShareDocumentDlg::UpdateView()
{
    if ( !mpDocShell )
    {
        return;
    }

    if ( mpDocShell->IsDocShared() )
    {
        try
        {
            ::svt::ShareControlFile aControlFile( mpDocShell->GetSharedFileUrl() );
            uno::Sequence< uno::Sequence< ::rtl::OUString > > aUsersData = aControlFile.GetUsersData();
            const uno::Sequence< ::rtl::OUString >* pUsersData = aUsersData.getConstArray();
            sal_Int32 nLength = aUsersData.getLength();

            if ( nLength > 0 )
            {
                sal_Int32 nUnknownUser = 1;

                for ( sal_Int32 i = 0; i < nLength; ++i )
                {
                    if ( pUsersData[i].getLength() != SHARED_ENTRYSIZE )
                    {
                        continue;
                    }

                    String aUser = pUsersData[i][SHARED_OOOUSERNAME_ID];
                    aUser.EraseLeadingAndTrailingChars();
                    if ( aUser.Len() == 0 )
                    {
                        aUser = pUsersData[i][SHARED_SYSUSERNAME_ID];
                        aUser.EraseLeadingAndTrailingChars();
                    }
                    if ( aUser.Len() == 0 )
                    {
                        aUser = maStrUnkownUser;
                        aUser += ' ';
                        aUser += String::CreateFromInt32( nUnknownUser++ );
                    }

                    String aDateTime = pUsersData[i][SHARED_EDITTIME_ID];

                    String aString( aUser );
                    aString += '\t';
                    aString += aDateTime;
                    maLbUsers.InsertEntry( aString, NULL );
                }
            }
            else
            {
                maLbUsers.InsertEntry( maStrNoUserData, NULL );
            }
        }
        catch ( uno::Exception& )
        {
            DBG_ERROR( "ScShareDocumentDlg::UpdateView(): caught exception\n" );
            maLbUsers.Clear();
            maLbUsers.InsertEntry( maStrNoUserData, NULL );
        }
    }
    else
    {
        // get OOO user name
        SvtUserOptions aUserOpt;
        String aUser = aUserOpt.GetFirstName();
        aUser += ' ';
        aUser += aUserOpt.GetLastName();
        aUser.EraseLeadingAndTrailingChars();
        if ( aUser.Len() == 0 )
        {
            // get sys user name
            ::rtl::OUString aUserName;
            ::osl::Security aSecurity;
            aSecurity.getUserName( aUserName );
            aUser = aUserName;
            aUser.EraseLeadingAndTrailingChars();
        }
        if ( aUser.Len() == 0 )
        {
            // unknown user name
            aUser = maStrUnkownUser;
        }
        aUser += ' ';
        aUser += maStrExclusiveAccess;
        String aString( aUser );
        aString += '\t';

        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(mpDocShell->GetModel(), uno::UNO_QUERY_THROW);
        uno::Reference<document::XDocumentProperties> xDocProps = xDPS->getDocumentProperties();

        util::DateTime uDT(xDocProps->getModificationDate());
        Date d(uDT.Day, uDT.Month, uDT.Year);
        Time t(uDT.Hours, uDT.Minutes, uDT.Seconds, uDT.HundredthSeconds);
        DateTime aDateTime(d,t);

        aString += ScGlobal::pLocaleData->getDate( aDateTime );
        aString += ' ';
        aString += ScGlobal::pLocaleData->getTime( aDateTime, FALSE );

        maLbUsers.InsertEntry( aString, NULL );
    }
}
<|endoftext|>


<commit_before>#pragma once

#include <experimental/optional>
#include <string>

enum class Color {
    grey = 2,
    black = 30,
    red = 31,
    green = 32,
    yellow = 33,
    blue = 34,
    magenta = 35,
    cyan = 36,
    light_grey = 37,
    dark_grey = 90,
    light_red = 91,
    light_green = 92,
    light_yellow = 93,
    light_blue = 94,
    light_magenta = 95,
    light_cyan = 96,
    white = 97
};

using Char = unsigned char;
using CharOpt = std::experimental::optional<Char>;
using StringOpt = std::experimental::optional<std::string>;
using ColorOpt = std::experimental::optional<Color>;

<commit_msg>Add reset color<commit_after>#pragma once

#include <experimental/optional>
#include <string>

enum class Color {
    reset = 0,
    grey = 2,
    black = 30,
    red = 31,
    green = 32,
    yellow = 33,
    blue = 34,
    magenta = 35,
    cyan = 36,
    light_grey = 37,
    dark_grey = 90,
    light_red = 91,
    light_green = 92,
    light_yellow = 93,
    light_blue = 94,
    light_magenta = 95,
    light_cyan = 96,
    white = 97
};

using Char = unsigned char;
using CharOpt = std::experimental::optional<Char>;
using StringOpt = std::experimental::optional<std::string>;
using ColorOpt = std::experimental::optional<Color>;

<|endoftext|>


<commit_before>#include "../coceditor/Context.h"
#include "../coceditor/COCCode.h"

#include <iostream>

#include <easybuilder.h>
#include <easycomplex.h>
#include <easyanim.h>
#include <easyscale9.h>
#include <easymesh.h>

#define CHARACTER

static void InitSymbolCreators()
{
	d2d::SymbolFactory::RegisterCreator(ecomplex::FILE_TAG, &ecomplex::Symbol::Create);
	d2d::SpriteFactory::Instance()->RegisterCreator(ecomplex::FILE_TAG, &ecomplex::Sprite::Create);

	d2d::SymbolFactory::RegisterCreator(eanim::FILE_TAG, &anim::Symbol::Create);
	d2d::SpriteFactory::Instance()->RegisterCreator(eanim::FILE_TAG, &anim::Sprite::Create);

	d2d::SymbolFactory::RegisterCreator(escale9::FILE_TAG, &escale9::Symbol::Create);
	d2d::SpriteFactory::Instance()->RegisterCreator(escale9::FILE_TAG, &escale9::Sprite::Create);

	d2d::SymbolFactory::RegisterCreator(emesh::FILE_TAG, &emesh::Symbol::Create);
	d2d::SpriteFactory::Instance()->RegisterCreator(emesh::FILE_TAG, &emesh::Sprite::Create);
}

void LoadAllFilesSorted(const std::string& dir, std::set<std::string>& files_sorted)
{
	wxArrayString files;
	d2d::FilenameTools::fetchAllFiles(dir, files);

	for (int i = 0, n = files.size(); i < n; ++i)
	{
		wxFileName filename(files[i]);
		filename.Normalize();
		wxString filepath = filename.GetFullPath();
		files_sorted.insert(filepath.ToStdString());
	}
}

void LoadFromDir(const std::string& dir)
{
	std::set<std::string> files_sorted;
	LoadAllFilesSorted(dir, files_sorted);

	try {
		std::set<std::string>::iterator itr = files_sorted.begin();
		for ( ; itr != files_sorted.end(); ++itr)
		{
			if (d2d::FileNameParser::isType(*itr, d2d::FileNameParser::e_complex)
				|| d2d::FileNameParser::isType(*itr, d2d::FileNameParser::e_anim))
			{
				// todo release symbol
				d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(*itr);
				coceditor::Context::Instance()->symbols.push_back(symbol);
			}
		}
	} catch (d2d::Exception& e) {
		std::cerr << e.what() << std::endl;
	}
}

void LoadFromList(const std::string& list)
{
	std::set<std::string> names;

	wxString ext = d2d::FilenameTools::getExtension(list).Lower();
	if (ext == "txt")
	{
		std::locale::global(std::locale(""));
		std::ifstream fin(list.c_str());
		std::locale::global(std::locale("C"));

		std::string str;
		while (getline(fin, str)) {
			names.insert(str);
		}

		fin.close();
	}
	else if (ext == "json")
	{
		Json::Value value;
		Json::Reader reader;
		std::locale::global(std::locale(""));
		std::ifstream fin(list.c_str());
		std::locale::global(std::locale("C"));
		reader.parse(fin, value);
		fin.close();

		int i = 0;
		Json::Value itemValue = value["items"][i++];
		while (!itemValue.isNull()) {
			std::string name = itemValue["name"].asString();
			names.insert(name);
			itemValue = value["items"][i++];
		}
	}
	else
	{
		std::cerr << "unsupported format " << ext << std::endl;
		return;
	}

	wxString dir = d2d::FilenameTools::getFileDir(list);

	std::set<std::string> files_sorted;
	LoadAllFilesSorted(dir.ToStdString(), files_sorted);

	try {
		std::set<std::string>::iterator itr = files_sorted.begin();
		for ( ; itr != files_sorted.end(); ++itr)
		{
			if (d2d::FileNameParser::isType(*itr, d2d::FileNameParser::e_complex)
				|| d2d::FileNameParser::isType(*itr, d2d::FileNameParser::e_anim))
			{
				// todo release symbol
				d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(*itr);
				std::set<std::string>::iterator itr = names.find(symbol->name);
				if (itr == names.end()) {
					symbol->release();
				} else {
					coceditor::Context::Instance()->symbols.push_back(symbol);
				}
			}
		}
	} catch (d2d::Exception& e) {
		std::cerr << e.what() << std::endl;
	}
}

void LoadTexturePacker(std::string texpackerpath)
{
	size_t i = 1;
	while (true)
	{
		std::string path = texpackerpath + wxString::FromDouble(i) + ".json";
		if (wxFileName::FileExists(path))
			coceditor::Context::Instance()->texMgr.initTexture(path, i-1);
		else
			break;
		++i;
	}
}

void DetectScale(int idx, char *argv[], float& scale)
{
	std::string opt = argv[idx];
	if (opt == "-s" || opt == "--scale") {
		scale = atof(argv[idx+1]);
	}
}

void DetectIgnoreFile(int idx, char *argv[], std::string& ignore_file)
{
	std::string opt = argv[idx];
	if (opt == "-i" || opt == "--ignore") {
		ignore_file = argv[idx+1];
	}
}

void ParamsDetection(int argc, char *argv[], float& scale, std::string& ignore_file)
{
	for (int i = 4; i < argc; i += 2)
	{
		DetectScale(i, argv, scale);
		DetectIgnoreFile(i, argv, ignore_file);
	}
}

void LoadIgnoreList(const std::string& filename)
{
	wxString ext = d2d::FilenameTools::getExtension(filename).Lower();

	std::set<std::string> list;

	std::locale::global(std::locale(""));
	std::ifstream fin(filename.c_str());
	std::locale::global(std::locale("C"));

	std::string str;
	while (getline(fin, str)) {
		list.insert(str);
	}

	fin.close();

	coceditor::Context::Instance()->ignore_list = list;
}

int main(int argc, char *argv[])
{
	if (argc < 4) {
		std::cerr << "Need Resource Dir & Texture Packer Filepath & Output filepath !" << std::endl;
		return 1;
	}

	InitSymbolCreators();

	float gscale = 1.0f;
	std::string ignore_file;
	if (argc > 4) {
		ParamsDetection(argc, argv, gscale, ignore_file);
	}
	if (!ignore_file.empty()) {
		LoadIgnoreList(ignore_file);
	}

	std::string path = argv[1];
	bool is_dir = false;
	int pos_dot = path.find_last_of('.');
	int pos_divide = std::max((int)path.find_last_of('/'), (int)path.find_last_of('\\'));
	if (pos_dot == std::string::npos || pos_dot < pos_divide) {
		is_dir = true;
	}
	if (is_dir) {
		LoadFromDir(path);
	} else {
		LoadFromList(path);
	}

	std::string texpackerpath = argv[2];
	LoadTexturePacker(texpackerpath);

	try {
		ebuilder::CodeGenerator gen;
		coceditor::COCCode code(gen, gscale);
		code.Parser();
		std::locale::global(std::locale(""));
		std::ofstream fout(argv[3]);
		std::locale::global(std::locale("C"));
		fout << gen.toText() << std::endl;
		fout.close();
	} catch (d2d::Exception& e) {
		std::cerr << e.what() << std::endl;
	}

	return 0;
}<commit_msg>[TODO]内存泄露。临时注释掉，提高cocpack速度<commit_after>#include "../coceditor/Context.h"
#include "../coceditor/COCCode.h"

#include <iostream>

#include <easybuilder.h>
#include <easycomplex.h>
#include <easyanim.h>
#include <easyscale9.h>
#include <easymesh.h>

#define CHARACTER

static void InitSymbolCreators()
{
	d2d::SymbolFactory::RegisterCreator(ecomplex::FILE_TAG, &ecomplex::Symbol::Create);
	d2d::SpriteFactory::Instance()->RegisterCreator(ecomplex::FILE_TAG, &ecomplex::Sprite::Create);

	d2d::SymbolFactory::RegisterCreator(eanim::FILE_TAG, &anim::Symbol::Create);
	d2d::SpriteFactory::Instance()->RegisterCreator(eanim::FILE_TAG, &anim::Sprite::Create);

	d2d::SymbolFactory::RegisterCreator(escale9::FILE_TAG, &escale9::Symbol::Create);
	d2d::SpriteFactory::Instance()->RegisterCreator(escale9::FILE_TAG, &escale9::Sprite::Create);

	d2d::SymbolFactory::RegisterCreator(emesh::FILE_TAG, &emesh::Symbol::Create);
	d2d::SpriteFactory::Instance()->RegisterCreator(emesh::FILE_TAG, &emesh::Sprite::Create);
}

void LoadAllFilesSorted(const std::string& dir, std::set<std::string>& files_sorted)
{
	wxArrayString files;
	d2d::FilenameTools::fetchAllFiles(dir, files);

	for (int i = 0, n = files.size(); i < n; ++i)
	{
		wxFileName filename(files[i]);
		filename.Normalize();
		wxString filepath = filename.GetFullPath();
		files_sorted.insert(filepath.ToStdString());
	}
}

void LoadFromDir(const std::string& dir)
{
	std::set<std::string> files_sorted;
	LoadAllFilesSorted(dir, files_sorted);

	try {
		std::set<std::string>::iterator itr = files_sorted.begin();
		for ( ; itr != files_sorted.end(); ++itr)
		{
			if (d2d::FileNameParser::isType(*itr, d2d::FileNameParser::e_complex)
				|| d2d::FileNameParser::isType(*itr, d2d::FileNameParser::e_anim))
			{
				// todo release symbol
				d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(*itr);
				coceditor::Context::Instance()->symbols.push_back(symbol);
			}
		}
	} catch (d2d::Exception& e) {
		std::cerr << e.what() << std::endl;
	}
}

void LoadFromList(const std::string& list)
{
	std::set<std::string> names;

	wxString ext = d2d::FilenameTools::getExtension(list).Lower();
	if (ext == "txt")
	{
		std::locale::global(std::locale(""));
		std::ifstream fin(list.c_str());
		std::locale::global(std::locale("C"));

		std::string str;
		while (getline(fin, str)) {
			names.insert(str);
		}

		fin.close();
	}
	else if (ext == "json")
	{
		Json::Value value;
		Json::Reader reader;
		std::locale::global(std::locale(""));
		std::ifstream fin(list.c_str());
		std::locale::global(std::locale("C"));
		reader.parse(fin, value);
		fin.close();

		int i = 0;
		Json::Value itemValue = value["items"][i++];
		while (!itemValue.isNull()) {
			std::string name = itemValue["name"].asString();
			names.insert(name);
			itemValue = value["items"][i++];
		}
	}
	else
	{
		std::cerr << "unsupported format " << ext << std::endl;
		return;
	}

	wxString dir = d2d::FilenameTools::getFileDir(list);

	std::set<std::string> files_sorted;
	LoadAllFilesSorted(dir.ToStdString(), files_sorted);

	try {
		std::set<std::string>::iterator itr = files_sorted.begin();
		for ( ; itr != files_sorted.end(); ++itr)
		{
			if (d2d::FileNameParser::isType(*itr, d2d::FileNameParser::e_complex)
				|| d2d::FileNameParser::isType(*itr, d2d::FileNameParser::e_anim))
			{
				// todo release symbol
				d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(*itr);
				std::set<std::string>::iterator itr = names.find(symbol->name);
				if (itr == names.end()) {
//					symbol->release();
				} else {
					coceditor::Context::Instance()->symbols.push_back(symbol);
				}
			}
		}
	} catch (d2d::Exception& e) {
		std::cerr << e.what() << std::endl;
	}
}

void LoadTexturePacker(std::string texpackerpath)
{
	size_t i = 1;
	while (true)
	{
		std::string path = texpackerpath + wxString::FromDouble(i) + ".json";
		if (wxFileName::FileExists(path))
			coceditor::Context::Instance()->texMgr.initTexture(path, i-1);
		else
			break;
		++i;
	}
}

void DetectScale(int idx, char *argv[], float& scale)
{
	std::string opt = argv[idx];
	if (opt == "-s" || opt == "--scale") {
		scale = atof(argv[idx+1]);
	}
}

void DetectIgnoreFile(int idx, char *argv[], std::string& ignore_file)
{
	std::string opt = argv[idx];
	if (opt == "-i" || opt == "--ignore") {
		ignore_file = argv[idx+1];
	}
}

void ParamsDetection(int argc, char *argv[], float& scale, std::string& ignore_file)
{
	for (int i = 4; i < argc; i += 2)
	{
		DetectScale(i, argv, scale);
		DetectIgnoreFile(i, argv, ignore_file);
	}
}

void LoadIgnoreList(const std::string& filename)
{
	wxString ext = d2d::FilenameTools::getExtension(filename).Lower();

	std::set<std::string> list;

	std::locale::global(std::locale(""));
	std::ifstream fin(filename.c_str());
	std::locale::global(std::locale("C"));

	std::string str;
	while (getline(fin, str)) {
		list.insert(str);
	}

	fin.close();

	coceditor::Context::Instance()->ignore_list = list;
}

int main(int argc, char *argv[])
{
	if (argc < 4) {
		std::cerr << "Need Resource Dir & Texture Packer Filepath & Output filepath !" << std::endl;
		return 1;
	}

	InitSymbolCreators();

	float gscale = 1.0f;
	std::string ignore_file;
	if (argc > 4) {
		ParamsDetection(argc, argv, gscale, ignore_file);
	}
	if (!ignore_file.empty()) {
		LoadIgnoreList(ignore_file);
	}

	std::string path = argv[1];
	bool is_dir = false;
	int pos_dot = path.find_last_of('.');
	int pos_divide = std::max((int)path.find_last_of('/'), (int)path.find_last_of('\\'));
	if (pos_dot == std::string::npos || pos_dot < pos_divide) {
		is_dir = true;
	}
	if (is_dir) {
		LoadFromDir(path);
	} else {
		LoadFromList(path);
	}

	std::string texpackerpath = argv[2];
	LoadTexturePacker(texpackerpath);

	try {
		ebuilder::CodeGenerator gen;
		coceditor::COCCode code(gen, gscale);
		code.Parser();
		std::locale::global(std::locale(""));
		std::ofstream fout(argv[3]);
		std::locale::global(std::locale("C"));
		fout << gen.toText() << std::endl;
		fout.close();
	} catch (d2d::Exception& e) {
		std::cerr << e.what() << std::endl;
	}

	return 0;
}<|endoftext|>


<commit_before>/*
 *  cam_INI.cpp
 *  PHD Guiding
 *
 *  Created by Geoffrey Hausheer.
 *  Copyright (c) 2009 Geoffrey Hausheer.
 *  All rights reserved.
 *
 *  This source code is distrubted under the following "BSD" license
 *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *    Neither the name of Craig Stark, Stark Labs nor the names of its contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 *  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "phd.h"
#include "camera.h"
#include "time.h"
#include "image_math.h"
#include "cam_INDI.h"

#include "libindiclient/indi.h"
#include "libindiclient/indigui.h"

extern long INDIport;
extern wxString INDIhost;
extern struct indi_t *INDIClient;

void camera_capture_cb(struct indi_prop_t *iprop, void *data)
{
    Camera_INDIClass *cb = (Camera_INDIClass *)(data);
    cb->blob_elem = indi_find_first_elem(iprop);
    indi_dev_enable_blob(iprop->idev, FALSE);
    printf("Got camera callback\n");
    cb->modal = false;
}

Camera_INDIClass::Camera_INDIClass() {
    Connected = FALSE;
    Name=_T("INDI Camera");
    HasPropertyDialog = true;
    FullSize = wxSize(640,480);
}

static int modal_timeout_cb(void * data)
{
    Camera_INDIClass *cb = (Camera_INDIClass *)(data);
    if(cb->modal) {
        cb->modal = false;
    }
    return FALSE;
}
static void connect_cb(struct indi_prop_t *iprop, void *data)
{
    Camera_INDIClass *cb = (Camera_INDIClass *)(data);
    cb->is_connected = (iprop->state == INDI_STATE_IDLE || iprop->state == INDI_STATE_OK) && indi_prop_get_switch(iprop, "CONNECT");
    printf("Camera connected state: %d\n", cb->is_connected);
    cb->CheckState();
}

static void new_prop_cb(struct indi_prop_t *iprop, void *callback_data)
{
    Camera_INDIClass *cb = (Camera_INDIClass *)(callback_data);
    return cb->NewProp(iprop);
}

void Camera_INDIClass::CheckState()
{
    if(has_blob && is_connected && expose_prop) {
        if (! ready) {
            printf("Camera is ready\n");
            ready = true;
            if (modal) {
                modal = false;
            }
        }
    }
}

void Camera_INDIClass::NewProp(struct indi_prop_t *iprop)
{
    /* property to set exposure */
    if (iprop->type == INDI_PROP_BLOB) {
        printf("Found BLOB property for camera %s\n", iprop->idev->name);
        has_blob = 1;
        indi_prop_add_cb(iprop, camera_capture_cb, this);
    }
    else if (strcmp(iprop->name, "CCD_EXPOSURE") == 0) {
        printf("Found CCD_EXPOSURE for camera %s\n", iprop->idev->name);
        expose_prop = iprop;
    }
    else if (strcmp(iprop->name, "CCD_FRAME") == 0) {
        printf("Found CCD_FRAME for camera %s\n", iprop->idev->name);
        frame_prop = iprop;
    }
    else if (strcmp(iprop->name, "CCD_FRAME_TYPE") == 0) {
        printf("Found CCD_FRAME_TYPE for camera %s\n", iprop->idev->name);
        frame_type_prop = iprop;
    }
    else if (strcmp(iprop->name, "CCD_BINNING") == 0) {
        printf("Found CCD_BINNING for camera %s\n", iprop->idev->name);
        binning_prop = iprop;
    }
    else if (strcmp(iprop->name, "VIDEO_STREAM") == 0) {
        printf("Found Video Camera %s\n", iprop->idev->name);
        video_prop = iprop;
    }
    else if (strcmp(iprop->name, "DEVICE_PORT") == 0 && indi_port.Length()) {
        indi_send(iprop, indi_prop_set_string(iprop, "PORT", indi_port.ToAscii()));
        indi_dev_set_switch(iprop->idev, "CONNECTION", "CONNECT", TRUE);
    }
    else if (strcmp(iprop->name, "CONNECTION") == 0) {
        printf("Found CONNECTION for camera %s\n", iprop->idev->name);
        indi_send(iprop, indi_prop_set_switch(iprop, "CONNECT", TRUE));
        indi_prop_add_cb(iprop, connect_cb, this);
    }
    CheckState();
}

bool Camera_INDIClass::Connect() {
    wxLongLong msec;
    if (! INDIClient) {
        INDIClient = indi_init(INDIhost.ToAscii(), INDIport, "PHDGuiding");
        if (! INDIClient) {
            return true;
        }
    }
    if (indi_name.IsEmpty()) {
        printf("No INDI camera is set.  Please set INDIcam in the preferences file\n");
        return true;
    }
    indi_device_add_cb(INDIClient, indi_name.ToAscii(), new_prop_cb, this);

    modal = true;
    msec = wxGetLocalTimeMillis();
    while(modal && wxGetLocalTimeMillis() - msec < 10 * 1000) {
        ::wxSafeYield();
    }
    modal = false;

    if(! ready)
        return true;
    return false;

}

bool Camera_INDIClass::Disconnect() {
    Connected = FALSE;
    CurrentGuideCamera = NULL;
    GuideCameraConnected = false;
    return false;
}

void Camera_INDIClass::ShowPropertyDialog() {
    indigui_show_dialog(INDIClient);
}

#if defined (__WINDOWS__)
#include "../fits/fitsio.h"
#elsif defined (__APPLE__)
#include "../cfitsio/fitsio.h"
#else
#include <fitsio.h>
#endif

bool Camera_INDIClass::ReadFITS(usImage& img) {
    int xsize, ysize;
    fitsfile *fptr;  // FITS file pointer
    int status = 0;  // CFITSIO status value MUST be initialized to zero!
    int hdutype, naxis;
    int nhdus=0;
    long fits_size[2];
    long fpixel[3] = {1,1,1};

    if (fits_open_memfile(&fptr,
            "",
            READONLY,
            ((void **)(&blob_elem->value.blob.data)),
            &(blob_elem->value.blob.size),
            0,
            NULL,
            &status) )
    {
        (void) wxMessageBox(wxT("Unsupported type or read error loading FITS file"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    if (fits_get_hdu_type(fptr, &hdutype, &status) || hdutype != IMAGE_HDU) {
        (void) wxMessageBox(wxT("FITS file is not of an image"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }

    // Get HDUs and size
    fits_get_img_dim(fptr, &naxis, &status);
    fits_get_img_size(fptr, 2, fits_size, &status);
    xsize = (int) fits_size[0];
    ysize = (int) fits_size[1];
    fits_get_num_hdus(fptr,&nhdus,&status);
    if ((nhdus != 1) || (naxis != 2)) {
        (void) wxMessageBox(wxT("Unsupported type or read error loading FITS file"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    if (img.Init(xsize,ysize)) {
        wxMessageBox(wxT("Memory allocation error"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    if (fits_read_pix(fptr, TUSHORT, fpixel, xsize*ysize, NULL, img.ImageData, NULL, &status) ) { // Read image
        (void) wxMessageBox(wxT("Error reading data"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    fits_close_file(fptr,&status);
    return false;
}

bool Camera_INDIClass::ReadStream(usImage& img) {
    int xsize, ysize;
    unsigned char *inptr;
    unsigned short *outptr;
    struct indi_elem_t *elem;

    if (! frame_prop) {
        wxMessageBox(wxT("Failed to determine image dimensions"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    if (! (elem = indi_find_elem(frame_prop, "WIDTH"))) {
        wxMessageBox(wxT("Failed to determine image dimensions"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    xsize = elem->value.num.value;
    if (! (elem = indi_find_elem(frame_prop, "HEIGHT"))) {
        wxMessageBox(wxT("Failed to determine image dimensions"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    ysize = elem->value.num.value;
    if (img.Init(xsize,ysize)) {
        wxMessageBox(wxT("Memory allocation error"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    outptr = img.ImageData;
    inptr = (unsigned char *)blob_elem->value.blob.data;
    for (int i = 0; i < xsize * ysize; i++)
        *outptr ++ = *inptr++;
    return false;
}

bool Camera_INDIClass::CaptureFull(int duration, usImage& img, bool recon) {
//    unsigned short *dataptr;
//    int i;

    indi_dev_enable_blob(expose_prop->idev, TRUE);
    if (video_prop) {
        printf("Enabling video capture\n");
        indi_send(video_prop, indi_prop_set_switch(video_prop, "ON", TRUE));
    } else {
        printf("Exposing for %d(ms)\n", duration);
        indi_prop_set_number(expose_prop, "CCD_EXPOSURE_VALUE", duration / 1000.0);
        indi_send(expose_prop, NULL);
    }
    modal = true;
    while (modal) {
	wxTheApp->Yield();
    }
    if (video_prop) {
        indi_send(video_prop, indi_prop_set_switch(video_prop, "OFF", TRUE));
    }

    if (strncmp(".fits",blob_elem->value.blob.fmt, 5) == 0) {
        printf("Processing fits file\n");
        return ReadFITS(img);
    } else if (strncmp(".stream", blob_elem->value.blob.fmt, 7) == 0) {
        printf("Processing strean file\n");
        return ReadStream(img);
    } else {
        wxMessageBox(wxT("Unknown image format: ") + wxString::FromAscii(blob_elem->value.blob.fmt),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
}

<commit_msg>Try to use FITS for video cameras<commit_after>/*
 *  cam_INI.cpp
 *  PHD Guiding
 *
 *  Created by Geoffrey Hausheer.
 *  Copyright (c) 2009 Geoffrey Hausheer.
 *  All rights reserved.
 *
 *  This source code is distrubted under the following "BSD" license
 *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *    Neither the name of Craig Stark, Stark Labs nor the names of its contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 *  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "phd.h"
#include "camera.h"
#include "time.h"
#include "image_math.h"
#include "cam_INDI.h"

#include "libindiclient/indi.h"
#include "libindiclient/indigui.h"

extern long INDIport;
extern wxString INDIhost;
extern struct indi_t *INDIClient;

void camera_capture_cb(struct indi_prop_t *iprop, void *data)
{
    Camera_INDIClass *cb = (Camera_INDIClass *)(data);
    cb->blob_elem = indi_find_first_elem(iprop);
    indi_dev_enable_blob(iprop->idev, FALSE);
    printf("Got camera callback\n");
    cb->modal = false;
}

Camera_INDIClass::Camera_INDIClass() {
    Connected = FALSE;
    Name=_T("INDI Camera");
    HasPropertyDialog = true;
    FullSize = wxSize(640,480);
}

static int modal_timeout_cb(void * data)
{
    Camera_INDIClass *cb = (Camera_INDIClass *)(data);
    if(cb->modal) {
        cb->modal = false;
    }
    return FALSE;
}
static void connect_cb(struct indi_prop_t *iprop, void *data)
{
    Camera_INDIClass *cb = (Camera_INDIClass *)(data);
    cb->is_connected = (iprop->state == INDI_STATE_IDLE || iprop->state == INDI_STATE_OK) && indi_prop_get_switch(iprop, "CONNECT");
    printf("Camera connected state: %d\n", cb->is_connected);
    cb->CheckState();
}

static void new_prop_cb(struct indi_prop_t *iprop, void *callback_data)
{
    Camera_INDIClass *cb = (Camera_INDIClass *)(callback_data);
    return cb->NewProp(iprop);
}

void Camera_INDIClass::CheckState()
{
    if(has_blob && is_connected && (expose_prop || video_prop)) {
        if (! ready) {
            printf("Camera is ready\n");
            ready = true;
            if (modal) {
                modal = false;
            }
        }
    }
}

void Camera_INDIClass::NewProp(struct indi_prop_t *iprop)
{
    /* property to set exposure */
    if (iprop->type == INDI_PROP_BLOB) {
        printf("Found BLOB property for camera %s\n", iprop->idev->name);
        has_blob = 1;
        indi_prop_add_cb(iprop, camera_capture_cb, this);
    }
    else if (strcmp(iprop->name, "CCD_EXPOSURE") == 0) {
        printf("Found CCD_EXPOSURE for camera %s\n", iprop->idev->name);
        expose_prop = iprop;
    }
    else if (strcmp(iprop->name, "CCD_FRAME") == 0) {
        printf("Found CCD_FRAME for camera %s\n", iprop->idev->name);
        frame_prop = iprop;
    }
    else if (strcmp(iprop->name, "CCD_FRAME_TYPE") == 0) {
        printf("Found CCD_FRAME_TYPE for camera %s\n", iprop->idev->name);
        frame_type_prop = iprop;
    }
    else if (strcmp(iprop->name, "CCD_BINNING") == 0) {
        printf("Found CCD_BINNING for camera %s\n", iprop->idev->name);
        binning_prop = iprop;
    }
    else if (strcmp(iprop->name, "VIDEO_STREAM") == 0) {
        printf("Found Video Camera %s\n", iprop->idev->name);
        video_prop = iprop;
    }
    else if (strcmp(iprop->name, "DEVICE_PORT") == 0 && indi_port.Length()) {
        indi_send(iprop, indi_prop_set_string(iprop, "PORT", indi_port.ToAscii()));
        indi_dev_set_switch(iprop->idev, "CONNECTION", "CONNECT", TRUE);
    }
    else if (strcmp(iprop->name, "CONNECTION") == 0) {
        printf("Found CONNECTION for camera %s\n", iprop->idev->name);
        indi_send(iprop, indi_prop_set_switch(iprop, "CONNECT", TRUE));
        indi_prop_add_cb(iprop, connect_cb, this);
    }
    CheckState();
}

bool Camera_INDIClass::Connect() {
    wxLongLong msec;
    if (! INDIClient) {
        INDIClient = indi_init(INDIhost.ToAscii(), INDIport, "PHDGuiding");
        if (! INDIClient) {
            return true;
        }
    }
    if (indi_name.IsEmpty()) {
        printf("No INDI camera is set.  Please set INDIcam in the preferences file\n");
        return true;
    }
    indi_device_add_cb(INDIClient, indi_name.ToAscii(), new_prop_cb, this);

    modal = true;
    msec = wxGetLocalTimeMillis();
    while(modal && wxGetLocalTimeMillis() - msec < 10 * 1000) {
        ::wxSafeYield();
    }
    modal = false;

    if(! ready)
        return true;
    return false;

}

bool Camera_INDIClass::Disconnect() {
    Connected = FALSE;
    CurrentGuideCamera = NULL;
    GuideCameraConnected = false;
    return false;
}

void Camera_INDIClass::ShowPropertyDialog() {
    indigui_show_dialog(INDIClient);
}

#if defined (__WINDOWS__)
#include "../fits/fitsio.h"
#elsif defined (__APPLE__)
#include "../cfitsio/fitsio.h"
#else
#include <fitsio.h>
#endif

bool Camera_INDIClass::ReadFITS(usImage& img) {
    int xsize, ysize;
    fitsfile *fptr;  // FITS file pointer
    int status = 0;  // CFITSIO status value MUST be initialized to zero!
    int hdutype, naxis;
    int nhdus=0;
    long fits_size[2];
    long fpixel[3] = {1,1,1};

    if (fits_open_memfile(&fptr,
            "",
            READONLY,
            ((void **)(&blob_elem->value.blob.data)),
            &(blob_elem->value.blob.size),
            0,
            NULL,
            &status) )
    {
        (void) wxMessageBox(wxT("Unsupported type or read error loading FITS file"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    if (fits_get_hdu_type(fptr, &hdutype, &status) || hdutype != IMAGE_HDU) {
        (void) wxMessageBox(wxT("FITS file is not of an image"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }

    // Get HDUs and size
    fits_get_img_dim(fptr, &naxis, &status);
    fits_get_img_size(fptr, 2, fits_size, &status);
    xsize = (int) fits_size[0];
    ysize = (int) fits_size[1];
    fits_get_num_hdus(fptr,&nhdus,&status);
    if ((nhdus != 1) || (naxis != 2)) {
        (void) wxMessageBox(wxT("Unsupported type or read error loading FITS file"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    if (img.Init(xsize,ysize)) {
        wxMessageBox(wxT("Memory allocation error"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    if (fits_read_pix(fptr, TUSHORT, fpixel, xsize*ysize, NULL, img.ImageData, NULL, &status) ) { // Read image
        (void) wxMessageBox(wxT("Error reading data"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    fits_close_file(fptr,&status);
    return false;
}

bool Camera_INDIClass::ReadStream(usImage& img) {
    int xsize, ysize;
    unsigned char *inptr;
    unsigned short *outptr;
    struct indi_elem_t *elem;

    if (! frame_prop) {
        wxMessageBox(wxT("Failed to determine image dimensions"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    if (! (elem = indi_find_elem(frame_prop, "WIDTH"))) {
        wxMessageBox(wxT("Failed to determine image dimensions"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    xsize = elem->value.num.value;
    if (! (elem = indi_find_elem(frame_prop, "HEIGHT"))) {
        wxMessageBox(wxT("Failed to determine image dimensions"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    ysize = elem->value.num.value;
    if (img.Init(xsize,ysize)) {
        wxMessageBox(wxT("Memory allocation error"),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
    outptr = img.ImageData;
    inptr = (unsigned char *)blob_elem->value.blob.data;
    for (int i = 0; i < xsize * ysize; i++)
        *outptr ++ = *inptr++;
    return false;
}

bool Camera_INDIClass::CaptureFull(int duration, usImage& img, bool recon) {
//    unsigned short *dataptr;
//    int i;

    if (expose_prop) {
        printf("Exposing for %d(ms)\n", duration);
        indi_dev_enable_blob(expose_prop->idev, TRUE);
        indi_prop_set_number(expose_prop, "CCD_EXPOSURE_VALUE", duration / 1000.0);
        indi_send(expose_prop, NULL);
    } else {
        printf("Enabling video capture\n");
        indi_dev_enable_blob(expose_prop->idev, TRUE);
        indi_send(video_prop, indi_prop_set_switch(video_prop, "ON", TRUE));
    }
    modal = true;
    while (modal) {
	wxTheApp->Yield();
    }
    if (! expose_prop) {
        indi_send(video_prop, indi_prop_set_switch(video_prop, "OFF", TRUE));
    }

    if (strncmp(".fits",blob_elem->value.blob.fmt, 5) == 0) {
        printf("Processing fits file\n");
        return ReadFITS(img);
    } else if (strncmp(".stream", blob_elem->value.blob.fmt, 7) == 0) {
        printf("Processing strean file\n");
        return ReadStream(img);
    } else {
        wxMessageBox(wxT("Unknown image format: ") + wxString::FromAscii(blob_elem->value.blob.fmt),wxT("Error"),wxOK | wxICON_ERROR);
        return true;
    }
}

<|endoftext|>