<commit_before>#include <stdio.h>
#include <ctype.h>
#include <iostream>
#include <fstream>
#include <string>

#include <metaUtils.h>
#include <metaObject.h>
#include <metaLine.h>

//
// MetaLine Constructors
//
MetaLine::
MetaLine()
:MetaObject()
{
  if(META_DEBUG) std::cout << "MetaLine()" << std::endl;
  Clear();
}

//
MetaLine::
MetaLine(const char *_headerName)
:MetaObject(_headerName)
{
  if(META_DEBUG)  std::cout << "MetaLine()" << std::endl;
  Clear();
  Read(_headerName);
}

//
MetaLine::
MetaLine(const MetaLine *_line)
:MetaObject()
{
  if(META_DEBUG)  std::cout << "MetaLine()" << std::endl;
  Clear();
  CopyInfo(_line);
}

//
MetaLine::
MetaLine(unsigned int dim)
:MetaObject(dim)
{
  if(META_DEBUG) std::cout << "MetaLine()" << std::endl;
  Clear();
}

//
MetaLine::
~MetaLine()
{
  Clear();
  M_Destroy();
}

//
void MetaLine::
PrintInfo() const
{
  MetaObject::PrintInfo();
  std::cout << "PointDim = " << m_PointDim << std::endl;
  std::cout << "NPoints = " << m_NPoints << std::endl;
  char str[255];
  MET_TypeToString(m_ElementType, str);
  std::cout << "ElementType = " << str << std::endl;
}

void MetaLine::
CopyInfo(const MetaLine * _line)
{
  MetaObject::CopyInfo(_line);
}

void MetaLine::
PointDim(const char* pointDim)
{
  strcpy(m_PointDim,pointDim);
}

const char* MetaLine::
PointDim(void) const
{
  return m_PointDim;
}

void MetaLine::
NPoints(int npnt)
{
  m_NPoints = npnt;
}

int MetaLine::
NPoints(void) const
{
  return m_NPoints;
}

/** Clear line information */
void MetaLine::
Clear(void)
{
  if(META_DEBUG) std::cout << "MetaLine: Clear" << std::endl;
  MetaObject::Clear();
  m_NPoints = 0;
    // Delete the list of pointers to lines.
  PointListType::iterator it = m_PointList.begin();
  while(it != m_PointList.end())
  {
    LinePnt* pnt = *it;
    it++;
    delete pnt;
  }
  m_PointList.clear();

  strcpy(m_PointDim, "x y z v1x v1y v1z");
  m_ElementType = MET_FLOAT;
}

/** Destroy line information */
void MetaLine::
M_Destroy(void)
{
  MetaObject::M_Destroy();
}

/** Set Read fields */
void MetaLine::
M_SetupReadFields(void)
{
  if(META_DEBUG) std::cout << "MetaLine: M_SetupReadFields" << std::endl;

  MetaObject::M_SetupReadFields();

  MET_FieldRecordType * mF;

  //int nDimsRecNum = MET_GetFieldRecordNumber("NDims", &m_Fields);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "PointDim", MET_STRING, true);
  m_Fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NPoints", MET_INT, true);
  m_Fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "ElementType", MET_STRING, true);
  mF->required = true;
  m_Fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Points", MET_NONE, true);
  mF->terminateRead = true;
  m_Fields.push_back(mF);

}

void MetaLine::
M_SetupWriteFields(void)
{
  strcpy(m_ObjectTypeName,"Line");
  MetaObject::M_SetupWriteFields();

  MET_FieldRecordType * mF;

  char s[255];
  mF = new MET_FieldRecordType;
  MET_TypeToString(m_ElementType, s);
  MET_InitWriteField(mF, "ElementType", MET_STRING, strlen(s), s);
  m_Fields.push_back(mF);

  if(strlen(m_PointDim)>0)
  {
    mF = new MET_FieldRecordType;
    MET_InitWriteField(mF, "PointDim", MET_STRING,
                           strlen(m_PointDim),m_PointDim);
    m_Fields.push_back(mF);
  }

  m_NPoints = m_PointList.size();
  mF = new MET_FieldRecordType;
  MET_InitWriteField(mF, "NPoints", MET_INT,m_NPoints);
  m_Fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitWriteField(mF, "Points", MET_NONE);
  m_Fields.push_back(mF);

}

MET_ValueEnumType MetaLine::
ElementType(void) const
{
  return m_ElementType;
}

void MetaLine::
ElementType(MET_ValueEnumType _elementType)
{
  m_ElementType = _elementType;
}

bool MetaLine::
M_Read(void)
{
  if(META_DEBUG) std::cout << "MetaLine: M_Read: Loading Header" << std::endl;

  if(!MetaObject::M_Read())
  {
    std::cout << "MetaLine: M_Read: Error parsing file" << std::endl;
    return false;
  }

  if(META_DEBUG) std::cout << "MetaLine: M_Read: Parsing Header" << std::endl;

  MET_FieldRecordType * mF;

  mF = MET_GetFieldRecord("NPoints", &m_Fields);
  if(mF->defined)
  {
    m_NPoints= (int)mF->value[0];
  }

  mF = MET_GetFieldRecord("ElementType", &m_Fields);
  if(mF->defined)
  {
    MET_StringToType((char *)(mF->value), &m_ElementType);
  }

  mF = MET_GetFieldRecord("PointDim", &m_Fields);
  if(mF->defined)
  {
    strcpy(m_PointDim,(char *)(mF->value));
  }

  int pntDim;
  char** pntVal = NULL;
  MET_StringToWordArray(m_PointDim, &pntDim, &pntVal);

  int i;
  for(i=0;i<pntDim;i++)
    {
      delete [] pntVal[i];
    }
  delete [] pntVal;

  float v[16];

  if(m_BinaryData)
  {
    int elementSize;
    MET_SizeOfType(m_ElementType, &elementSize);
    int readSize = m_NPoints*(m_NDims*m_NDims+4)*elementSize;

    char* _data = new char[readSize];
    m_ReadStream->read((char *)_data, readSize);

    int gc = m_ReadStream->gcount();
    if(gc != readSize)
    {
      std::cout << "MetaLine: m_Read: data not read completely"
                << std::endl;
      std::cout << "   ideal = " << readSize << " : actual = " << gc << std::endl;
      return false;
    }

    i=0;
    double td;
    int d;
    for(int j=0; j<m_NPoints; j++)
    {
      LinePnt* pnt = new LinePnt(m_NDims);

      for(d=0; d<m_NDims; d++)
      {
        MET_ValueToDouble(m_ElementType, _data, i++, &td);
        pnt->m_X[d] = (float)td;
      }

      for(int l=0;l<m_NDims-1;l++)
      {
        for(d=0; d<m_NDims; d++)
        {
          MET_ValueToDouble(m_ElementType, _data, i++, &td);
          pnt->m_V[l][d] = (float)td;
        }
      }

      for(d=0; d<4; d++)
      {
        MET_ValueToDouble(m_ElementType, _data, i++, &td);
        pnt->m_Color[d] = (float)td;
      }

      m_PointList.push_back(pnt);
    }
    delete [] _data;
  }
  else
  {
    for(int j=0; j<m_NPoints; j++)
    {
      LinePnt* pnt = new LinePnt(m_NDims);

      int k;
      int d;
      for(k=0; k<m_NDims; k++)
      {
        *m_ReadStream >> v[k];
        m_ReadStream->get();
      }

      //float* x = new float[m_NDims];
      for(d=0; d<m_NDims; d++)
      {
        pnt->m_X[d] = v[d];
      }

      //pnt.m_X = x;

      for(k=0; k<m_NDims-1; k++)
      {
        for(j=0; j<m_NDims; j++)
        {
          *m_ReadStream >> v[j];
          m_ReadStream->get();
        }

        //float* n = new float[m_NDims];
        for(d=0; d<m_NDims; d++)
        {
          pnt->m_V[k][d] = v[d];
        }
        //pnt.m_V[k] = n;
      }
      for(k=0; k<4; k++)
      {
        *m_ReadStream >> v[k];
        m_ReadStream->get();
        pnt->m_Color[k] = v[k];
      }

      m_PointList.push_back(pnt);
    }

    char c = ' ';
    while( (c!='\n') && (!m_ReadStream->eof()))
    {
      c = m_ReadStream->get();// to avoid unrecognized characters
    }
  }

  return true;
}

bool MetaLine::
M_Write(void)
{

  if(!MetaObject::M_Write())
  {
    std::cout << "MetaLine: M_Read: Error parsing file" << std::endl;
    return false;
  }

  /** Then copy all points */
  if(m_BinaryData)
  {
    PointListType::const_iterator it = m_PointList.begin();
    int elementSize;
    MET_SizeOfType(m_ElementType, &elementSize);

    char* data = new char[(m_NDims*m_NDims+4)*m_NPoints*elementSize];
    int i=0;
    int d;
    while(it != m_PointList.end())
    {
      for(d = 0; d < m_NDims; d++)
      {
        MET_DoubleToValue((double)(*it)->m_X[d],m_ElementType,data,i++);
      }

      for(int j=0;j<m_NDims-1;j++)
      {
        for(d=0; d<m_NDims; d++)
        {
          MET_DoubleToValue((double)(*it)->m_V[j][d],m_ElementType,data,i++);
        }
      }

      for(d=0; d<4; d++)
      {
        MET_DoubleToValue((double)(*it)->m_Color[d],m_ElementType,data,i++);
      }

      it++;
    }

    m_WriteStream->write((char *)data,(m_NDims*m_NDims+4)*m_NPoints*elementSize);
    m_WriteStream->write("\n",1);
    delete [] data;
  }
  else
  {
    PointListType::const_iterator it = m_PointList.begin();

    int d;
    while(it != m_PointList.end())
    {
      for(d = 0; d < m_NDims; d++)
      {
        *m_WriteStream << (*it)->m_X[d] << " ";
      }

      for(d = 0; d < m_NDims-1; d++)
      {
        for(int i = 0; i < m_NDims; i++)
        {
          *m_WriteStream << (*it)->m_V[d][i] << " ";
        }
      }

      for(d=0;d<4;d++)
      {
        *m_WriteStream << (*it)->m_Color[d] << " ";
      }

      *m_WriteStream << std::endl;
      it++;
    }
  }

  return true;

}
<commit_msg>BUG: strange interaction with shadowed variable.<commit_after>#include <stdio.h>
#include <ctype.h>
#include <iostream>
#include <fstream>
#include <string>

#include <metaUtils.h>
#include <metaObject.h>
#include <metaLine.h>

//
// MetaLine Constructors
//
MetaLine::
MetaLine()
:MetaObject()
{
  if(META_DEBUG) std::cout << "MetaLine()" << std::endl;
  Clear();
}

//
MetaLine::
MetaLine(const char *_headerName)
:MetaObject(_headerName)
{
  if(META_DEBUG)  std::cout << "MetaLine()" << std::endl;
  Clear();
  Read(_headerName);
}

//
MetaLine::
MetaLine(const MetaLine *_line)
:MetaObject()
{
  if(META_DEBUG)  std::cout << "MetaLine()" << std::endl;
  Clear();
  CopyInfo(_line);
}

//
MetaLine::
MetaLine(unsigned int dim)
:MetaObject(dim)
{
  if(META_DEBUG) std::cout << "MetaLine()" << std::endl;
  Clear();
}

//
MetaLine::
~MetaLine()
{
  Clear();
  M_Destroy();
}

//
void MetaLine::
PrintInfo() const
{
  MetaObject::PrintInfo();
  std::cout << "PointDim = " << m_PointDim << std::endl;
  std::cout << "NPoints = " << m_NPoints << std::endl;
  char str[255];
  MET_TypeToString(m_ElementType, str);
  std::cout << "ElementType = " << str << std::endl;
}

void MetaLine::
CopyInfo(const MetaLine * _line)
{
  MetaObject::CopyInfo(_line);
}

void MetaLine::
PointDim(const char* pointDim)
{
  strcpy(m_PointDim,pointDim);
}

const char* MetaLine::
PointDim(void) const
{
  return m_PointDim;
}

void MetaLine::
NPoints(int npnt)
{
  m_NPoints = npnt;
}

int MetaLine::
NPoints(void) const
{
  return m_NPoints;
}

/** Clear line information */
void MetaLine::
Clear(void)
{
  if(META_DEBUG) std::cout << "MetaLine: Clear" << std::endl;
  MetaObject::Clear();
  m_NPoints = 0;
    // Delete the list of pointers to lines.
  PointListType::iterator it = m_PointList.begin();
  while(it != m_PointList.end())
  {
    LinePnt* pnt = *it;
    it++;
    delete pnt;
  }
  m_PointList.clear();

  strcpy(m_PointDim, "x y z v1x v1y v1z");
  m_ElementType = MET_FLOAT;
}

/** Destroy line information */
void MetaLine::
M_Destroy(void)
{
  MetaObject::M_Destroy();
}

/** Set Read fields */
void MetaLine::
M_SetupReadFields(void)
{
  if(META_DEBUG) std::cout << "MetaLine: M_SetupReadFields" << std::endl;

  MetaObject::M_SetupReadFields();

  MET_FieldRecordType * mF;

  //int nDimsRecNum = MET_GetFieldRecordNumber("NDims", &m_Fields);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "PointDim", MET_STRING, true);
  m_Fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NPoints", MET_INT, true);
  m_Fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "ElementType", MET_STRING, true);
  mF->required = true;
  m_Fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Points", MET_NONE, true);
  mF->terminateRead = true;
  m_Fields.push_back(mF);

}

void MetaLine::
M_SetupWriteFields(void)
{
  strcpy(m_ObjectTypeName,"Line");
  MetaObject::M_SetupWriteFields();

  MET_FieldRecordType * mF;

  char s[255];
  mF = new MET_FieldRecordType;
  MET_TypeToString(m_ElementType, s);
  MET_InitWriteField(mF, "ElementType", MET_STRING, strlen(s), s);
  m_Fields.push_back(mF);

  if(strlen(m_PointDim)>0)
  {
    mF = new MET_FieldRecordType;
    MET_InitWriteField(mF, "PointDim", MET_STRING,
                           strlen(m_PointDim),m_PointDim);
    m_Fields.push_back(mF);
  }

  m_NPoints = m_PointList.size();
  mF = new MET_FieldRecordType;
  MET_InitWriteField(mF, "NPoints", MET_INT,m_NPoints);
  m_Fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitWriteField(mF, "Points", MET_NONE);
  m_Fields.push_back(mF);

}

MET_ValueEnumType MetaLine::
ElementType(void) const
{
  return m_ElementType;
}

void MetaLine::
ElementType(MET_ValueEnumType _elementType)
{
  m_ElementType = _elementType;
}

bool MetaLine::
M_Read(void)
{
  if(META_DEBUG) std::cout << "MetaLine: M_Read: Loading Header" << std::endl;

  if(!MetaObject::M_Read())
  {
    std::cout << "MetaLine: M_Read: Error parsing file" << std::endl;
    return false;
  }

  if(META_DEBUG) std::cout << "MetaLine: M_Read: Parsing Header" << std::endl;

  MET_FieldRecordType * mF;

  mF = MET_GetFieldRecord("NPoints", &m_Fields);
  if(mF->defined)
  {
    m_NPoints= (int)mF->value[0];
  }

  mF = MET_GetFieldRecord("ElementType", &m_Fields);
  if(mF->defined)
  {
    MET_StringToType((char *)(mF->value), &m_ElementType);
  }

  mF = MET_GetFieldRecord("PointDim", &m_Fields);
  if(mF->defined)
  {
    strcpy(m_PointDim,(char *)(mF->value));
  }

  int pntDim;
  char** pntVal = NULL;
  MET_StringToWordArray(m_PointDim, &pntDim, &pntVal);

  int ii;
  for(ii=0;ii<pntDim;ii++)
    {
      delete [] pntVal[ii];
    }
  delete [] pntVal;

  float v[16];

  if(m_BinaryData)
  {
    int elementSize;
    MET_SizeOfType(m_ElementType, &elementSize);
    int readSize = m_NPoints*(m_NDims*m_NDims+4)*elementSize;

    char* _data = new char[readSize];
    m_ReadStream->read((char *)_data, readSize);

    int gc = m_ReadStream->gcount();
    if(gc != readSize)
    {
      std::cout << "MetaLine: m_Read: data not read completely"
                << std::endl;
      std::cout << "   ideal = " << readSize << " : actual = " << gc << std::endl;
      return false;
    }

    int i=0;
    double td;
    int d;
    for(int j=0; j<m_NPoints; j++)
    {
      LinePnt* pnt = new LinePnt(m_NDims);

      for(d=0; d<m_NDims; d++)
      {
        MET_ValueToDouble(m_ElementType, _data, i++, &td);
        pnt->m_X[d] = (float)td;
      }

      for(int l=0;l<m_NDims-1;l++)
      {
        for(d=0; d<m_NDims; d++)
        {
          MET_ValueToDouble(m_ElementType, _data, i++, &td);
          pnt->m_V[l][d] = (float)td;
        }
      }

      for(d=0; d<4; d++)
      {
        MET_ValueToDouble(m_ElementType, _data, i++, &td);
        pnt->m_Color[d] = (float)td;
      }

      m_PointList.push_back(pnt);
    }
    delete [] _data;
  }
  else
  {
    for(int j=0; j<m_NPoints; j++)
    {
      LinePnt* pnt = new LinePnt(m_NDims);

      int k;
      int d;
      for(k=0; k<m_NDims; k++)
      {
        *m_ReadStream >> v[k];
        m_ReadStream->get();
      }

      //float* x = new float[m_NDims];
      for(d=0; d<m_NDims; d++)
      {
        pnt->m_X[d] = v[d];
      }

      //pnt.m_X = x;

      for(k=0; k<m_NDims-1; k++)
      {
        for(int j=0; j<m_NDims; j++)
        {
          *m_ReadStream >> v[j];
          m_ReadStream->get();
        }

        //float* n = new float[m_NDims];
        for(d=0; d<m_NDims; d++)
        {
          pnt->m_V[k][d] = v[d];
        }
        //pnt.m_V[k] = n;
      }
      for(k=0; k<4; k++)
      {
        *m_ReadStream >> v[k];
        m_ReadStream->get();
        pnt->m_Color[k] = v[k];
      }

      m_PointList.push_back(pnt);
    }

    char c = ' ';
    while( (c!='\n') && (!m_ReadStream->eof()))
    {
      c = m_ReadStream->get();// to avoid unrecognized characters
    }
  }

  return true;
}

bool MetaLine::
M_Write(void)
{

  if(!MetaObject::M_Write())
  {
    std::cout << "MetaLine: M_Read: Error parsing file" << std::endl;
    return false;
  }

  /** Then copy all points */
  if(m_BinaryData)
  {
    PointListType::const_iterator it = m_PointList.begin();
    int elementSize;
    MET_SizeOfType(m_ElementType, &elementSize);

    char* data = new char[(m_NDims*m_NDims+4)*m_NPoints*elementSize];
    int i=0;
    int d;
    while(it != m_PointList.end())
    {
      for(d = 0; d < m_NDims; d++)
      {
        MET_DoubleToValue((double)(*it)->m_X[d],m_ElementType,data,i++);
      }

      for(int j=0;j<m_NDims-1;j++)
      {
        for(d=0; d<m_NDims; d++)
        {
          MET_DoubleToValue((double)(*it)->m_V[j][d],m_ElementType,data,i++);
        }
      }

      for(d=0; d<4; d++)
      {
        MET_DoubleToValue((double)(*it)->m_Color[d],m_ElementType,data,i++);
      }

      it++;
    }

    m_WriteStream->write((char *)data,(m_NDims*m_NDims+4)*m_NPoints*elementSize);
    m_WriteStream->write("\n",1);
    delete [] data;
  }
  else
  {
    PointListType::const_iterator it = m_PointList.begin();

    int d;
    while(it != m_PointList.end())
    {
      for(d = 0; d < m_NDims; d++)
      {
        *m_WriteStream << (*it)->m_X[d] << " ";
      }

      for(d = 0; d < m_NDims-1; d++)
      {
        for(int i = 0; i < m_NDims; i++)
        {
          *m_WriteStream << (*it)->m_V[d][i] << " ";
        }
      }

      for(d=0;d<4;d++)
      {
        *m_WriteStream << (*it)->m_Color[d] << " ";
      }

      *m_WriteStream << std::endl;
      it++;
    }
  }

  return true;

}
<|endoftext|>


<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2021 Intel Corporation. All Rights Reserved.

#include "converter-csv.hpp"
#include <iomanip>
#include <algorithm>
#include <iostream>

using namespace rs2::tools::converter;

converter_csv::motion_pose_frame_record::motion_pose_frame_record(rs2_stream stream_type, int stream_index,
    unsigned long long frame_number,
    double frame_ts, double backend_ts, double arrival_time,
    double p1, double p2, double p3,
    double p4, double p5, double p6, double p7) :
    _stream_type(stream_type),
    _stream_idx(stream_index),
    _frame_number(frame_number),
    _frame_ts(frame_ts),
    _backend_ts(backend_ts),
    _arrival_time(arrival_time),
    _params({ p1, p2, p3, p4, p5, p6, p7 }){}

std::string converter_csv::motion_pose_frame_record::to_string() const
{
    std::stringstream ss;
    ss << rs2_stream_to_string(_stream_type) << "," << _frame_number << ","
        << std::fixed << std::setprecision(3) << _frame_ts << "," << _backend_ts << "," << _arrival_time;

    // IMU and Pose frame hold the sample data in addition to the frame's header attributes
    size_t specific_attributes = 0;
    if (val_in_range(_stream_type, { RS2_STREAM_GYRO,RS2_STREAM_ACCEL }))
        specific_attributes = 3;
    if (val_in_range(_stream_type, { RS2_STREAM_POSE }))
        specific_attributes = 7;

    for (auto i = 0; i < specific_attributes; i++)
        ss << "," << _params[i];
    ss << std::endl;
    return ss.str().c_str();
}

converter_csv::converter_csv(const std::string& filePath, rs2_stream streamType)
    : _filePath(filePath)
    , _streamType(streamType)
    , _imu_pose_collection()
    , _sub_workers_joined(false)
    , _m()
    , _cv()
{
}

void converter_csv::convert_depth(rs2::depth_frame& depthframe)
{
    if (frames_map_get_and_set(depthframe.get_profile().stream_type(), depthframe.get_frame_number())) {
        return;
    }

    start_worker(
        [this, &depthframe] {

            std::stringstream filename;
            filename << _filePath
                << "_" << depthframe.get_profile().stream_name()
                << "_" << std::setprecision(14) << std::fixed << depthframe.get_timestamp()
                << ".csv";

            std::stringstream metadata_file;
            metadata_file << _filePath
                << "_" << depthframe.get_profile().stream_name()
                << "_metadata_" << std::setprecision(14) << std::fixed << depthframe.get_timestamp()
                << ".txt";

            std::string filenameS = filename.str();
            std::string metadataS = metadata_file.str();

            add_sub_worker(
                [filenameS, metadataS, depthframe] {
                    std::ofstream fs(filenameS, std::ios::trunc);

                    if (fs) {
                        for (int y = 0; y < depthframe.get_height(); y++) {
                            auto delim = "";

                            for (int x = 0; x < depthframe.get_width(); x++) {
                                fs << delim << depthframe.get_distance(x, y);
                                delim = ",";
                            }
                            fs << '\n';
                        }
                        fs.flush();
                    }
                    metadata_to_txtfile(depthframe, metadataS);
                });
            wait_sub_workers();
        });
}

std::string converter_csv::get_time_string() const
{
    auto t = time(nullptr);
    char buffer[20] = {};
    const tm* time = localtime(&t);
    if (nullptr != time)
        strftime(buffer, sizeof(buffer), "%Y%m%d%H%M%S", time);

    return std::string(buffer);
}

void converter_csv::save_motion_pose_data_to_file()
{
    if (!_imu_pose_collection.size())
        throw std::runtime_error(stringify() << "No imu or pose data collected, aborting");

    // Report amount of frames collected
    std::vector<uint64_t> frames_per_stream;
    for (const auto& kv : _imu_pose_collection)
        frames_per_stream.emplace_back(kv.second.size());

    std::sort(frames_per_stream.begin(), frames_per_stream.end());

    // Serialize and store data into csv-like format
    static auto time_Str = get_time_string();
    std::stringstream filename;
    filename << _filePath  << "_" << time_Str <<"_imu_pose.csv";
    std::ofstream csv(filename.str());
    if (!csv.is_open())
        throw std::runtime_error(stringify() << "Cannot open the requested output file " << _filePath << ", please check permissions");

    for (const auto& elem : _imu_pose_collection)
    {
        csv << "\n\nStream Type,F#,HW Timestamp (ms),Backend Timestamp(ms),Host Timestamp(ms)"
            << (val_in_range(elem.first.first, { RS2_STREAM_GYRO,RS2_STREAM_ACCEL }) ? ",3DOF_x,3DOF_y,3DOF_z" : "")
            << (val_in_range(elem.first.first, { RS2_STREAM_POSE }) ? ",t_x,t_y,t_z,r_x,r_y,r_z,r_w" : "")
            << std::endl;

        for (auto i = 0; i < elem.second.size(); i++)
            csv << elem.second[i].to_string();
    }

}

void converter_csv::convert_motion_pose(rs2::frame& f)
{
    if (frames_map_get_and_set(f.get_profile().stream_type(), f.get_frame_number())) {
        return;
    }

    start_worker(
        [this, f] {

            add_sub_worker(
                [this, f] {
                    auto stream_uid = std::make_pair(f.get_profile().stream_type(),
                        f.get_profile().stream_index());

                    double frame_timestamp = 0.;
                    if (f.supports_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP))
                        frame_timestamp = f.get_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP);

                    double backend_timestamp = 0.;
                    if (f.supports_frame_metadata(RS2_FRAME_METADATA_BACKEND_TIMESTAMP))
                        backend_timestamp = f.get_frame_metadata(RS2_FRAME_METADATA_BACKEND_TIMESTAMP);

                    double time_of_arrival = 0.;
                    if (f.supports_frame_metadata(RS2_FRAME_METADATA_TIME_OF_ARRIVAL))
                        time_of_arrival = f.get_frame_metadata(RS2_FRAME_METADATA_TIME_OF_ARRIVAL);

                    motion_pose_frame_record record{ f.get_profile().stream_type(),
                                                f.get_profile().stream_index(),
                                                f.get_frame_number(),
                                                frame_timestamp,
                                                backend_timestamp,
                                                time_of_arrival};

                    if (auto motion = f.as<rs2::motion_frame>())
                    {
                        auto axes = motion.get_motion_data();
                        record._params = { axes.x, axes.y, axes.z };
                    }

                    if (auto pf = f.as<rs2::pose_frame>())
                    {
                        auto pose = pf.get_pose_data();
                        record._params = { pose.translation.x, pose.translation.y, pose.translation.z,
                                pose.rotation.x,pose.rotation.y,pose.rotation.z,pose.rotation.w };
                    }

                    _imu_pose_collection[stream_uid].emplace_back(record);
                });
            wait_sub_workers();
            _sub_workers_joined = true;
            _cv.notify_all();
        });
    std::unique_lock<std::mutex> lck(_m);
    while (!_sub_workers_joined)
        _cv.wait(lck);
    save_motion_pose_data_to_file();
}

void converter_csv::convert(rs2::frame& frame)
{
    if (!(_streamType == rs2_stream::RS2_STREAM_ANY || frame.get_profile().stream_type() == _streamType))
        return;

    auto depthframe = frame.as<rs2::depth_frame>();
    if (depthframe)
    {
        convert_depth(depthframe);
        return;
    }

    auto motionframe = frame.as<rs2::motion_frame>();
    auto poseframe = frame.as<rs2::pose_frame>();
    if (motionframe || poseframe)
    {
        convert_motion_pose(frame);
        return;
    }
}
<commit_msg>cr correction<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2021 Intel Corporation. All Rights Reserved.

#include "converter-csv.hpp"
#include <iomanip>
#include <algorithm>
#include <iostream>

using namespace rs2::tools::converter;

converter_csv::motion_pose_frame_record::motion_pose_frame_record(rs2_stream stream_type, int stream_index,
    unsigned long long frame_number,
    double frame_ts, double backend_ts, double arrival_time,
    double p1, double p2, double p3,
    double p4, double p5, double p6, double p7) :
    _stream_type(stream_type),
    _stream_idx(stream_index),
    _frame_number(frame_number),
    _frame_ts(frame_ts),
    _backend_ts(backend_ts),
    _arrival_time(arrival_time),
    _params({ p1, p2, p3, p4, p5, p6, p7 }){}

std::string converter_csv::motion_pose_frame_record::to_string() const
{
    std::stringstream ss;
    ss << rs2_stream_to_string(_stream_type) << "," << _frame_number << ","
        << std::fixed << std::setprecision(3) << _frame_ts << "," << _backend_ts << "," << _arrival_time;

    // IMU and Pose frame hold the sample data in addition to the frame's header attributes
    size_t specific_attributes = 0;
    if (val_in_range(_stream_type, { RS2_STREAM_GYRO,RS2_STREAM_ACCEL }))
        specific_attributes = 3;
    if (val_in_range(_stream_type, { RS2_STREAM_POSE }))
        specific_attributes = 7;

    for (auto i = 0; i < specific_attributes; i++)
        ss << "," << _params[i];
    ss << std::endl;
    return ss.str().c_str();
}

converter_csv::converter_csv(const std::string& filePath, rs2_stream streamType)
    : _filePath(filePath)
    , _streamType(streamType)
    , _imu_pose_collection()
    , _sub_workers_joined(false)
    , _m()
    , _cv()
{
}

void converter_csv::convert_depth(rs2::depth_frame& depthframe)
{
    if (frames_map_get_and_set(depthframe.get_profile().stream_type(), depthframe.get_frame_number())) {
        return;
    }

    start_worker(
        [this, &depthframe] {

            std::stringstream filename;
            filename << _filePath
                << "_" << depthframe.get_profile().stream_name()
                << "_" << std::setprecision(14) << std::fixed << depthframe.get_timestamp()
                << ".csv";

            std::stringstream metadata_file;
            metadata_file << _filePath
                << "_" << depthframe.get_profile().stream_name()
                << "_metadata_" << std::setprecision(14) << std::fixed << depthframe.get_timestamp()
                << ".txt";

            std::string filenameS = filename.str();
            std::string metadataS = metadata_file.str();

            add_sub_worker(
                [filenameS, metadataS, depthframe] {
                    std::ofstream fs(filenameS, std::ios::trunc);

                    if (fs) {
                        for (int y = 0; y < depthframe.get_height(); y++) {
                            auto delim = "";

                            for (int x = 0; x < depthframe.get_width(); x++) {
                                fs << delim << depthframe.get_distance(x, y);
                                delim = ",";
                            }
                            fs << '\n';
                        }
                        fs.flush();
                    }
                    metadata_to_txtfile(depthframe, metadataS);
                });
            wait_sub_workers();
        });
}

std::string converter_csv::get_time_string() const
{
    auto t = time(nullptr);
    char buffer[20] = {};
    const tm* time = localtime(&t);
    if (nullptr != time)
        strftime(buffer, sizeof(buffer), "%Y%m%d%H%M%S", time);

    return std::string(buffer);
}

void converter_csv::save_motion_pose_data_to_file()
{
    if (!_imu_pose_collection.size())
    {
        std::cout << "No imu or pose data collected" << std::endl;
        return;
    }

    // Report amount of frames collected
    std::vector<uint64_t> frames_per_stream;
    for (const auto& kv : _imu_pose_collection)
        frames_per_stream.emplace_back(kv.second.size());

    std::sort(frames_per_stream.begin(), frames_per_stream.end());

    // Serialize and store data into csv-like format
    static auto time_Str = get_time_string();
    std::stringstream filename;
    filename << _filePath  << "_" << time_Str <<"_imu_pose.csv";
    std::ofstream csv(filename.str());
    if (!csv.is_open())
        throw std::runtime_error(stringify() << "Cannot open the requested output file " << _filePath << ", please check permissions");

    for (const auto& elem : _imu_pose_collection)
    {
        csv << "\n\nStream Type,F#,HW Timestamp (ms),Backend Timestamp(ms),Host Timestamp(ms)"
            << (val_in_range(elem.first.first, { RS2_STREAM_GYRO,RS2_STREAM_ACCEL }) ? ",3DOF_x,3DOF_y,3DOF_z" : "")
            << (val_in_range(elem.first.first, { RS2_STREAM_POSE }) ? ",t_x,t_y,t_z,r_x,r_y,r_z,r_w" : "")
            << std::endl;

        for (auto i = 0; i < elem.second.size(); i++)
            csv << elem.second[i].to_string();
    }

}

void converter_csv::convert_motion_pose(rs2::frame& f)
{
    if (frames_map_get_and_set(f.get_profile().stream_type(), f.get_frame_number())) {
        return;
    }

    start_worker(
        [this, f] {

            add_sub_worker(
                [this, f] {
                    auto stream_uid = std::make_pair(f.get_profile().stream_type(),
                        f.get_profile().stream_index());

                    double frame_timestamp = 0.;
                    if (f.supports_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP))
                        frame_timestamp = f.get_frame_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP);

                    double backend_timestamp = 0.;
                    if (f.supports_frame_metadata(RS2_FRAME_METADATA_BACKEND_TIMESTAMP))
                        backend_timestamp = f.get_frame_metadata(RS2_FRAME_METADATA_BACKEND_TIMESTAMP);

                    double time_of_arrival = 0.;
                    if (f.supports_frame_metadata(RS2_FRAME_METADATA_TIME_OF_ARRIVAL))
                        time_of_arrival = f.get_frame_metadata(RS2_FRAME_METADATA_TIME_OF_ARRIVAL);

                    motion_pose_frame_record record{ f.get_profile().stream_type(),
                                                f.get_profile().stream_index(),
                                                f.get_frame_number(),
                                                frame_timestamp,
                                                backend_timestamp,
                                                time_of_arrival};

                    if (auto motion = f.as<rs2::motion_frame>())
                    {
                        auto axes = motion.get_motion_data();
                        record._params = { axes.x, axes.y, axes.z };
                    }

                    if (auto pf = f.as<rs2::pose_frame>())
                    {
                        auto pose = pf.get_pose_data();
                        record._params = { pose.translation.x, pose.translation.y, pose.translation.z,
                                pose.rotation.x,pose.rotation.y,pose.rotation.z,pose.rotation.w };
                    }

                    _imu_pose_collection[stream_uid].emplace_back(record);
                });
            wait_sub_workers();
            _sub_workers_joined = true;
            _cv.notify_all();
        });
    std::unique_lock<std::mutex> lck(_m);
    while (!_sub_workers_joined)
        _cv.wait(lck);
    save_motion_pose_data_to_file();
}

void converter_csv::convert(rs2::frame& frame)
{
    if (!(_streamType == rs2_stream::RS2_STREAM_ANY || frame.get_profile().stream_type() == _streamType))
        return;

    auto depthframe = frame.as<rs2::depth_frame>();
    if (depthframe)
    {
        convert_depth(depthframe);
        return;
    }

    auto motionframe = frame.as<rs2::motion_frame>();
    auto poseframe = frame.as<rs2::pose_frame>();
    if (motionframe || poseframe)
    {
        convert_motion_pose(frame);
        return;
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2015, Intel Corporation, all rights reserved.

/*
* This sample shows how to use custom schema in xml file.
*/

#include <vmf/vmf.hpp>
#include <iostream>
#include <fstream>
#include <ctime>
#include <iomanip>
#include <fstream>
#include <vector>

using namespace vmf;
using namespace std;
void dumpMetadataDesc(shared_ptr<MetadataDesc> spDesc)
{
	if (spDesc == nullptr)
		return;

	cout << "Metadata: " << spDesc->getMetadataName() << endl;
	vector<FieldDesc> fields = spDesc->getFields();
	for (FieldDesc field : fields)
	{
		cout << "\t[" << field.name << "]: " << Variant::typeToString(field.type) << std::endl;
	}
}
void demoLoadSchemaFromFile(const string& schemaFilePath, const string& schemaName)
{
	MetadataStream stream;

	try
	{
		// Open schema file
		std::ifstream inputFile(schemaFilePath);

		// Read schema content into memory string
		stringstream ss;
		ss << inputFile.rdbuf();

		// Parse schema content and load it into stream
		XMLReader reader;
		stream.deserialize(ss.str(), reader);

		// Get a pointer to the schema
		shared_ptr<MetadataSchema> spSchema = stream.getSchema(schemaName);
		if (spSchema == nullptr)
			throw exception("Did not find schema in the xml file!");

		// Get a pointer to the metadata description structure
		shared_ptr<MetadataDesc> spMetadataDesc = spSchema->findMetadataDesc("table2");
		if (spMetadataDesc == nullptr)
			throw exception("Did not find metadata <table2> in the schema.");

		// Found everything!
		std::cout << "Found schema and metadata!" << std::endl;
		std::cout << "Schema: " << spSchema->getName() << std::endl;
		dumpMetadataDesc(spMetadataDesc);

		stream.close();
	}
	catch (std::exception& e)
	{
		std::cout << "Operation fialed: " << e.what() << std::endl;
		stream.close();
	}
}

int main(int argc, char* argv[])
{
    vmf::initialize();

	string schemaFilePath("demo_schema.xml");
	string schemaName("vmf://ns.intel.com/vmf/demo-schema-1.0");

	string appPath = argv[0];
#ifdef WIN32
	char delim = '\\';
#else
	char delim = '/';
#endif
	size_t pos = appPath.find_last_of(delim);

	string workingPath;
	if (pos != string::npos)
	{
		workingPath = appPath.substr(0, pos + 1);
	}

	// Run demo
	demoLoadSchemaFromFile(workingPath + schemaFilePath, schemaName);

    vmf::terminate();

    return 0;
}
<commit_msg>Added new header boilerplate<commit_after>/*
 * Copyright 2015 Intel(r) 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.
 *
 */

/*
* This sample shows how to use custom schema in xml file.
*/

#include <vmf/vmf.hpp>
#include <iostream>
#include <fstream>
#include <ctime>
#include <iomanip>
#include <fstream>
#include <vector>

using namespace vmf;
using namespace std;
void dumpMetadataDesc(shared_ptr<MetadataDesc> spDesc)
{
	if (spDesc == nullptr)
		return;

	cout << "Metadata: " << spDesc->getMetadataName() << endl;
	vector<FieldDesc> fields = spDesc->getFields();
	for (FieldDesc field : fields)
	{
		cout << "\t[" << field.name << "]: " << Variant::typeToString(field.type) << std::endl;
	}
}
void demoLoadSchemaFromFile(const string& schemaFilePath, const string& schemaName)
{
	MetadataStream stream;

	try
	{
		// Open schema file
		std::ifstream inputFile(schemaFilePath);

		// Read schema content into memory string
		stringstream ss;
		ss << inputFile.rdbuf();

		// Parse schema content and load it into stream
		XMLReader reader;
		stream.deserialize(ss.str(), reader);

		// Get a pointer to the schema
		shared_ptr<MetadataSchema> spSchema = stream.getSchema(schemaName);
		if (spSchema == nullptr)
			throw exception("Did not find schema in the xml file!");

		// Get a pointer to the metadata description structure
		shared_ptr<MetadataDesc> spMetadataDesc = spSchema->findMetadataDesc("table2");
		if (spMetadataDesc == nullptr)
			throw exception("Did not find metadata <table2> in the schema.");

		// Found everything!
		std::cout << "Found schema and metadata!" << std::endl;
		std::cout << "Schema: " << spSchema->getName() << std::endl;
		dumpMetadataDesc(spMetadataDesc);

		stream.close();
	}
	catch (std::exception& e)
	{
		std::cout << "Operation fialed: " << e.what() << std::endl;
		stream.close();
	}
}

int main(int argc, char* argv[])
{
    vmf::initialize();

	string schemaFilePath("demo_schema.xml");
	string schemaName("vmf://ns.intel.com/vmf/demo-schema-1.0");

	string appPath = argv[0];
#ifdef WIN32
	char delim = '\\';
#else
	char delim = '/';
#endif
	size_t pos = appPath.find_last_of(delim);

	string workingPath;
	if (pos != string::npos)
	{
		workingPath = appPath.substr(0, pos + 1);
	}

	// Run demo
	demoLoadSchemaFromFile(workingPath + schemaFilePath, schemaName);

    vmf::terminate();

    return 0;
}
<|endoftext|>


<commit_before>#include "immediate_hud.h"
#include "entity_system/entity.h"
#include "entity_system/world.h"

#include "game/systems/render_system.h"
#include "game/systems/gui_system.h"
#include "game/components/sprite_component.h"
#include "game/components/camera_component.h"
#include "game/components/sentience_component.h"
#include "game/components/render_component.h"
#include "game/components/physics_component.h"
#include "game/components/name_component.h"

#include "game/messages/health_event.h"

#include "game/detail/inventory_utils.h"
#include "game/detail/inventory_slot.h"
#include "game/detail/inventory_slot_id.h"
#include "game/detail/entity_description.h"

#include "graphics/renderer.h"
#include "graphics/vertex.h"
#include "stream.h"
#include "stlutil.h"
#include "augs/gui/text_drawer.h"

void immediate_hud::draw_circular_bars(messages::camera_render_request_message r) {
	auto& render = r.camera->get_owner_world().get_system<render_system>();
	const auto& visible_entities = render.get_all_visible_entities();
	auto& target = *r.state.output;

	auto camera = r.camera;
	auto watched_character = camera->get<components::camera>().entity_to_chase;

	int timestamp_ms = render.frame_timestamp_seconds() * 1000;

	circular_bars_information.clear();
	pure_color_highlights.clear();

	for (auto v : render.get_all_visible_entities()) {
		auto* sentience = v->find<components::sentience>();

		if (sentience) {
			auto hr = sentience->health_ratio();
			auto one_less_hr = 1 - hr;

			int pulse_duration = 1250 - 1000 * (1 - hr);
			float time_pulse_ratio = (timestamp_ms % pulse_duration) / float(pulse_duration);

			hr *= 1.f - (0.2f * time_pulse_ratio);

			auto* render = v->find<components::render>();

			if (render) {
				//render->partial_overlay_color = red;
				//render->partial_overlay_height_ratio = 1 - hr;
				if (hr < 1.f) {
					render->draw_border = true;
					render->border_color = rgba(255, 0, 0, one_less_hr * one_less_hr * one_less_hr * one_less_hr * 255 * time_pulse_ratio);
				}
				else
					render->draw_border = false;
			}

			auto health_col = sentience->calculate_health_color(time_pulse_ratio);

			auto& transform = v->get<components::transform>();
			shared::state_for_drawing_renderable state;
			state.setup_camera_state(r.state);
			state.renderable_transform = transform;
			state.renderable_transform.rotation = 0;

			components::sprite circle_hud;
			circle_hud.set(assets::HUD_CIRCULAR_BAR_MEDIUM, health_col);
			circle_hud.draw(state);

			auto watched_character_transform = watched_character->get<components::transform>();
			float starting_health_angle = 0.f;
			float ending_health_angle = 0.f;

			if (v == watched_character) {
				starting_health_angle = watched_character_transform.rotation + 135;
				ending_health_angle = starting_health_angle + sentience->health_ratio() * 90.f;
			}
			else {
				starting_health_angle = (v->get<components::transform>().pos - watched_character_transform.pos).degrees() - 45;
				ending_health_angle = starting_health_angle + sentience->health_ratio() * 90.f;
			}

			auto push_angles = [&target](float lower_outside, float upper_outside, float lower_inside, float upper_inside) {
				augs::special s;

				s.v1.set(normalize_degrees(lower_outside) / 180, normalize_degrees(upper_outside) / 180);
				s.v2.set(normalize_degrees(lower_inside) / 180, normalize_degrees(upper_inside) / 180);

				target.push_special_vertex_triangle(s, s, s);
				target.push_special_vertex_triangle(s, s, s);
			};

			push_angles(starting_health_angle, starting_health_angle + 90, starting_health_angle, ending_health_angle);

			struct circle_info {
				float angle;
				std::wstring text;
				rgba color;
			};

			std::vector<circle_info> textual_infos;

			if (v == watched_character) {
				auto examine_item_slot = [&textual_infos, &push_angles, &circle_hud, &state](inventory_slot_id id, float lower_outside, float max_angular_length, bool ccw) {
					if (id.alive() && id.has_items()) {
						auto item = id->items_inside[0];

						auto maybe_magazine_slot = item[slot_function::GUN_DETACHABLE_MAGAZINE];
						auto chamber_slot = item[slot_function::GUN_CHAMBER];

						float ammo_ratio = 0.f;
						int charges = 0;
						float total_space_available = 0.f;
						float total_actual_free_space = 0.f;

						if (maybe_magazine_slot.alive() && maybe_magazine_slot.has_items()) {
							auto mag = maybe_magazine_slot->items_inside[0];
							auto ammo_depo = mag[slot_function::ITEM_DEPOSIT];
							charges += count_charges_in_deposit(mag);

							total_space_available += ammo_depo->space_available;
							total_actual_free_space += ammo_depo->calculate_free_space_with_children();
						}

						if (chamber_slot.alive()) {
							charges += count_charges_inside(chamber_slot);

							total_space_available += chamber_slot->space_available;
							total_actual_free_space += chamber_slot->calculate_free_space_with_children();
						}

						if (total_space_available > 0) {
							ammo_ratio = 1 - (total_actual_free_space / total_space_available);

							auto redviolet = augs::violet;
							redviolet.r = 200;
							circle_hud.color = augs::interp(augs::white, redviolet, (1 - ammo_ratio)* (1 - ammo_ratio));
							circle_hud.color.a = 200;
							circle_hud.draw(state);

							circle_info new_info;

							auto upper_outside = lower_outside + max_angular_length;

							if (!ccw) {
								push_angles(lower_outside, upper_outside, lower_outside, lower_outside + ammo_ratio * max_angular_length);
								new_info.angle = upper_outside;
							}
							else {
								push_angles(lower_outside, upper_outside, upper_outside - ammo_ratio * max_angular_length, upper_outside);
								new_info.angle = lower_outside;
							}

							new_info.text = augs::to_wstring(charges);
							new_info.color = circle_hud.color;

							textual_infos.push_back(new_info);
						}
					}
				};

				examine_item_slot(v[slot_function::SECONDARY_HAND], starting_health_angle + 90, 90, false);
				examine_item_slot(v[slot_function::PRIMARY_HAND], starting_health_angle - 90, 90, true);
			}

			int radius = (*assets::HUD_CIRCULAR_BAR_MEDIUM).get_size().x / 2;

			textual_infos.push_back({ starting_health_angle + 90, augs::to_wstring(sentience->health), health_col });
			textual_infos.push_back({ starting_health_angle, description_of_entity(v).name, health_col });

			for (auto& in : textual_infos) {
				if (in.text.empty()) continue;

				augs::gui::text_drawer health_points;
				health_points.set_text(augs::gui::text::format(in.text, augs::gui::text::style(assets::GUI_FONT, in.color)));

				auto circle_displacement_length = health_points.get_bbox().bigger_side() + radius;
				vec2i screen_space_circle_center = r.get_screen_space(transform.pos);

				health_points.pos = screen_space_circle_center + vec2().set_from_degrees(in.angle).set_length(circle_displacement_length);

				health_points.draw_stroke(circular_bars_information);
				health_points.draw(circular_bars_information);
			}
		}
	}
}

void immediate_hud::draw_circular_bars_information(messages::camera_render_request_message r) {
	r.state.output->triangles.insert(r.state.output->triangles.begin(), circular_bars_information.begin(), circular_bars_information.end());
}

void immediate_hud::acquire_game_events(augs::world& w) {
	auto& healths = w.get_message_queue<messages::health_event>();

	for (auto& h : healths) {
		vertically_flying_number vn;
		vn.time_of_occurence = w.get_current_timestamp();
		vn.value = h.effective_amount;
		vn.maximum_duration_seconds = 0.7;

		augs::rgba col;

		if (h.target == messages::health_event::HEALTH) {
			if (h.effective_amount > 0) {
				col = red;
			}
			else col = green;
		}
		else
			continue;

		vn.text.set_text(augs::gui::text::format(augs::to_wstring(std::abs(vn.value)), augs::gui::text::style(assets::GUI_FONT, col)));
		vn.transform.pos = h.point_of_impact;

		recent_vertically_flying_numbers.push_back(vn);

		pure_color_highlight ph;
		ph.time_of_occurence = w.get_current_timestamp();
		ph.target = h.subject;
		ph.starting_alpha_ratio = std::min(1.f, h.ratio_to_maximum_value * 15);
		ph.maximum_duration_seconds = 0.3;
		ph.color = col;

		erase_remove(recent_pure_color_highlights, [&ph](const pure_color_highlight& h) { return h.target == ph.target; });
		recent_pure_color_highlights.push_back(ph);
	}
}

double immediate_hud::get_current_time(messages::camera_render_request_message msg) const {
	auto& world = msg.camera->get_owner_world();
	return world.get_current_timestamp() + world.parent_overworld.fixed_delta_milliseconds() / 1000 * world.parent_overworld.view_interpolation_ratio();
}

void immediate_hud::draw_vertically_flying_numbers(messages::camera_render_request_message msg) {
	auto& target = renderer::get_current();

	auto current_time = get_current_time(msg);

	for (auto& r : recent_vertically_flying_numbers) {
		auto passed = current_time - r.time_of_occurence;
		auto ratio =  passed / r.maximum_duration_seconds;

		r.text.pos = msg.get_screen_space((r.transform.pos - vec2(0, sqrt(passed) * 150.f)));

		r.text.draw_stroke(msg.state.output->triangles);
		r.text.draw(msg.state.output->triangles);
	}

	auto timeout_lambda = [current_time](const game_event_visualization& v) {
		return (current_time - v.time_of_occurence) > v.maximum_duration_seconds;
	};

	erase_remove(recent_vertically_flying_numbers, timeout_lambda);
	erase_remove(recent_pure_color_highlights, timeout_lambda);
}

void immediate_hud::draw_pure_color_highlights(messages::camera_render_request_message msg) {
	auto current_time = get_current_time(msg);

	for (auto& r : recent_pure_color_highlights) {
		auto& col = r.target->get<components::sprite>().color;
		auto prevcol = col;
		col = r.color;

		auto passed = current_time - r.time_of_occurence;
		auto ratio = passed / r.maximum_duration_seconds;

		col.a = 255 * (1-ratio) * r.starting_alpha_ratio;
		render_system::standard_draw_entity(r.target, msg.state);
		col = prevcol;
	}

	//msg.state.output->triangles.insert(msg.state.output->triangles.begin(), pure_color_highlights.begin(), pure_color_highlights.end());
}<commit_msg>moving ammo/health captions<commit_after>#include "immediate_hud.h"
#include "entity_system/entity.h"
#include "entity_system/world.h"

#include "game/systems/render_system.h"
#include "game/systems/gui_system.h"
#include "game/components/sprite_component.h"
#include "game/components/camera_component.h"
#include "game/components/sentience_component.h"
#include "game/components/render_component.h"
#include "game/components/physics_component.h"
#include "game/components/name_component.h"

#include "game/messages/health_event.h"

#include "game/detail/inventory_utils.h"
#include "game/detail/inventory_slot.h"
#include "game/detail/inventory_slot_id.h"
#include "game/detail/entity_description.h"

#include "graphics/renderer.h"
#include "graphics/vertex.h"
#include "stream.h"
#include "stlutil.h"
#include "augs/gui/text_drawer.h"

void immediate_hud::draw_circular_bars(messages::camera_render_request_message r) {
	auto& render = r.camera->get_owner_world().get_system<render_system>();
	const auto& visible_entities = render.get_all_visible_entities();
	auto& target = *r.state.output;

	auto camera = r.camera;
	auto watched_character = camera->get<components::camera>().entity_to_chase;

	int timestamp_ms = render.frame_timestamp_seconds() * 1000;

	circular_bars_information.clear();
	pure_color_highlights.clear();

	for (auto v : render.get_all_visible_entities()) {
		auto* sentience = v->find<components::sentience>();

		if (sentience) {
			auto hr = sentience->health_ratio();
			auto one_less_hr = 1 - hr;

			int pulse_duration = 1250 - 1000 * (1 - hr);
			float time_pulse_ratio = (timestamp_ms % pulse_duration) / float(pulse_duration);

			hr *= 1.f - (0.2f * time_pulse_ratio);

			auto* render = v->find<components::render>();

			if (render) {
				//render->partial_overlay_color = red;
				//render->partial_overlay_height_ratio = 1 - hr;
				if (hr < 1.f) {
					render->draw_border = true;
					render->border_color = rgba(255, 0, 0, one_less_hr * one_less_hr * one_less_hr * one_less_hr * 255 * time_pulse_ratio);
				}
				else
					render->draw_border = false;
			}

			auto health_col = sentience->calculate_health_color(time_pulse_ratio);

			auto& transform = v->get<components::transform>();
			shared::state_for_drawing_renderable state;
			state.setup_camera_state(r.state);
			state.renderable_transform = transform;
			state.renderable_transform.rotation = 0;

			components::sprite circle_hud;
			circle_hud.set(assets::HUD_CIRCULAR_BAR_MEDIUM, health_col);
			circle_hud.draw(state);

			auto watched_character_transform = watched_character->get<components::transform>();
			float starting_health_angle = 0.f;
			float ending_health_angle = 0.f;

			if (v == watched_character) {
				starting_health_angle = watched_character_transform.rotation + 135;
				ending_health_angle = starting_health_angle + sentience->health_ratio() * 90.f;
			}
			else {
				starting_health_angle = (v->get<components::transform>().pos - watched_character_transform.pos).degrees() - 45;
				ending_health_angle = starting_health_angle + sentience->health_ratio() * 90.f;
			}

			auto push_angles = [&target](float lower_outside, float upper_outside, float lower_inside, float upper_inside) {
				augs::special s;

				s.v1.set(normalize_degrees(lower_outside) / 180, normalize_degrees(upper_outside) / 180);
				s.v2.set(normalize_degrees(lower_inside) / 180, normalize_degrees(upper_inside) / 180);

				target.push_special_vertex_triangle(s, s, s);
				target.push_special_vertex_triangle(s, s, s);
			};

			push_angles(starting_health_angle, starting_health_angle + 90, starting_health_angle, ending_health_angle);

			struct circle_info {
				float angle;
				std::wstring text;
				rgba color;
			};

			std::vector<circle_info> textual_infos;

			if (v == watched_character) {
				auto examine_item_slot = [&textual_infos, &push_angles, &circle_hud, &state](inventory_slot_id id, float lower_outside, float max_angular_length, bool ccw) {
					if (id.alive() && id.has_items()) {
						auto item = id->items_inside[0];

						auto maybe_magazine_slot = item[slot_function::GUN_DETACHABLE_MAGAZINE];
						auto chamber_slot = item[slot_function::GUN_CHAMBER];

						float ammo_ratio = 0.f;
						int charges = 0;
						float total_space_available = 0.f;
						float total_actual_free_space = 0.f;

						if (maybe_magazine_slot.alive() && maybe_magazine_slot.has_items()) {
							auto mag = maybe_magazine_slot->items_inside[0];
							auto ammo_depo = mag[slot_function::ITEM_DEPOSIT];
							charges += count_charges_in_deposit(mag);

							total_space_available += ammo_depo->space_available;
							total_actual_free_space += ammo_depo->calculate_free_space_with_children();
						}

						if (chamber_slot.alive()) {
							charges += count_charges_inside(chamber_slot);

							total_space_available += chamber_slot->space_available;
							total_actual_free_space += chamber_slot->calculate_free_space_with_children();
						}

						if (total_space_available > 0) {
							ammo_ratio = 1 - (total_actual_free_space / total_space_available);

							auto redviolet = augs::violet;
							redviolet.r = 200;
							circle_hud.color = augs::interp(augs::white, redviolet, (1 - ammo_ratio)* (1 - ammo_ratio));
							circle_hud.color.a = 200;
							circle_hud.draw(state);

							circle_info new_info;

							auto upper_outside = lower_outside + max_angular_length;

							auto empty_amount = (1 - ammo_ratio) * max_angular_length;

							if (!ccw) {
								push_angles(lower_outside, upper_outside, lower_outside, lower_outside + ammo_ratio * max_angular_length);
								new_info.angle = upper_outside - empty_amount/2;
							}
							else {
								push_angles(lower_outside, upper_outside, upper_outside - ammo_ratio * max_angular_length, upper_outside);
								new_info.angle = lower_outside + empty_amount / 2;
							}

							new_info.text = augs::to_wstring(charges);
							new_info.color = circle_hud.color;

							textual_infos.push_back(new_info);
						}
					}
				};

				examine_item_slot(v[slot_function::SECONDARY_HAND], starting_health_angle + 90 + 22.5, 90, false);
				examine_item_slot(v[slot_function::PRIMARY_HAND], starting_health_angle - 90 - 22.5, 90, true);
			}

			int radius = (*assets::HUD_CIRCULAR_BAR_MEDIUM).get_size().x / 2;

			int empty_health_amount = (1 - sentience->health_ratio()) * 90;

			textual_infos.push_back({ starting_health_angle + 90 - empty_health_amount/2, augs::to_wstring(sentience->health), health_col });
			textual_infos.push_back({ starting_health_angle, description_of_entity(v).name, health_col });

			for (auto& in : textual_infos) {
				if (in.text.empty()) continue;

				augs::gui::text_drawer health_points;
				health_points.set_text(augs::gui::text::format(in.text, augs::gui::text::style(assets::GUI_FONT, in.color)));

				auto circle_displacement_length = health_points.get_bbox().bigger_side() + radius;
				vec2i screen_space_circle_center = r.get_screen_space(transform.pos);

				health_points.pos = screen_space_circle_center + vec2().set_from_degrees(in.angle).set_length(circle_displacement_length);

				health_points.draw_stroke(circular_bars_information);
				health_points.draw(circular_bars_information);
			}
		}
	}
}

void immediate_hud::draw_circular_bars_information(messages::camera_render_request_message r) {
	r.state.output->triangles.insert(r.state.output->triangles.begin(), circular_bars_information.begin(), circular_bars_information.end());
}

void immediate_hud::acquire_game_events(augs::world& w) {
	auto& healths = w.get_message_queue<messages::health_event>();

	for (auto& h : healths) {
		vertically_flying_number vn;
		vn.time_of_occurence = w.get_current_timestamp();
		vn.value = h.effective_amount;
		vn.maximum_duration_seconds = 0.7;

		augs::rgba col;

		if (h.target == messages::health_event::HEALTH) {
			if (h.effective_amount > 0) {
				col = red;
			}
			else col = green;
		}
		else
			continue;

		vn.text.set_text(augs::gui::text::format(augs::to_wstring(std::abs(vn.value)), augs::gui::text::style(assets::GUI_FONT, col)));
		vn.transform.pos = h.point_of_impact;

		recent_vertically_flying_numbers.push_back(vn);

		pure_color_highlight ph;
		ph.time_of_occurence = w.get_current_timestamp();
		ph.target = h.subject;
		ph.starting_alpha_ratio = std::min(1.f, h.ratio_to_maximum_value * 15);
		ph.maximum_duration_seconds = 0.3;
		ph.color = col;

		erase_remove(recent_pure_color_highlights, [&ph](const pure_color_highlight& h) { return h.target == ph.target; });
		recent_pure_color_highlights.push_back(ph);
	}
}

double immediate_hud::get_current_time(messages::camera_render_request_message msg) const {
	auto& world = msg.camera->get_owner_world();
	return world.get_current_timestamp() + world.parent_overworld.fixed_delta_milliseconds() / 1000 * world.parent_overworld.view_interpolation_ratio();
}

void immediate_hud::draw_vertically_flying_numbers(messages::camera_render_request_message msg) {
	auto& target = renderer::get_current();

	auto current_time = get_current_time(msg);

	for (auto& r : recent_vertically_flying_numbers) {
		auto passed = current_time - r.time_of_occurence;
		auto ratio =  passed / r.maximum_duration_seconds;

		r.text.pos = msg.get_screen_space((r.transform.pos - vec2(0, sqrt(passed) * 150.f)));

		r.text.draw_stroke(msg.state.output->triangles);
		r.text.draw(msg.state.output->triangles);
	}

	auto timeout_lambda = [current_time](const game_event_visualization& v) {
		return (current_time - v.time_of_occurence) > v.maximum_duration_seconds;
	};

	erase_remove(recent_vertically_flying_numbers, timeout_lambda);
	erase_remove(recent_pure_color_highlights, timeout_lambda);
}

void immediate_hud::draw_pure_color_highlights(messages::camera_render_request_message msg) {
	auto current_time = get_current_time(msg);

	for (auto& r : recent_pure_color_highlights) {
		auto& col = r.target->get<components::sprite>().color;
		auto prevcol = col;
		col = r.color;

		auto passed = current_time - r.time_of_occurence;
		auto ratio = passed / r.maximum_duration_seconds;

		col.a = 255 * (1-ratio) * r.starting_alpha_ratio;
		render_system::standard_draw_entity(r.target, msg.state);
		col = prevcol;
	}

	//msg.state.output->triangles.insert(msg.state.output->triangles.begin(), pure_color_highlights.begin(), pure_color_highlights.end());
}<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS loadenv01 (1.2.28); FILE MERGED 2004/03/22 09:07:51 as 1.2.28.2: RESYNC: (1.2-1.3); FILE MERGED 2004/03/15 06:04:06 as 1.2.28.1: #i24378# use new MediaDescriptor class and constants<commit_after><|endoftext|>


<commit_before>#include "analysis.h"

/**
 * @brief POI::POI
 */
POI::POI(){}

/**
 * @brief POI::add_detections
 * Adds OOIs for a specific frame in a POI.
 * @param frame_num
 * @param detections
 */
void POI::add_detections(int frame_num, std::vector<OOI> detections) {
    if (start_frame == -1)
        start_frame = frame_num;
    OOIs[frame_num] = detections;
}

/**
 * @brief POI::set_end_frame
 * Sets the end frame of the POI.
 * @param frame_num
 */
void POI::set_end_frame(int frame_num) {
    end_frame = frame_num;
}

/**
 * @brief POI::read
 * Reads POI from json format.
 * @param json
 */
void POI::read(const QJsonObject& json) {
    // TODO
    this->start_frame = json["start"].toInt();
    this->end_frame = json["end"].toInt();
    for(int i = start_frame; i != end_frame; i++){
        QJsonArray json_frame_OOIs = json[QString::number(i)];
        std::vector<OOI> oois;
        for(int j  = 0; j = json_frame_OOIs.size(); j++){
            OOI ooi;
            ooi.read(json_frame_OOIs[j]);
            oois.push_back(ooi);
        }
        this->OOIs.insert(std::make_pair(i, oois));
    }
}

/**
 * @brief POI::write
 * Writes POI to json format.
 * @param json
 */
void POI::write(QJsonObject& json) {
    json["start"] = start_frame;
    json["end"] = end_frame;

    for(const auto& ooi_pair : OOIs){
        QJsonArray json_frame_OOIs;
        int frame = ooi_pair.first;
        std::vector<OOI> oois = ooi_pair.second;
        for (OOI o : oois) {
            QJsonObject json_ooi;
            o.write(json_ooi);
            json_frame_OOIs.append(json_ooi);
        }
        json[QString::number(frame)] = json_frame_OOIs;
    }
}

/**
 * @brief OOI::OOI
 */
OOI::OOI(){}

/**
 * @brief OOI::OOI
 * @param upper_left
 * @param down_right
 */
OOI::OOI(std::pair<int, int> upper_left, std::pair<int, int> down_right){
    this->upper_left = upper_left;
    this->lower_right = down_right;
}

/**
 * @brief OOI::OOI
 * @param upper_left
 * @param height
 * @param width
 */
OOI::OOI(std::pair<int, int> upper_left, int height, int width){
    this->upper_left = upper_left;
    this ->lower_right = std::make_pair(upper_left.second + width, upper_left.second + height);
}

/**
 * @brief OOI::OOI
 * Creates an OOI from a cv::Rect.
 * @param rect
 */
OOI::OOI(cv::Rect rect) {
    upper_left = std::make_pair(rect.x, rect.y);
    lower_right = std::make_pair(rect.x + rect.width, rect.y + rect.height);
}

/**
 * @brief OOI::read
 * Reads OOI from json format.
 * @param json
 */
void OOI::read(const QJsonObject &json){
    this->upper_left.first = json["UL_X"].toInt();
    this->upper_left.second = json["UL_Y"].toInt();

    this->lower_right.first = json["LR_X"].toInt();
    this->lower_right.second = json["LR_Y"].toInt();
}

/**
 * @brief OOI::write
 * Writes OOI to json format.
 * @param json
 */
void OOI::write(QJsonObject &json){
    json["UL_X"] = this->upper_left.first;
    json["UL_Y"] = this->upper_left.second;

    json["LR_X"] = this->lower_right.first;
    json["LR_Y"] = this->lower_right.second;
}

/**
 * @brief OOI::get_rect
 * Returns the rectangle specified by the OOI.
 * @return
 */
cv::Rect OOI::get_rect() {
    return cv::Rect(upper_left.first, upper_left.second, lower_right.first - upper_left.first,
                      lower_right.second - upper_left.second);
}

/**
 * @brief Analysis::Analysis
 */
Analysis::Analysis() {
}

/**
 * @brief Analysis::Analysis
 * Copy constructor. Needed for signals and slots.
 * @param obj
 */
Analysis::Analysis(const Analysis &obj) {
    POIs = obj.POIs;
    type = obj.type;
}

/**
 * @brief Analysis::~Analysis
 */
Analysis::~Analysis() {
}

/**
 * @brief Analysis::add_POI
 * Adds a POI to the analysis.
 * @param poi
 */
void Analysis::add_POI(POI poi){
    this->POIs.push_back(poi);
}

/**
 * @brief Analysis::read
 * Reads analysis from json format.
 * @param json
 */
void Analysis::read(const QJsonObject &json){
    this->type = (ANALYSIS_TYPE)json["analysis"].toInt();
    QJsonArray json_pois = json["POI:s"].toArray();
    for (int i = 0; i < json_pois.size(); ++i) {
        QJsonObject json_poi = json_pois[i].toObject();
        POI poi;
        POI.read(json_poi);
        this->add_POI(poi);
    }
}

/**
 * @brief Analysis::write
 * Writes analysis to json format.
 * @param json
 */
void Analysis::write(QJsonObject &json){
    json["type"] = this->type;
    QJsonArray json_POIs;
    for(auto it = this->POIs.begin(); it != this->POIs.end(); it++){
        QJsonObject json_POI;
        POI p = *it;
        p.write(json_POI);
        json_POIs.append(json_POI);
    }
    json["POI:s"] = json_POIs;
}

/**
 * @brief Analysis::get_detections_on_frame
 * Returns all detections on a specified frame in the analysed video.
 * @param frame_num
 * @return
 */
std::vector<cv::Rect> Analysis::get_detections_on_frame(int frame_num) {
    std::vector<cv::Rect> rects;
    for (POI p : POIs) {
        if (frame_num >= p.start_frame && frame_num <= p.end_frame) {
            std::vector<OOI> oois = p.OOIs[frame_num];
            for (OOI o : oois) {
                rects.push_back(o.get_rect());
            }
            break;
        }
    }
    return rects;
}
<commit_msg>woops, compiles now<commit_after>#include "analysis.h"

/**
 * @brief POI::POI
 */
POI::POI(){}

/**
 * @brief POI::add_detections
 * Adds OOIs for a specific frame in a POI.
 * @param frame_num
 * @param detections
 */
void POI::add_detections(int frame_num, std::vector<OOI> detections) {
    if (start_frame == -1)
        start_frame = frame_num;
    OOIs[frame_num] = detections;
}

/**
 * @brief POI::set_end_frame
 * Sets the end frame of the POI.
 * @param frame_num
 */
void POI::set_end_frame(int frame_num) {
    end_frame = frame_num;
}

/**
 * @brief POI::read
 * Reads POI from json format.
 * @param json
 */
void POI::read(const QJsonObject& json) {
    // TODO
    this->start_frame = json["start"].toInt();
    this->end_frame = json["end"].toInt();
    for(int i = start_frame; i != end_frame; i++){
        QJsonArray json_frame_OOIs = json[QString::number(i)].toArray();
        std::vector<OOI> oois;
        for(int j  = 0; j = json_frame_OOIs.size(); j++){
            OOI ooi;
            ooi.read(json_frame_OOIs[j].toObject());
            oois.push_back(ooi);
        }
        this->OOIs.insert(std::make_pair(i, oois));
    }
}

/**
 * @brief POI::write
 * Writes POI to json format.
 * @param json
 */
void POI::write(QJsonObject& json) {
    json["start"] = start_frame;
    json["end"] = end_frame;

    for(const auto& ooi_pair : OOIs){
        QJsonArray json_frame_OOIs;
        int frame = ooi_pair.first;
        std::vector<OOI> oois = ooi_pair.second;
        for (OOI o : oois) {
            QJsonObject json_ooi;
            o.write(json_ooi);
            json_frame_OOIs.append(json_ooi);
        }
        json[QString::number(frame)] = json_frame_OOIs;
    }
}

/**
 * @brief OOI::OOI
 */
OOI::OOI(){}

/**
 * @brief OOI::OOI
 * @param upper_left
 * @param down_right
 */
OOI::OOI(std::pair<int, int> upper_left, std::pair<int, int> down_right){
    this->upper_left = upper_left;
    this->lower_right = down_right;
}

/**
 * @brief OOI::OOI
 * @param upper_left
 * @param height
 * @param width
 */
OOI::OOI(std::pair<int, int> upper_left, int height, int width){
    this->upper_left = upper_left;
    this ->lower_right = std::make_pair(upper_left.second + width, upper_left.second + height);
}

/**
 * @brief OOI::OOI
 * Creates an OOI from a cv::Rect.
 * @param rect
 */
OOI::OOI(cv::Rect rect) {
    upper_left = std::make_pair(rect.x, rect.y);
    lower_right = std::make_pair(rect.x + rect.width, rect.y + rect.height);
}

/**
 * @brief OOI::read
 * Reads OOI from json format.
 * @param json
 */
void OOI::read(const QJsonObject &json){
    this->upper_left.first = json["UL_X"].toInt();
    this->upper_left.second = json["UL_Y"].toInt();

    this->lower_right.first = json["LR_X"].toInt();
    this->lower_right.second = json["LR_Y"].toInt();
}

/**
 * @brief OOI::write
 * Writes OOI to json format.
 * @param json
 */
void OOI::write(QJsonObject &json){
    json["UL_X"] = this->upper_left.first;
    json["UL_Y"] = this->upper_left.second;

    json["LR_X"] = this->lower_right.first;
    json["LR_Y"] = this->lower_right.second;
}

/**
 * @brief OOI::get_rect
 * Returns the rectangle specified by the OOI.
 * @return
 */
cv::Rect OOI::get_rect() {
    return cv::Rect(upper_left.first, upper_left.second, lower_right.first - upper_left.first,
                      lower_right.second - upper_left.second);
}

/**
 * @brief Analysis::Analysis
 */
Analysis::Analysis() {
}

/**
 * @brief Analysis::Analysis
 * Copy constructor. Needed for signals and slots.
 * @param obj
 */
Analysis::Analysis(const Analysis &obj) {
    POIs = obj.POIs;
    type = obj.type;
}

/**
 * @brief Analysis::~Analysis
 */
Analysis::~Analysis() {
}

/**
 * @brief Analysis::add_POI
 * Adds a POI to the analysis.
 * @param poi
 */
void Analysis::add_POI(POI poi){
    this->POIs.push_back(poi);
}

/**
 * @brief Analysis::read
 * Reads analysis from json format.
 * @param json
 */
void Analysis::read(const QJsonObject &json){
    this->type = (ANALYSIS_TYPE)json["analysis"].toInt();
    QJsonArray json_pois = json["POI:s"].toArray();
    for (int i = 0; i < json_pois.size(); ++i) {
        QJsonObject json_poi = json_pois[i].toObject();
        POI poi;
        poi.read(json_poi);
        this->add_POI(poi);
    }
}

/**
 * @brief Analysis::write
 * Writes analysis to json format.
 * @param json
 */
void Analysis::write(QJsonObject &json){
    json["type"] = this->type;
    QJsonArray json_POIs;
    for(auto it = this->POIs.begin(); it != this->POIs.end(); it++){
        QJsonObject json_POI;
        POI p = *it;
        p.write(json_POI);
        json_POIs.append(json_POI);
    }
    json["POI:s"] = json_POIs;
}

/**
 * @brief Analysis::get_detections_on_frame
 * Returns all detections on a specified frame in the analysed video.
 * @param frame_num
 * @return
 */
std::vector<cv::Rect> Analysis::get_detections_on_frame(int frame_num) {
    std::vector<cv::Rect> rects;
    for (POI p : POIs) {
        if (frame_num >= p.start_frame && frame_num <= p.end_frame) {
            std::vector<OOI> oois = p.OOIs[frame_num];
            for (OOI o : oois) {
                rects.push_back(o.get_rect());
            }
            break;
        }
    }
    return rects;
}
<|endoftext|>


<commit_before>#include <renderer.h>
#include <rasterizer.h>
#include <s1516.h>

#include <stdio.h>

#define FLYTHROUGH_CAMERA_IMPLEMENTATION
#include <flythrough_camera.h>

#include <Windows.h>
#include <DirectXMath.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <imgui.h>
#include <imgui_impl_win32_gl.h>

#pragma comment(lib, "OpenGL32.lib")
#pragma comment(lib, "glu32.lib")

LRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    if (ImGui_ImplWin32GL_WndProcHandler(hWnd, message, wParam, lParam))
        return true;

    switch (message)
    {
    case WM_CLOSE:
        ExitProcess(0);
        return 0;
    case WM_SYSCOMMAND:
        if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
            return 0;
        break;
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
}

HDC g_hDC;

void init_window(int32_t width, int32_t height)
{
    WNDCLASSEX wc;
    ZeroMemory(&wc, sizeof(wc));
    wc.cbSize = sizeof(wc);
    wc.style = CS_OWNDC;
    wc.lpfnWndProc = MyWndProc;
    wc.hInstance = GetModuleHandle(NULL);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
    wc.lpszClassName = TEXT("WindowClass");
    RegisterClassEx(&wc);

    RECT wr = { 0, 0, width, height };
    AdjustWindowRect(&wr, 0, FALSE);
    HWND hWnd = CreateWindowEx(
        0, TEXT("WindowClass"),
        TEXT("viewer"),
        WS_OVERLAPPEDWINDOW,
        0, 0, wr.right - wr.left, wr.bottom - wr.top,
        0, 0, GetModuleHandle(NULL), 0);

    PIXELFORMATDESCRIPTOR pfd;
    ZeroMemory(&pfd, sizeof(pfd));
    pfd.nSize = sizeof(pfd);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.iLayerType = PFD_MAIN_PLANE;

    g_hDC = GetDC(hWnd);

    int chosenPixelFormat = ChoosePixelFormat(g_hDC, &pfd);
    SetPixelFormat(g_hDC, chosenPixelFormat, &pfd);

    HGLRC hGLRC = wglCreateContext(g_hDC);
    wglMakeCurrent(g_hDC, hGLRC);

    ShowWindow(hWnd, SW_SHOWNORMAL);

    ImGui_ImplWin32GL_Init(hWnd);
}

int main()
{
    int fbwidth = 1024;
    int fbheight = 768;

    SetProcessDPIAware();
    init_window(fbwidth, fbheight);

    renderer_t* rd = new_renderer(fbwidth, fbheight);

    scene_t* sc = new_scene();
    uint32_t first_model_id, num_added_models;
    scene_add_models(sc, "assets/cube/cube.obj", "assets/cube/", &first_model_id, &num_added_models);
    for (uint32_t model_id = first_model_id; model_id < first_model_id + num_added_models; model_id++)
    {
        uint32_t instance_id;
        scene_add_instance(sc, model_id, &instance_id);
    }

    // compute projection matrix with DirectXMath because lazy
    {
        DirectX::XMMATRIX proj = DirectX::XMMatrixPerspectiveFovLH(DirectX::XMConvertToRadians(70.0f), (float)fbwidth / fbheight, 0.01f, 10.0f);
        DirectX::XMFLOAT4X4 proj4x4;
        DirectX::XMStoreFloat4x4(&proj4x4, proj);

        int32_t fx_proj[16];
        for (int32_t i = 0; i < 16; i++)
        {
            fx_proj[i] = s1516_flt(*((float*)proj4x4.m + i));
        }
        scene_set_projection(sc, fx_proj);
    }

    float eye[3] = { 0.0f, 0.0f, 3.0f };
    float look[3] = { 0.0f, 0.0f, -1.0f };
    const float up[3] = { 0.0f, 1.0f, 0.0f };

    LARGE_INTEGER then, now, freq;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&then);

    POINT oldcursor;
    GetCursorPos(&oldcursor);

    bool show_tiles = true;

    uint8_t* rgba8_pixels = (uint8_t*)malloc(fbwidth * fbheight * 4);
    assert(rgba8_pixels);

    // readback framebuffer contents
    framebuffer_t* fb = renderer_get_framebuffer(rd);

    while (!(GetAsyncKeyState(VK_ESCAPE) & 0x8000))
    {
        MSG msg;
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        ImGui_ImplWin32GL_NewFrame();

        if (ImGui::Begin("Toolbox"))
        {
            ImGui::Checkbox("Show tiles", &show_tiles);
            ImGui::End();
        }

        QueryPerformanceCounter(&now);
        float delta_time_sec = (float)(now.QuadPart - then.QuadPart) / freq.QuadPart;

        POINT cursor;
        GetCursorPos(&cursor);

        // only move and rotate camera when right mouse button is pressed
        float activated = (GetAsyncKeyState(VK_RBUTTON) & 0x8000) ? 1.0f : 0.0f;

        float view[16];
        flythrough_camera_update(
            eye, look, up, view,
            delta_time_sec,
            10.0f * ((GetAsyncKeyState(VK_LSHIFT) & 0x8000) ? 2.0f : 1.0f) * activated,
            0.5f * activated,
            80.0f,
            cursor.x - oldcursor.x, cursor.y - oldcursor.y,
            GetAsyncKeyState('W') & 0x8000, GetAsyncKeyState('A') & 0x8000, GetAsyncKeyState('S') & 0x8000, GetAsyncKeyState('D') & 0x8000,
            GetAsyncKeyState(VK_SPACE) & 0x8000, GetAsyncKeyState(VK_LCONTROL) & 0x8000,
            FLYTHROUGH_CAMERA_LEFT_HANDED_BIT);

        int32_t view_s1516[16];
        for (int32_t i = 0; i < 16; i++)
        {
            view_s1516[i] = s1516_flt(view[i]);
        }
        scene_set_view(sc, view_s1516);

        renderer_render_scene(rd, sc);

        // render rasterization to screen
        {
            framebuffer_t* fb = renderer_get_framebuffer(rd);
            framebuffer_pack_row_major(fb, 0, 0, fbwidth, fbheight, pixelformat_r8g8b8a8_unorm, rgba8_pixels);
            // flip the rows to appease the OpenGL gods
            for (int32_t row = 0; row < fbheight / 2; row++)
            {
                for (int32_t col = 0; col < fbwidth; col++)
                {
                    uint32_t tmp = *(uint32_t*)&rgba8_pixels[(row * fbwidth + col) * 4];
                    *(uint32_t*)&rgba8_pixels[(row * fbwidth + col) * 4] = *(uint32_t*)&rgba8_pixels[((fbheight - row - 1) * fbwidth + col) * 4];
                    *(uint32_t*)&rgba8_pixels[((fbheight - row - 1) * fbwidth + col) * 4] = tmp;
                }
            }
            glDrawPixels(fbwidth, fbheight, GL_RGBA, GL_UNSIGNED_BYTE, rgba8_pixels);
        }

        // draw lines showing tiles
        if (show_tiles)
        {
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            gluOrtho2D(0.0, (GLdouble)fbwidth, (GLdouble)fbheight, 0.0);
            glMatrixMode(GL_MODELVIEW);
            glLoadIdentity();
            glBegin(GL_LINES);
            glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
            for (int i = 0; i < fbwidth / 128; i++)
            {
                glVertex2f(i * 128.0f, 0.0f);
                glVertex2f(i * 128.0f, (float)fbheight);
            }
            for (int i = 0; i < fbheight / 128; i++)
            {
                glVertex2f(0.0f, i * 128.0f);
                glVertex2f((float)fbwidth, i * 128.0f);
            }
            glEnd();
            glBlendFunc(GL_ONE, GL_ZERO);
            glDisable(GL_BLEND);
        }

        ImGui::Render();

        SwapBuffers(g_hDC);

        then = now;
        oldcursor = cursor;
    }

    free(rgba8_pixels);

    delete_scene(sc);
    delete_renderer(rd);

    return 0;
}<commit_msg>add raster time info<commit_after>#include <renderer.h>
#include <rasterizer.h>
#include <s1516.h>

#include <stdio.h>

#define FLYTHROUGH_CAMERA_IMPLEMENTATION
#include <flythrough_camera.h>

#include <Windows.h>
#include <DirectXMath.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <imgui.h>
#include <imgui_impl_win32_gl.h>

#pragma comment(lib, "OpenGL32.lib")
#pragma comment(lib, "glu32.lib")

LRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    if (ImGui_ImplWin32GL_WndProcHandler(hWnd, message, wParam, lParam))
        return true;

    switch (message)
    {
    case WM_CLOSE:
        ExitProcess(0);
        return 0;
    case WM_SYSCOMMAND:
        if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
            return 0;
        break;
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
}

HDC g_hDC;

void init_window(int32_t width, int32_t height)
{
    WNDCLASSEX wc;
    ZeroMemory(&wc, sizeof(wc));
    wc.cbSize = sizeof(wc);
    wc.style = CS_OWNDC;
    wc.lpfnWndProc = MyWndProc;
    wc.hInstance = GetModuleHandle(NULL);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
    wc.lpszClassName = TEXT("WindowClass");
    RegisterClassEx(&wc);

    RECT wr = { 0, 0, width, height };
    AdjustWindowRect(&wr, 0, FALSE);
    HWND hWnd = CreateWindowEx(
        0, TEXT("WindowClass"),
        TEXT("viewer"),
        WS_OVERLAPPEDWINDOW,
        0, 0, wr.right - wr.left, wr.bottom - wr.top,
        0, 0, GetModuleHandle(NULL), 0);

    PIXELFORMATDESCRIPTOR pfd;
    ZeroMemory(&pfd, sizeof(pfd));
    pfd.nSize = sizeof(pfd);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.iLayerType = PFD_MAIN_PLANE;

    g_hDC = GetDC(hWnd);

    int chosenPixelFormat = ChoosePixelFormat(g_hDC, &pfd);
    SetPixelFormat(g_hDC, chosenPixelFormat, &pfd);

    HGLRC hGLRC = wglCreateContext(g_hDC);
    wglMakeCurrent(g_hDC, hGLRC);

    ShowWindow(hWnd, SW_SHOWNORMAL);

    ImGui_ImplWin32GL_Init(hWnd);
}

int main()
{
    int fbwidth = 1024;
    int fbheight = 768;

    SetProcessDPIAware();
    init_window(fbwidth, fbheight);

    renderer_t* rd = new_renderer(fbwidth, fbheight);

    scene_t* sc = new_scene();
    uint32_t first_model_id, num_added_models;
    scene_add_models(sc, "assets/cube/cube.obj", "assets/cube/", &first_model_id, &num_added_models);
    for (uint32_t model_id = first_model_id; model_id < first_model_id + num_added_models; model_id++)
    {
        uint32_t instance_id;
        scene_add_instance(sc, model_id, &instance_id);
    }

    // compute projection matrix with DirectXMath because lazy
    {
        DirectX::XMMATRIX proj = DirectX::XMMatrixPerspectiveFovLH(DirectX::XMConvertToRadians(70.0f), (float)fbwidth / fbheight, 0.01f, 10.0f);
        DirectX::XMFLOAT4X4 proj4x4;
        DirectX::XMStoreFloat4x4(&proj4x4, proj);

        int32_t fx_proj[16];
        for (int32_t i = 0; i < 16; i++)
        {
            fx_proj[i] = s1516_flt(*((float*)proj4x4.m + i));
        }
        scene_set_projection(sc, fx_proj);
    }

    float eye[3] = { 0.0f, 0.0f, 3.0f };
    float look[3] = { 0.0f, 0.0f, -1.0f };
    const float up[3] = { 0.0f, 1.0f, 0.0f };

    LARGE_INTEGER then, now, freq;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&then);

    POINT oldcursor;
    GetCursorPos(&oldcursor);

    bool show_tiles = true;

    uint8_t* rgba8_pixels = (uint8_t*)malloc(fbwidth * fbheight * 4);
    assert(rgba8_pixels);

    // readback framebuffer contents
    framebuffer_t* fb = renderer_get_framebuffer(rd);

    while (!(GetAsyncKeyState(VK_ESCAPE) & 0x8000))
    {
        MSG msg;
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        ImGui_ImplWin32GL_NewFrame();

        if (ImGui::Begin("Toolbox"))
        {
            ImGui::Checkbox("Show tiles", &show_tiles);
            ImGui::End();
        }

        QueryPerformanceCounter(&now);
        float delta_time_sec = (float)(now.QuadPart - then.QuadPart) / freq.QuadPart;

        POINT cursor;
        GetCursorPos(&cursor);

        // only move and rotate camera when right mouse button is pressed
        float activated = (GetAsyncKeyState(VK_RBUTTON) & 0x8000) ? 1.0f : 0.0f;

        float view[16];
        flythrough_camera_update(
            eye, look, up, view,
            delta_time_sec,
            10.0f * ((GetAsyncKeyState(VK_LSHIFT) & 0x8000) ? 2.0f : 1.0f) * activated,
            0.5f * activated,
            80.0f,
            cursor.x - oldcursor.x, cursor.y - oldcursor.y,
            GetAsyncKeyState('W') & 0x8000, GetAsyncKeyState('A') & 0x8000, GetAsyncKeyState('S') & 0x8000, GetAsyncKeyState('D') & 0x8000,
            GetAsyncKeyState(VK_SPACE) & 0x8000, GetAsyncKeyState(VK_LCONTROL) & 0x8000,
            FLYTHROUGH_CAMERA_LEFT_HANDED_BIT);

        int32_t view_s1516[16];
        for (int32_t i = 0; i < 16; i++)
        {
            view_s1516[i] = s1516_flt(view[i]);
        }
        scene_set_view(sc, view_s1516);

        LARGE_INTEGER before_raster, after_raster;
        QueryPerformanceCounter(&before_raster);
        renderer_render_scene(rd, sc);
        QueryPerformanceCounter(&after_raster);

        // render rasterization to screen
        {
            framebuffer_t* fb = renderer_get_framebuffer(rd);
            framebuffer_pack_row_major(fb, 0, 0, fbwidth, fbheight, pixelformat_r8g8b8a8_unorm, rgba8_pixels);
            // flip the rows to appease the OpenGL gods
            for (int32_t row = 0; row < fbheight / 2; row++)
            {
                for (int32_t col = 0; col < fbwidth; col++)
                {
                    uint32_t tmp = *(uint32_t*)&rgba8_pixels[(row * fbwidth + col) * 4];
                    *(uint32_t*)&rgba8_pixels[(row * fbwidth + col) * 4] = *(uint32_t*)&rgba8_pixels[((fbheight - row - 1) * fbwidth + col) * 4];
                    *(uint32_t*)&rgba8_pixels[((fbheight - row - 1) * fbwidth + col) * 4] = tmp;
                }
            }
            glDrawPixels(fbwidth, fbheight, GL_RGBA, GL_UNSIGNED_BYTE, rgba8_pixels);
        }

        // draw lines showing tiles
        if (show_tiles)
        {
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            gluOrtho2D(0.0, (GLdouble)fbwidth, (GLdouble)fbheight, 0.0);
            glMatrixMode(GL_MODELVIEW);
            glLoadIdentity();
            glBegin(GL_LINES);
            glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
            for (int i = 0; i < fbwidth / 128; i++)
            {
                glVertex2f(i * 128.0f, 0.0f);
                glVertex2f(i * 128.0f, (float)fbheight);
            }
            for (int i = 0; i < fbheight / 128; i++)
            {
                glVertex2f(0.0f, i * 128.0f);
                glVertex2f((float)fbwidth, i * 128.0f);
            }
            glEnd();
            glBlendFunc(GL_ONE, GL_ZERO);
            glDisable(GL_BLEND);
        }

        if (ImGui::Begin("Info"))
        {
            LONGLONG raster_time = after_raster.QuadPart - before_raster.QuadPart;
            LONGLONG raster_time_us = raster_time * 1000000 / freq.QuadPart;
            ImGui::Text("Raster time: %llu microseconds", raster_time_us);
            ImGui::End();
        }

        ImGui::Render();

        SwapBuffers(g_hDC);

        then = now;
        oldcursor = cursor;
    }

    free(rgba8_pixels);

    delete_scene(sc);
    delete_renderer(rd);

    return 0;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: brwview.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: oj $ $Date: 2002-02-11 12:46:43 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SBX_BRWVIEW_HXX
#define _SBX_BRWVIEW_HXX

#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif

#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif

#ifndef _TOOLS_RESID_HXX //autogen wg. ResId
#include <tools/resid.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef DBAUI_DATAVIEW_HXX
#include "dataview.hxx"
#endif

namespace com { namespace sun { namespace star { namespace awt {
    class XControl;
    class XControlContainer;
    class XControlModel;
}}}}

// =========================================================================
class ResMgr;
class Splitter;

namespace dbaui
{
    class DBTreeListModel;
    class DBTreeView;
    class SbaGridControl;

    class UnoDataBrowserView : public ODataView
    {
    protected:
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >                 m_xGrid;            // our grid's UNO representation
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >        m_xMe;              // our own UNO representation
        DBTreeView*             m_pTreeView;
        Splitter*               m_pSplitter;
        SbaGridControl*         m_pVclControl;  // our grid's VCL representation
        Window*                 m_pStatus;

        DECL_LINK( SplitHdl, void* );
    // attribute access
    public:
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >             getGridControl() const  { return m_xGrid; }
        SbaGridControl*         getVclControl() const   { return m_pVclControl; }

    public:
        UnoDataBrowserView( Window* pParent,
                            IController* _pController,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
        virtual ~UnoDataBrowserView();

        /// late construction
        virtual void Construct(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& xModel);

        /** as columns may be hidden there is a difference between a columns model pos and its view pos
            so we you may use these translation function
        */
        sal_uInt16 Model2ViewPos(sal_uInt16 nPos) const;
        sal_uInt16 View2ModelPos(sal_uInt16 nPos) const;
        /// for the same reason the view column count isn't the same as the model column count
        sal_uInt16 ViewColumnCount() const;

        void setSplitter(Splitter* _pSplitter);
        void setTreeView(DBTreeView* _pTreeView);

        void    showStatus( const String& _rStatus );
        void    hideStatus();

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >     getContainer() { return m_xMe; }

    protected:
        virtual long PreNotify( NotifyEvent& rNEvt );
        virtual void GetFocus();
        virtual void resizeDocumentView(Rectangle& rRect);
    };

    class BrowserViewStatusDisplay
    {
    protected:
        UnoDataBrowserView*     m_pView;

    public:
        BrowserViewStatusDisplay( UnoDataBrowserView* _pView, const String& _rStatus );
        ~BrowserViewStatusDisplay( );
    };
}
#endif // _SBX_BRWVIEW_HXX

<commit_msg>INTEGRATION: CWS insight01 (1.8.112); FILE MERGED 2004/03/11 09:04:03 oj 1.8.112.2: #111075# changes for closing 2004/02/27 08:40:24 oj 1.8.112.1: #111075# check for vcl control<commit_after>/*************************************************************************
 *
 *  $RCSfile: brwview.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 15:56:11 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SBX_BRWVIEW_HXX
#define _SBX_BRWVIEW_HXX

#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif

#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif

#ifndef _TOOLS_RESID_HXX //autogen wg. ResId
#include <tools/resid.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef DBAUI_DATAVIEW_HXX
#include "dataview.hxx"
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif

namespace com { namespace sun { namespace star { namespace awt {
    class XControl;
    class XControlContainer;
    class XControlModel;
}}}}

// =========================================================================
class ResMgr;
class Splitter;

namespace dbaui
{
    class DBTreeListModel;
    class DBTreeView;
    class SbaGridControl;

    class UnoDataBrowserView : public ODataView, public ::utl::OEventListenerAdapter
    {
    protected:
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >                 m_xGrid;            // our grid's UNO representation
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >        m_xMe;              // our own UNO representation
        DBTreeView*             m_pTreeView;
        Splitter*               m_pSplitter;
        mutable SbaGridControl* m_pVclControl;  // our grid's VCL representation
        Window*                 m_pStatus;

        DECL_LINK( SplitHdl, void* );
    // attribute access
    public:
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >             getGridControl() const  { return m_xGrid; }
        SbaGridControl*         getVclControl() const;

    public:
        UnoDataBrowserView( Window* pParent,
                            IController* _pController,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
        virtual ~UnoDataBrowserView();

        /// late construction
        virtual void Construct(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& xModel);

        /** as columns may be hidden there is a difference between a columns model pos and its view pos
            so we you may use these translation function
        */
        sal_uInt16 Model2ViewPos(sal_uInt16 nPos) const;
        sal_uInt16 View2ModelPos(sal_uInt16 nPos) const;
        /// for the same reason the view column count isn't the same as the model column count
        sal_uInt16 ViewColumnCount() const;

        void setSplitter(Splitter* _pSplitter);
        void setTreeView(DBTreeView* _pTreeView);

        void    showStatus( const String& _rStatus );
        void    hideStatus();

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >     getContainer() { return m_xMe; }

    protected:
        virtual long PreNotify( NotifyEvent& rNEvt );
        virtual void GetFocus();
        virtual void resizeDocumentView(Rectangle& rRect);
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );
    };

    class BrowserViewStatusDisplay
    {
    protected:
        UnoDataBrowserView*     m_pView;

    public:
        BrowserViewStatusDisplay( UnoDataBrowserView* _pView, const String& _rStatus );
        ~BrowserViewStatusDisplay( );
    };
}
#endif // _SBX_BRWVIEW_HXX

<|endoftext|>