<commit_before>#include "h5test.h"
#include "parallel_io.h"
#include "comm.h"
#include "cmdLineOptions.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "measure.h"
#include "t3pio.h"

struct Var_t
{
  const char * name;
  const char * descript;
};

Var_t varT[] =
  {
    {"T", "Temp in K"},
    {"p", "Pressure in N/m^2"},
    {"u", "X Velocity in m/s"},
    {"v", "Y Velocity in m/s"},
    {"w", "Z Velocity in m/s"},
    {"a", "A Velocity in m/s"},
    {"b", "B Velocity in m/s"},
    {"c", "C Velocity in m/s"},
    {"d", "D Velocity in m/s"},
    {"e", "E Velocity in m/s"},
  };

ParallelIO::ParallelIO()
  : m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),
    m_nIOUnits(1), m_stripeSz(-1), m_numvar(1), m_aggregators(0)
{}

#ifndef USE_HDF5
void ParallelIO::h5writer(CmdLineOptions& cmd)
{
  if (P.myProc == 0)
    printf("This program requires HDF5 which is not available => quitting\n");
}

void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
}

#else
void ParallelIO::h5writer(CmdLineOptions& cmd)
{

  hid_t   file_id;       //file      identifier
  hid_t   group_id;      //group     identifier
  hid_t   dset_id;       //Dataset   identifier
  hid_t   filespace;     //Dataspace id in file
  hid_t   memspace;      //Dataspace id in memory.
  hid_t   plist_id;      //Property List id
  hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1], rem;
  hsize_t is, num;
  int     ierr;
  MPI_Comm commF;
  H5FD_mpio_xfer_t  xfer_mode;   // HDF5 transfer mode (indep or collective)
  const char * fn = "UNSTRUCT.h5";

  // compute size info

  rem = cmd.globalSz % P.nProcs;
  if (P.myProc < rem)
    is = P.myProc * cmd.localSz;
  else
    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);

  double lSz     = 1.0;

  m_numvar    = cmd.nvar;
  num         = cmd.localSz;
  lSz         = num;
  count[0]    = 1;
  h5stride[0] = 1;
  starts[0]   = is;
  sz[0]       = num;
  gsz[0]      = cmd.globalSz;
  m_totalSz   = cmd.globalSz*m_numvar*sizeof(double);

  int iTotalSz = m_totalSz/(1024*1024);

  // Initialize data buffer
  double xk = num*P.myProc;

  double *data = new double[num];
  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t0, t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info  = MPI_INFO_NULL;
  MPI_Info infoF = MPI_INFO_NULL;

  MPI_Info_create(&info);
  MPI_Info_create(&infoF);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_STRIPE_COUNT,        cmd.stripes,
                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,
                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,
                                T3PIO_RESULTS,             &results);
    }

  xfer_mode = (cmd.collective) ? H5FD_MPIO_COLLECTIVE : H5FD_MPIO_INDEPENDENT;

  t0 = walltime();

  plist_id = H5Pcreate(H5P_FILE_ACCESS);
  H5Pset_fapl_mpio(plist_id, P.comm, info);

  // Create file collectively
  file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);

  MPI_File* pFH = NULL;
  ierr    = H5Fget_vfd_handle(file_id, H5P_DEFAULT, (void **) &pFH);
  ierr    = MPI_File_get_info(*pFH, &infoF);

  t3pio_extract_key_values(infoF, &results);
  m_nStripes = results.numStripes;
  m_nIOUnits = results.numIO;
  m_stripeSz = results.stripeSize;
  H5Pclose(plist_id);

  // Create Group
  group_id = H5Gcreate(file_id, "Solution", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

  std::string timeZ, timeL;
  dateZ(timeZ);
  add_attribute(group_id,"Zulu Time", timeZ.c_str());

  dateL(timeL);
  add_attribute(group_id,"Local Time", timeL.c_str());

  for (int ivar = 0; ivar < m_numvar; ++ivar)
    {

      // Create the dataspace for the dataset
      filespace = H5Screate_simple(1, &gsz[0], NULL);
      memspace  = H5Screate_simple(1, sz,      NULL);

      if (cmd.h5chunk)
        {
          plist_id = H5Pcreate(H5P_DATASET_CREATE);
          H5Pset_chunk(plist_id,1, sz);

          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, plist_id, H5P_DEFAULT);
          H5Pclose(plist_id);
          H5Sclose(filespace);

          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);
        }
      else if (cmd.h5slab)
        {
          // Create the dataset w/ default properties and close filespace
          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
          H5Sclose(filespace);

          // Select hyperslab in the file.
          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);
        }

      plist_id = H5Pcreate(H5P_DATASET_XFER);
      H5Pset_dxpl_mpio(plist_id, xfer_mode);

      add_attribute(dset_id, "Variable Description", varT[ivar].descript);

      t1   = walltime();

      herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,
                               plist_id, data);
      t2   = walltime();
      m_t += (t2 - t1);

      H5Dclose(dset_id);
      H5Sclose(filespace);
      H5Sclose(memspace);
      H5Pclose(plist_id);
    }

  m_totalTime = walltime() - t0;
  m_rate      = m_totalSz /(m_totalTime * 1024.0 * 1024.0);
  free(data);
  H5Gclose(group_id);
  H5Fclose(file_id);
  MPI_Info_free(&info);
  MPI_Info_free(&infoF);
}

void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
  hid_t attr_id, aspace_id, atype_id;
  hsize_t attrlen, num[1];

  attrlen = strlen(value);
  num[0]  = 1;

  atype_id = H5Tcopy(H5T_C_S1);
  H5Tset_size(atype_id, attrlen);

  aspace_id = H5Screate_simple(1,num, NULL);

  attr_id   = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);
  H5Awrite(attr_id, atype_id, value);
  H5Aclose(attr_id);
  H5Sclose(aspace_id);
}
#endif

void ParallelIO::MPIIOwriter(CmdLineOptions& cmd)
{

  MPI_File     fh;
  MPI_Offset   is, rem, offset;
  MPI_Datatype coreData, gblData, my_vector;
  MPI_Status   status;
  int          iTotalSz, ierr, nDim;
  int          sz[2], gsz[2], starts[2];
  const char*  fn = "UNSTRUCT.mpiio";

  rem = cmd.globalSz % P.nProcs;
  if (P.myProc < rem)
    is = P.myProc * cmd.localSz;
  else
    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);

  m_numvar      = 1;
  m_totalSz     = cmd.globalSz*m_numvar*sizeof(double);
  iTotalSz      = m_totalSz/(1024*1024);
  int    num    = cmd.localSz;
  double *data  = new double[num];
  double xk     = is;

  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t0, t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info  = MPI_INFO_NULL;
  MPI_Info infoF = MPI_INFO_NULL;
  MPI_Info_create(&info);
  MPI_Info_create(&infoF);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_STRIPE_COUNT,        cmd.stripes,
                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,
                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,
                                T3PIO_RESULTS,             &results);
      m_nIOUnits = results.numIO;
    }

  //nDim = 1;
  //offset = is*sizeof(double);
  //ierr = MPI_Type_contiguous(num, MPI_DOUBLE, &my_vector);
  //ierr = MPI_Type_commit(&my_vector);
  //ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, my_vector, "native", info);

  offset    = 0;
  nDim      = 2;
  sz[0]     = cmd.localSz/cmd.xwidth;
  sz[1]     = cmd.xwidth;
  gsz[0]    = cmd.globalSz/cmd.xwidth;
  gsz[1]    = cmd.xwidth;
  starts[0] = 0;
  starts[1] = 0;

  ierr = MPI_Type_create_subarray(nDim, sz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
                                  &coreData);
  ierr = MPI_Type_commit(&coreData);
  starts[0] = sz[0]*P.myProc;
  ierr = MPI_Type_create_subarray(nDim, gsz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
                                  &gblData);
  ierr = MPI_Type_commit(&gblData);

  t0 = walltime();

  ierr = MPI_File_open(P.comm, (char *) fn, MPI_MODE_WRONLY | MPI_MODE_CREATE, info, &fh);
  if (ierr)
    MPI_Abort(P.comm, -1);

  ierr = MPI_File_get_info(fh, &infoF);

  t3pio_extract_key_values(infoF, &results);
  m_aggregators = results.numIO;
  m_nStripes    = results.numStripes;
  m_stripeSz    = results.stripeSize;

  ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, gblData, "native", info);

  ierr = MPI_File_write_all(fh, &data[0], 1, coreData, &status);
  ierr = MPI_File_close(&fh);

  m_totalTime = walltime() - t0;
  m_rate      = m_totalSz/(m_totalTime * 1024.0 * 1024.0);
  MPI_Info_free(&info);
  MPI_Info_free(&infoF);
}

<commit_msg>report requested writers and actual writers for unstructTest<commit_after>#include "h5test.h"
#include "parallel_io.h"
#include "comm.h"
#include "cmdLineOptions.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "measure.h"
#include "t3pio.h"

struct Var_t
{
  const char * name;
  const char * descript;
};

Var_t varT[] =
  {
    {"T", "Temp in K"},
    {"p", "Pressure in N/m^2"},
    {"u", "X Velocity in m/s"},
    {"v", "Y Velocity in m/s"},
    {"w", "Z Velocity in m/s"},
    {"a", "A Velocity in m/s"},
    {"b", "B Velocity in m/s"},
    {"c", "C Velocity in m/s"},
    {"d", "D Velocity in m/s"},
    {"e", "E Velocity in m/s"},
  };

ParallelIO::ParallelIO()
  : m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),
    m_nIOUnits(1), m_stripeSz(-1), m_numvar(1), m_aggregators(0)
{}

#ifndef USE_HDF5
void ParallelIO::h5writer(CmdLineOptions& cmd)
{
  if (P.myProc == 0)
    printf("This program requires HDF5 which is not available => quitting\n");
}

void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
}

#else
void ParallelIO::h5writer(CmdLineOptions& cmd)
{

  hid_t   file_id;       //file      identifier
  hid_t   group_id;      //group     identifier
  hid_t   dset_id;       //Dataset   identifier
  hid_t   filespace;     //Dataspace id in file
  hid_t   memspace;      //Dataspace id in memory.
  hid_t   plist_id;      //Property List id
  hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1], rem;
  hsize_t is, num;
  int     ierr;
  MPI_Comm commF;
  H5FD_mpio_xfer_t  xfer_mode;   // HDF5 transfer mode (indep or collective)
  const char * fn = "UNSTRUCT.h5";

  // compute size info

  rem = cmd.globalSz % P.nProcs;
  if (P.myProc < rem)
    is = P.myProc * cmd.localSz;
  else
    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);

  double lSz     = 1.0;

  m_numvar    = cmd.nvar;
  num         = cmd.localSz;
  lSz         = num;
  count[0]    = 1;
  h5stride[0] = 1;
  starts[0]   = is;
  sz[0]       = num;
  gsz[0]      = cmd.globalSz;
  m_totalSz   = cmd.globalSz*m_numvar*sizeof(double);

  int iTotalSz = m_totalSz/(1024*1024);

  // Initialize data buffer
  double xk = num*P.myProc;

  double *data = new double[num];
  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t0, t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info  = MPI_INFO_NULL;
  MPI_Info infoF = MPI_INFO_NULL;

  MPI_Info_create(&info);
  MPI_Info_create(&infoF);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_STRIPE_COUNT,        cmd.stripes,
                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,
                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,
                                T3PIO_RESULTS,             &results);
      m_nIOUnits = results.numIO;
    }

  xfer_mode = (cmd.collective) ? H5FD_MPIO_COLLECTIVE : H5FD_MPIO_INDEPENDENT;

  t0 = walltime();

  plist_id = H5Pcreate(H5P_FILE_ACCESS);
  H5Pset_fapl_mpio(plist_id, P.comm, info);

  // Create file collectively
  file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);

  MPI_File* pFH = NULL;
  ierr    = H5Fget_vfd_handle(file_id, H5P_DEFAULT, (void **) &pFH);
  ierr    = MPI_File_get_info(*pFH, &infoF);

  t3pio_extract_key_values(infoF, &results);
  m_aggregators = results.numIO;
  m_nStripes    = results.numStripes;
  m_stripeSz    = results.stripeSize;
  H5Pclose(plist_id);

  // Create Group
  group_id = H5Gcreate(file_id, "Solution", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

  std::string timeZ, timeL;
  dateZ(timeZ);
  add_attribute(group_id,"Zulu Time", timeZ.c_str());

  dateL(timeL);
  add_attribute(group_id,"Local Time", timeL.c_str());

  for (int ivar = 0; ivar < m_numvar; ++ivar)
    {

      // Create the dataspace for the dataset
      filespace = H5Screate_simple(1, &gsz[0], NULL);
      memspace  = H5Screate_simple(1, sz,      NULL);

      if (cmd.h5chunk)
        {
          plist_id = H5Pcreate(H5P_DATASET_CREATE);
          H5Pset_chunk(plist_id,1, sz);

          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, plist_id, H5P_DEFAULT);
          H5Pclose(plist_id);
          H5Sclose(filespace);

          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);
        }
      else if (cmd.h5slab)
        {
          // Create the dataset w/ default properties and close filespace
          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
          H5Sclose(filespace);

          // Select hyperslab in the file.
          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);
        }

      plist_id = H5Pcreate(H5P_DATASET_XFER);
      H5Pset_dxpl_mpio(plist_id, xfer_mode);

      add_attribute(dset_id, "Variable Description", varT[ivar].descript);

      t1   = walltime();

      herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,
                               plist_id, data);
      t2   = walltime();
      m_t += (t2 - t1);

      H5Dclose(dset_id);
      H5Sclose(filespace);
      H5Sclose(memspace);
      H5Pclose(plist_id);
    }

  m_totalTime = walltime() - t0;
  m_rate      = m_totalSz /(m_totalTime * 1024.0 * 1024.0);
  free(data);
  H5Gclose(group_id);
  H5Fclose(file_id);
  MPI_Info_free(&info);
  MPI_Info_free(&infoF);
}

void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
  hid_t attr_id, aspace_id, atype_id;
  hsize_t attrlen, num[1];

  attrlen = strlen(value);
  num[0]  = 1;

  atype_id = H5Tcopy(H5T_C_S1);
  H5Tset_size(atype_id, attrlen);

  aspace_id = H5Screate_simple(1,num, NULL);

  attr_id   = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);
  H5Awrite(attr_id, atype_id, value);
  H5Aclose(attr_id);
  H5Sclose(aspace_id);
}
#endif

void ParallelIO::MPIIOwriter(CmdLineOptions& cmd)
{

  MPI_File     fh;
  MPI_Offset   is, rem, offset;
  MPI_Datatype coreData, gblData, my_vector;
  MPI_Status   status;
  int          iTotalSz, ierr, nDim;
  int          sz[2], gsz[2], starts[2];
  const char*  fn = "UNSTRUCT.mpiio";

  rem = cmd.globalSz % P.nProcs;
  if (P.myProc < rem)
    is = P.myProc * cmd.localSz;
  else
    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);

  m_numvar      = 1;
  m_totalSz     = cmd.globalSz*m_numvar*sizeof(double);
  iTotalSz      = m_totalSz/(1024*1024);
  int    num    = cmd.localSz;
  double *data  = new double[num];
  double xk     = is;

  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t0, t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info  = MPI_INFO_NULL;
  MPI_Info infoF = MPI_INFO_NULL;
  MPI_Info_create(&info);
  MPI_Info_create(&infoF);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_STRIPE_COUNT,        cmd.stripes,
                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,
                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,
                                T3PIO_RESULTS,             &results);
      m_nIOUnits = results.numIO;
    }

  //nDim = 1;
  //offset = is*sizeof(double);
  //ierr = MPI_Type_contiguous(num, MPI_DOUBLE, &my_vector);
  //ierr = MPI_Type_commit(&my_vector);
  //ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, my_vector, "native", info);

  offset    = 0;
  nDim      = 2;
  sz[0]     = cmd.localSz/cmd.xwidth;
  sz[1]     = cmd.xwidth;
  gsz[0]    = cmd.globalSz/cmd.xwidth;
  gsz[1]    = cmd.xwidth;
  starts[0] = 0;
  starts[1] = 0;

  ierr = MPI_Type_create_subarray(nDim, sz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
                                  &coreData);
  ierr = MPI_Type_commit(&coreData);
  starts[0] = sz[0]*P.myProc;
  ierr = MPI_Type_create_subarray(nDim, gsz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
                                  &gblData);
  ierr = MPI_Type_commit(&gblData);

  t0 = walltime();

  ierr = MPI_File_open(P.comm, (char *) fn, MPI_MODE_WRONLY | MPI_MODE_CREATE, info, &fh);
  if (ierr)
    MPI_Abort(P.comm, -1);

  ierr = MPI_File_get_info(fh, &infoF);

  t3pio_extract_key_values(infoF, &results);
  m_aggregators = results.numIO;
  m_nStripes    = results.numStripes;
  m_stripeSz    = results.stripeSize;

  ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, gblData, "native", info);

  ierr = MPI_File_write_all(fh, &data[0], 1, coreData, &status);
  ierr = MPI_File_close(&fh);

  m_totalTime = walltime() - t0;
  m_rate      = m_totalSz/(m_totalTime * 1024.0 * 1024.0);
  MPI_Info_free(&info);
  MPI_Info_free(&infoF);
}

<|endoftext|>


<commit_before>#include "mygame.h"

MyGame::MyGame()
	: DemoBase()
	, sfxHelloWorld()
	, sfxPickup()
	, sfxTheme()
	, musTheme()
	, musTheme2()
	, iCount(0)
{
}

MyGame::~MyGame()
{
}

BOOL MyGame::Initialize()
{
	DemoBase::Initialize();

/*
	sfxTheme.Load("theme.adpcm");
	sfxTheme.SetVolume(0.1f);
	sfxTheme.SetLoop(TRUE);
	sfxTheme.Play();
	pSoundSystem->Add(&sfxTheme);
*/

	sfxHelloWorld.Load(SFX_HELLOWORLD);
	pSoundSystem->Add(&sfxHelloWorld);

	sfxPickup.Load(SFX_PICKUP_ITEM);
	pSoundSystem->Add(&sfxPickup);

	pSoundSystem->SetSfxVolume(0.5f);
	pSoundSystem->SetMusicVolume(0.5f);

	sfxHelloWorld.Play();
	sfxPickup.SetVolume(0.1f);

	musTheme.Load(BGM_THEME);
	musTheme.SetVolume(0.5f);
	musTheme.SetAutoUnload(TRUE);
	pSoundSystem->PlayMusic(&musTheme, 500);
	Log("1");

	return TRUE;
}

BOOL MyGame::Update(f32 dt)
{
	iCount++;

	if ((iCount % 10) == 0)
		sfxPickup.Play();

	if (iCount == 300)
	{
#if 0 // cross fade another music (in this case, the same music 0.o)
		musTheme2.Load(BGM_THEME);
		musTheme2.SetVolume(0.5f);
		musTheme2.SetAutoUnload(TRUE);
		pSoundSystem->PlayMusic(&musTheme2, 500);
#else
		pSoundSystem->StopMusic(500);
#endif
		Log("2");
	}
	else if (iCount == 600)
	{
		musTheme.Load(BGM_THEME);
		musTheme.SetVolume(0.5f);
		musTheme.SetAutoUnload(TRUE);
		pSoundSystem->PlayMusic(&musTheme, 500);
		Log("1");
		iCount = 0;
	}

	return TRUE;
}

<commit_msg>cleanup<commit_after>#include "mygame.h"

MyGame::MyGame()
	: DemoBase()
	, sfxHelloWorld()
	, sfxPickup()
	, sfxTheme()
	, musTheme()
	, musTheme2()
	, iCount(0)
{
}

MyGame::~MyGame()
{
}

BOOL MyGame::Initialize()
{
	DemoBase::Initialize();

	sfxHelloWorld.Load(SFX_HELLOWORLD);
	pSoundSystem->Add(&sfxHelloWorld);

	sfxPickup.Load(SFX_PICKUP_ITEM);
	pSoundSystem->Add(&sfxPickup);

	pSoundSystem->SetSfxVolume(0.5f);
	pSoundSystem->SetMusicVolume(0.5f);

	sfxHelloWorld.Play();
	sfxPickup.SetVolume(0.1f);

	musTheme.Load(BGM_THEME);
	musTheme.SetVolume(0.5f);
	musTheme.SetAutoUnload(TRUE);
	pSoundSystem->PlayMusic(&musTheme, 500);

	return TRUE;
}

BOOL MyGame::Update(f32 dt)
{
	iCount++;

	if ((iCount % 10) == 0)
		sfxPickup.Play();

	if (iCount == 300)
	{
#if 0 // cross fade another music (in this case, the same music 0.o)
		musTheme2.Load(BGM_THEME);
		musTheme2.SetVolume(0.5f);
		musTheme2.SetAutoUnload(TRUE);
		pSoundSystem->PlayMusic(&musTheme2, 500);
#else
		pSoundSystem->StopMusic(500);
#endif
		Log("2");
	}
	else if (iCount == 600)
	{
		musTheme.Load(BGM_THEME);
		musTheme.SetVolume(0.5f);
		musTheme.SetAutoUnload(TRUE);
		pSoundSystem->PlayMusic(&musTheme, 500);
		Log("1");
		iCount = 0;
	}

	return TRUE;
}

<|endoftext|>


<commit_before>// $Id: residue.C,v 1.11 2000/05/15 18:32:37 amoll Exp $

#include <BALL/KERNEL/residue.h>

#include <BALL/KERNEL/chain.h>
#include <BALL/KERNEL/protein.h>
#include <BALL/STRUCTURE/geometricProperties.h>

using namespace std;

namespace BALL
{

	Residue::Residue()
		:	Fragment(),
			id_(BALL_RESIDUE_DEFAULT_ID),
			insertion_code_(BALL_RESIDUE_DEFAULT_INSERTION_CODE)
	{
	}

	Residue::Residue(const Residue& residue, bool deep)
		:	Fragment(residue, deep),
			id_(residue.id_),
			insertion_code_(residue.insertion_code_)
	{
	}

	Residue::Residue(const String& name, const String& id, char insertion_code)
		:	Fragment(name),
			id_(id),
			insertion_code_(insertion_code)
	{
	}

	Residue::~Residue()
	{
		destroy();
	}

	void Residue::clear()
	{
		Fragment::clear();

		clear_();
	}

	void Residue::destroy()
	{
		Fragment::destroy();

		clear_();
	}

	void Residue::persistentWrite(PersistenceManager& pm, const char* name) const
	{
		pm.writeObjectHeader(this, name);
			Fragment::persistentWrite(pm);
			pm.writePrimitive(id_, "id_");
			pm.writePrimitive(insertion_code_, "insertion_code_");
		pm.writeObjectTrailer(name);
	}

	void Residue::persistentRead(PersistenceManager& pm)
	{
		pm.checkObjectHeader(RTTI::getStreamName<Fragment>());
			Fragment::persistentRead(pm);
		pm.checkObjectTrailer(0);

		pm.readPrimitive(id_, "id_");
		pm.readPrimitive(insertion_code_, "insertion_code_");
	}

	void Residue::set(const Residue& residue, bool deep)
	{
		Fragment::set(residue, deep);

		id_ = residue.id_;
		insertion_code_ = residue.insertion_code_;
	}

	Residue& Residue::operator =(const Residue& residue)
	{
		set(residue);

		return *this;
	}

	void Residue::get(Residue& residue, bool deep) const
	{
		residue.set(*this, deep);
	}

	void Residue::swap(Residue& residue)
	{
		Fragment::swap(residue);

		id_.swap(residue.id_);

		char temp_insertion_code = insertion_code_;
		insertion_code_ = residue.insertion_code_;
		residue.insertion_code_ = temp_insertion_code;
	}

	bool Residue::hasTorsionPsi() const
	{
		// instance must have a parent chain
		if (getChain() == 0)
		{
			return false;
		}
		// at least 2 residues are needed to create an angle
		if (getChain()->countResidues() < 2)
		{
			return false;
		}
		// the torsion angle psi is not defined for
		// the C-terminus
		return !isCTerminal();
	}

	Angle Residue::getTorsionPsi() const
	{
		Angle result(0.0);
		if (hasTorsionPsi())
		{
			const Residue* next = getNext(RTTI::getDefault<Residue>());
			if (next != 0)
			{
				Atom* C = 0;
				Atom* N = 0;
				Atom* CA = 0;
				AtomIterator it;
				for (it = beginAtom(); +it; ++it)
				{
					if (it->getName() == "C")	C  = &*it;
					if (it->getName() == "CA") CA = &*it;
					if (it->getName() == "N")	N  = &*it;
				}

				Atom* next_N = 0;
				for (it = next->beginAtom(); +it; ++it)
				{
					if (it->getName() == "N")
					{
						next_N  = &*it;
						break;
					}
				}

				if ((N != 0) && (C != 0) && (CA != 0) && (next_N != 0))
				{
					result = calculateTorsionAngle(*N, *CA, *C, *next_N);
				}
				else
				{
					Log.error() << "Atoms not found:" << N << "/" << CA << "/" << C << "/" << next_N << endl;
				}
			}
			else
			{
				Log.error() << "No next residue!" << endl;
			}
		}

		return result;
	}

	bool Residue::hasTorsionPhi() const
	{
		// instance must have a parent chain
		if (getChain() == 0)
		{
			return false;
		}
		// at least 2 residues are needed to create an angle
		if (getChain()->countResidues() < 2)
		{
			return false;
		}
		// the torsion angle phi is not defined for
		// the N-terminus
		return !isNTerminal();
	}

	Angle Residue::getTorsionPhi() const
	{
		Angle result(0.0);
		if (hasTorsionPhi())
		{
			const Residue* previous = getPrevious(RTTI::getDefault<Residue>());
			if (previous != 0)
			{
				Atom* C = 0;
				Atom* N = 0;
				Atom* CA = 0;
				AtomIterator it;
				for (it = beginAtom(); +it; ++it)
				{
					if (it->getName() == "C")	 C  = &*it;
					if (it->getName() == "CA") CA = &*it;
					if (it->getName() == "N")  N  = &*it;
				}

				Atom* last_C = 0;
				for (it = previous->beginAtom(); +it; ++it)
				{
					if (it->getName() == "C")
					{
						last_C  = &*it;
						break;
					}
				}

				if ((N != 0) && (C != 0) && (CA != 0) && (last_C != 0))
				{
					result = calculateTorsionAngle(*last_C, *N, *CA, *C);
				}
				else
				{
					Log.error() << "Atoms not found:" << last_C << "/" << N << "/" << CA << "/" << C << endl;
				}
			}
			else
			{
				Log.error() << "No previous residue!" << endl;
			}
		}

		return result;
	}

	Protein* Residue::getProtein()
	{
		for (Composite::AncestorIterator ancestor_it = beginAncestor(); !ancestor_it.isEnd(); ++ancestor_it)
		{
			if (RTTI::isKindOf<Protein>(*ancestor_it))
			{
				return (Protein *)&*ancestor_it;
			}
		}

		return 0;
	}

	const Protein* Residue::getProtein() const
	{
		return ((Residue *)this)->getProtein();
	}

	Chain* Residue::getChain()
	{
		for (Composite::AncestorIterator ancestor_it = beginAncestor(); !ancestor_it.isEnd(); ++ancestor_it)
		{
			if (RTTI::isKindOf<Chain>(*ancestor_it))
			{
				return (Chain *)&*ancestor_it;
			}
		}

		return 0;
	}

	const Chain *Residue::getChain() const
	{
		return ((Residue *)this)->getChain();
	}

	PDBAtom *Residue::getPDBAtom(Position position)
	{
		for (PDBAtomIterator protein_atom_iterator = beginPDBAtom();
				 !protein_atom_iterator.isEnd(); ++protein_atom_iterator)
		{
			if (position-- == 0)
			{
				return &(*protein_atom_iterator);
			}
		}

		return 0;
	}

	const PDBAtom* Residue::getPDBAtom(Position position) const
	{
		return ((Residue *)this)->getPDBAtom(position);
	}

	void Residue::setID(const String &id)
	{
		id_ = id;
	}

	const String &Residue::getID() const
	{
		return id_;
	}

	void Residue::setInsertionCode(char insertion_code)
	{
		insertion_code_ = insertion_code;
	}

	char Residue::getInsertionCode() const
	{
		return insertion_code_;
	}

	Size Residue::countPDBAtoms() const
	{
		register Size size = 0;

		for (PDBAtomIterator protein_atom_iterator = beginPDBAtom();
				 !protein_atom_iterator.isEnd(); ++protein_atom_iterator)
		{
			++size;
		}

		return size;
	}

	void Residue::prepend(PDBAtom &protein_atom)
	{
		Fragment::prepend(protein_atom);
	}

	void Residue::append(PDBAtom& protein_atom)
	{
		Fragment::append(protein_atom);
	}

	void
	Residue::insert(PDBAtom& protein_atom)
	{
		Fragment::insert(protein_atom);
	}

	void Residue::insertBefore(PDBAtom& protein_atom, Composite& before)
	{
		Fragment::insertBefore(protein_atom, before);
	}

	void Residue::insertAfter(PDBAtom& protein_atom, Composite& after)
	{
		Fragment::insertAfter(protein_atom, after);
	}

	bool Residue::remove(PDBAtom& protein_atom)
	{
		return Fragment::remove(protein_atom);
	}

	void Residue::spliceBefore(Residue& residue)
	{
		Fragment::spliceBefore(residue);
	}

	void Residue::spliceAfter(Residue& residue)
	{
		Fragment::spliceAfter(residue);
	}

	void Residue::splice(Residue& residue)
	{
		Fragment::splice(residue);
	}

	bool Residue::isAminoAcid() const
	{
		return hasProperty(PROPERTY__AMINO_ACID);
	}

	bool Residue::isTerminal() const
	{
		return (isNTerminal() || isCTerminal());
	}

	bool Residue::isNTerminal() const
	{
		if (isAminoAcid() == true)
		{
			const Chain* chain = getChain();

			if (chain != 0)
			{
				ResidueConstIterator res_it = chain->beginResidue();
				for (; +res_it && &(*res_it) != this && !res_it->isAminoAcid(); ++res_it);

				return (&(*res_it) == this);
			}
		}

		return false;
	}

	bool Residue::isCTerminal() const
	{
		if (isAminoAcid() == true)
		{
			const Chain* chain = getChain();

			if (chain != 0)
			{
				ResidueConstIterator res_it = chain->rbeginResidue();
				for (; +res_it && &(*res_it) != this && !res_it->isAminoAcid(); --res_it);

				return (&(*res_it) == this);
			}
		}

		return false;
	}

	bool Residue::isValid() const
	{
		if (Fragment::isValid() == false
				|| id_.isValid() == false)
		{
			return false;
		}

		return true;
	}

	void Residue::dump(ostream& s, Size depth) const
	{
		BALL_DUMP_STREAM_PREFIX(s);

		Fragment::dump(s, depth);

		BALL_DUMP_DEPTH(s, depth);
		s << "  id: " << id_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "  insertion code: " << insertion_code_ << endl;

		BALL_DUMP_STREAM_SUFFIX(s);
	}

	void Residue::read(istream&  /* s */)
	{
		throw Exception::NotImplemented(__FILE__, __LINE__);
	}

	void Residue::write(ostream&  /*s */) const
	{
		throw Exception::NotImplemented(__FILE__, __LINE__);
	}

	void Residue::clear_()
	{
		id_ = BALL_RESIDUE_DEFAULT_ID;
		insertion_code_ = BALL_RESIDUE_DEFAULT_INSERTION_CODE;
	}

	String Residue::getFullName(Residue::FullNameType type) const
	{
		// retrieve the residue name and remove blanks
		String full_name = getName();
		full_name.trim();

		// if the variant extension should be added, do so
		if (type == ADD_VARIANT_EXTENSIONS)
		{
			String suffix = "-";
			if (isNTerminal())
			{
				suffix = "-N";
			}
			if (isCTerminal())
			{
				suffix = "-C";
			}
			if (isCTerminal() && isNTerminal())
			{
				suffix = "-M";
			}
			if (hasProperty(Residue::PROPERTY__HAS_SSBOND))
			{
				suffix += "S";
			}

			if (suffix != "-")
			{
				full_name += suffix;
			}
		}

		return full_name;
	}

} // namespace BALL
<commit_msg>added: rudimentary support for cyclic peptides<commit_after>// $Id: residue.C,v 1.12 2000/05/15 19:25:32 oliver Exp $

#include <BALL/KERNEL/residue.h>

#include <BALL/KERNEL/chain.h>
#include <BALL/KERNEL/protein.h>
#include <BALL/STRUCTURE/geometricProperties.h>

using namespace std;

namespace BALL
{

	Residue::Residue()
		:	Fragment(),
			id_(BALL_RESIDUE_DEFAULT_ID),
			insertion_code_(BALL_RESIDUE_DEFAULT_INSERTION_CODE)
	{
	}

	Residue::Residue(const Residue& residue, bool deep)
		:	Fragment(residue, deep),
			id_(residue.id_),
			insertion_code_(residue.insertion_code_)
	{
	}

	Residue::Residue(const String& name, const String& id, char insertion_code)
		:	Fragment(name),
			id_(id),
			insertion_code_(insertion_code)
	{
	}

	Residue::~Residue()
	{
		destroy();
	}

	void Residue::clear()
	{
		Fragment::clear();

		clear_();
	}

	void Residue::destroy()
	{
		Fragment::destroy();

		clear_();
	}

	void Residue::persistentWrite(PersistenceManager& pm, const char* name) const
	{
		pm.writeObjectHeader(this, name);
			Fragment::persistentWrite(pm);
			pm.writePrimitive(id_, "id_");
			pm.writePrimitive(insertion_code_, "insertion_code_");
		pm.writeObjectTrailer(name);
	}

	void Residue::persistentRead(PersistenceManager& pm)
	{
		pm.checkObjectHeader(RTTI::getStreamName<Fragment>());
			Fragment::persistentRead(pm);
		pm.checkObjectTrailer(0);

		pm.readPrimitive(id_, "id_");
		pm.readPrimitive(insertion_code_, "insertion_code_");
	}

	void Residue::set(const Residue& residue, bool deep)
	{
		Fragment::set(residue, deep);

		id_ = residue.id_;
		insertion_code_ = residue.insertion_code_;
	}

	Residue& Residue::operator =(const Residue& residue)
	{
		set(residue);

		return *this;
	}

	void Residue::get(Residue& residue, bool deep) const
	{
		residue.set(*this, deep);
	}

	void Residue::swap(Residue& residue)
	{
		Fragment::swap(residue);

		id_.swap(residue.id_);

		char temp_insertion_code = insertion_code_;
		insertion_code_ = residue.insertion_code_;
		residue.insertion_code_ = temp_insertion_code;
	}

	bool Residue::hasTorsionPsi() const
	{
		// the torsion angle psi is not defined for
		// the C-terminus
		return !isCTerminal();
	}

	Angle Residue::getTorsionPsi() const
	{
		Angle result(0.0);
		if (hasTorsionPsi())
		{
			const Residue* next = getNext(RTTI::getDefault<Residue>());
			if (next != 0)
			{
				Atom* C = 0;
				Atom* N = 0;
				Atom* CA = 0;
				AtomIterator it;
				for (it = beginAtom(); +it; ++it)
				{
					if (it->getName() == "C")	C  = &*it;
					if (it->getName() == "CA") CA = &*it;
					if (it->getName() == "N")	N  = &*it;
				}

				Atom* next_N = 0;
				for (it = next->beginAtom(); +it; ++it)
				{
					if (it->getName() == "N")
					{
						next_N  = &*it;
						break;
					}
				}

				if ((N != 0) && (C != 0) && (CA != 0) && (next_N != 0))
				{
					result = calculateTorsionAngle(*N, *CA, *C, *next_N);
				}
				else
				{
					Log.error() << "Atoms not found:" << N << "/" << CA << "/" << C << "/" << next_N << endl;
				}
			}
			else
			{
				Log.error() << "No next residue!" << endl;
			}
		}

		return result;
	}

	bool Residue::hasTorsionPhi() const
	{
		// the torsion angle phi is not defined for
		// the C-terminus
		return !isNTerminal();
	}

	Angle Residue::getTorsionPhi() const
	{
		Angle result(0.0);
		if (hasTorsionPhi())
		{
			const Residue* previous = getPrevious(RTTI::getDefault<Residue>());
			if (previous != 0)
			{
				Atom* C = 0;
				Atom* N = 0;
				Atom* CA = 0;
				AtomIterator it;
				for (it = beginAtom(); +it; ++it)
				{
					if (it->getName() == "C")	 C  = &*it;
					if (it->getName() == "CA") CA = &*it;
					if (it->getName() == "N")  N  = &*it;
				}

				Atom* last_C = 0;
				for (it = previous->beginAtom(); +it; ++it)
				{
					if (it->getName() == "C")
					{
						last_C  = &*it;
						break;
					}
				}

				if ((N != 0) && (C != 0) && (CA != 0) && (last_C != 0))
				{
					result = calculateTorsionAngle(*last_C, *N, *CA, *C);
				}
				else
				{
					Log.error() << "Atoms not found:" << last_C << "/" << N << "/" << CA << "/" << C << endl;
				}
			}
			else
			{
				Log.error() << "No previous residue!" << endl;
			}
		}

		return result;
	}

	Protein* Residue::getProtein()
	{
		for (Composite::AncestorIterator ancestor_it = beginAncestor(); !ancestor_it.isEnd(); ++ancestor_it)
		{
			if (RTTI::isKindOf<Protein>(*ancestor_it))
			{
				return (Protein *)&*ancestor_it;
			}
		}

		return 0;
	}

	const Protein* Residue::getProtein() const
	{
		return ((Residue *)this)->getProtein();
	}

	Chain* Residue::getChain()
	{
		for (Composite::AncestorIterator ancestor_it = beginAncestor(); !ancestor_it.isEnd(); ++ancestor_it)
		{
			if (RTTI::isKindOf<Chain>(*ancestor_it))
			{
				return (Chain *)&*ancestor_it;
			}
		}

		return 0;
	}

	const Chain *Residue::getChain() const
	{
		return ((Residue *)this)->getChain();
	}

	PDBAtom *Residue::getPDBAtom(Position position)
	{
		for (PDBAtomIterator protein_atom_iterator = beginPDBAtom();
				 !protein_atom_iterator.isEnd(); ++protein_atom_iterator)
		{
			if (position-- == 0)
			{
				return &(*protein_atom_iterator);
			}
		}

		return 0;
	}

	const PDBAtom* Residue::getPDBAtom(Position position) const
	{
		return ((Residue *)this)->getPDBAtom(position);
	}

	void Residue::setID(const String &id)
	{
		id_ = id;
	}

	const String &Residue::getID() const
	{
		return id_;
	}

	void Residue::setInsertionCode(char insertion_code)
	{
		insertion_code_ = insertion_code;
	}

	char Residue::getInsertionCode() const
	{
		return insertion_code_;
	}

	Size Residue::countPDBAtoms() const
	{
		register Size size = 0;

		for (PDBAtomIterator protein_atom_iterator = beginPDBAtom();
				 !protein_atom_iterator.isEnd(); ++protein_atom_iterator)
		{
			++size;
		}

		return size;
	}

	void Residue::prepend(PDBAtom &protein_atom)
	{
		Fragment::prepend(protein_atom);
	}

	void Residue::append(PDBAtom& protein_atom)
	{
		Fragment::append(protein_atom);
	}

	void
	Residue::insert(PDBAtom& protein_atom)
	{
		Fragment::insert(protein_atom);
	}

	void Residue::insertBefore(PDBAtom& protein_atom, Composite& before)
	{
		Fragment::insertBefore(protein_atom, before);
	}

	void Residue::insertAfter(PDBAtom& protein_atom, Composite& after)
	{
		Fragment::insertAfter(protein_atom, after);
	}

	bool Residue::remove(PDBAtom& protein_atom)
	{
		return Fragment::remove(protein_atom);
	}

	void Residue::spliceBefore(Residue& residue)
	{
		Fragment::spliceBefore(residue);
	}

	void Residue::spliceAfter(Residue& residue)
	{
		Fragment::spliceAfter(residue);
	}

	void Residue::splice(Residue& residue)
	{
		Fragment::splice(residue);
	}

	bool Residue::isAminoAcid() const
	{
		return hasProperty(PROPERTY__AMINO_ACID);
	}

	bool Residue::isTerminal() const
	{
		return (isNTerminal() || isCTerminal());
	}

	bool Residue::isNTerminal() const
	{
		if ((isAminoAcid() == true) && !hasProperty(Residue::PROPERTY__CYCLIC))
		{
			const Chain* chain = getChain();

			if (chain != 0)
			{
				ResidueConstIterator res_it = chain->beginResidue();
				for (; +res_it && &(*res_it) != this && !res_it->isAminoAcid(); ++res_it);

				return (&(*res_it) == this);
			}
		}

		return false;
	}

	bool Residue::isCTerminal() const
	{
		if ((isAminoAcid() == true) && !hasProperty(Residue::PROPERTY__CYCLIC))
		{
			const Chain* chain = getChain();

			if (chain != 0)
			{
				ResidueConstIterator res_it = chain->rbeginResidue();
				for (; +res_it && &(*res_it) != this && !res_it->isAminoAcid(); --res_it);

				return (&(*res_it) == this);
			}
		}

		return false;
	}

	bool Residue::isValid() const
	{
		if (Fragment::isValid() == false
				|| id_.isValid() == false)
		{
			return false;
		}

		return true;
	}

	void Residue::dump(ostream& s, Size depth) const
	{
		BALL_DUMP_STREAM_PREFIX(s);

		Fragment::dump(s, depth);

		BALL_DUMP_DEPTH(s, depth);
		s << "  id: " << id_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "  insertion code: " << insertion_code_ << endl;

		BALL_DUMP_STREAM_SUFFIX(s);
	}

	void Residue::read(istream&  /* s */)
	{
		throw Exception::NotImplemented(__FILE__, __LINE__);
	}

	void Residue::write(ostream&  /*s */) const
	{
		throw Exception::NotImplemented(__FILE__, __LINE__);
	}

	void Residue::clear_()
	{
		id_ = BALL_RESIDUE_DEFAULT_ID;
		insertion_code_ = BALL_RESIDUE_DEFAULT_INSERTION_CODE;
	}

	String Residue::getFullName(Residue::FullNameType type) const
	{
		// retrieve the residue name and remove blanks
		String full_name = getName();
		full_name.trim();

		// if the variant extension should be added, do so
		if (type == ADD_VARIANT_EXTENSIONS)
		{
			String suffix = "-";
			if (isNTerminal())
			{
				suffix = "-N";
			}
			if (isCTerminal())
			{
				suffix = "-C";
			}
			if (isCTerminal() && isNTerminal())
			{
				suffix = "-M";
			}
			if (hasProperty(Residue::PROPERTY__HAS_SSBOND))
			{
				suffix += "S";
			}

			if (suffix != "-")
			{
				full_name += suffix;
			}
		}

		return full_name;
	}

} // namespace BALL
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: sysinfo.C,v 1.7 2005/01/27 15:29:54 oliver Exp $
//

#include <BALL/SYSTEM/sysinfo.h>

#ifndef BALL_PLATFORM_WINDOWS
 #include <sys/sysinfo.h>
 #include <BALL/SYSTEM/file.h>
#else
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
#endif

namespace BALL
{
	namespace SysInfo
	{

		LongIndex getAvailableMemory()
		{
			LongIndex mem = getFreeMemory();
#ifndef BALL_PLATFORM_WINDOWS
			mem += getBufferedMemory();
#endif
			return mem;
		}

		LongIndex getFreeMemory()
		{
#ifdef BALL_PLATFORM_WINDOWS
			MEMORYSTATUSEX statex;
			GlobalMemoryStatusEx (&statex);
			return static_cast<LongIndex>(statex.ullAvailPhys)
#else
			try
			{
				File cpuinfo("/proc/meminfo");
				char buffer[1024];
				String line;
				while (!cpuinfo.eof())
				{
					cpuinfo.getline(buffer, 1024);
					line.assign(buffer);
					if (line.hasPrefix("MemFree:"))
					{
						line = line.after(":");
						line.trimLeft();
						line = line.before(" ");
						return line.toLong() * 1024;
					}
				}
			}
			catch(...)
			{
			}

			// sysinfo seems to return somewhat insane values, but better than nothing...
			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1)
			{
				return result;
			}
			return info.freeram;
#endif
		}

		LongIndex getTotalMemory()
		{
#ifdef BALL_PLATFORM_WINDOWS
 			MEMORYSTATUSEX statex;
			GlobalMemoryStatusEx (&statex);
			return static_cast<LongIndex>(statex.ullFullPhys);
#else
			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1)
			{
				return result;
			}
			return info.totalram;
#endif
		}

		LongIndex getBufferedMemory()
		{
#ifdef BALL_PLATFORM_WINDOWS
#else
			try
			{
				File cpuinfo("/proc/meminfo");
				char buffer[1024];
				String line;
				while (!cpuinfo.eof())
				{
					cpuinfo.getline(buffer, 1024);
					line.assign(buffer);
					if (line.hasPrefix("Cached:"))
					{
						line = line.after(":");
						line.trimLeft();
						line = line.before(" ");
						return line.toLong() * 1024;
					}
				}
			}
			catch(...)
			{
			}

			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1) return result;
			return info.bufferram;
#endif
		}

		Time getUptime()
		{
#ifdef BALL_PLATFORM_WINDOWS
			return -1;
#else
			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1) return result;
			return info.uptime;
#endif
		}

		Index getNumberOfProcessors()
		{
#ifdef BALL_PLATFORM_WINDOWS
			SYSTEM_INFO sysinfo;
			GetSystemInfo(&sysinfo);
			return sysinfo.dwNumberOfProcessors;
#else
			try
			{
				File cpuinfo("/proc/cpuinfo");
				char buffer[1024];
				String line;
				Index nr_processors = 0;
				while (!cpuinfo.eof())
				{
					cpuinfo.getline(buffer, 1024);
					line.assign(buffer);
					if (line.hasPrefix("processor"))
					{
						nr_processors++;
					}
				}

				if (nr_processors == 0) return -1;

				return nr_processors;
			}
			catch(...)
			{
			}

			return -1;
#endif
		}

		LongIndex getFreeSwapSpace()
		{
#ifdef BALL_PLATFORM_WINDOWS
 			MEMORYSTATUSEX statex;
			GlobalMemoryStatusEx (&statex);
			return (LongIndex) statex.ullAvailPageFile;
#else
			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1) return result;
			return info.freeswap;
#endif

		}

	} // namespace SysInfo

} // namespace BALL

<commit_msg>added fix for windows<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: sysinfo.C,v 1.8 2005/01/28 13:29:04 amoll Exp $
//

#include <BALL/SYSTEM/sysinfo.h>

#ifndef BALL_PLATFORM_WINDOWS
 #include <sys/sysinfo.h>
 #include <BALL/SYSTEM/file.h>
#else
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
#endif

namespace BALL
{
	namespace SysInfo
	{

		LongIndex getAvailableMemory()
		{
			LongIndex mem = getFreeMemory();
#ifndef BALL_PLATFORM_WINDOWS
			mem += getBufferedMemory();
#endif
			return mem;
		}

		LongIndex getFreeMemory()
		{
#ifdef BALL_PLATFORM_WINDOWS
			MEMORYSTATUSEX statex;
			GlobalMemoryStatusEx (&statex);
			return static_cast<LongIndex>(statex.ullAvailPhys);
#else
			try
			{
				File cpuinfo("/proc/meminfo");
				char buffer[1024];
				String line;
				while (!cpuinfo.eof())
				{
					cpuinfo.getline(buffer, 1024);
					line.assign(buffer);
					if (line.hasPrefix("MemFree:"))
					{
						line = line.after(":");
						line.trimLeft();
						line = line.before(" ");
						return line.toLong() * 1024;
					}
				}
			}
			catch(...)
			{
			}

			// sysinfo seems to return somewhat insane values, but better than nothing...
			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1)
			{
				return result;
			}
			return info.freeram;
#endif
		}

		LongIndex getTotalMemory()
		{
#ifdef BALL_PLATFORM_WINDOWS
 			MEMORYSTATUSEX statex;
			GlobalMemoryStatusEx (&statex);
			return static_cast<LongIndex>(statex.ullTotalPhys);
#else
			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1)
			{
				return result;
			}
			return info.totalram;
#endif
		}

		LongIndex getBufferedMemory()
		{
#ifdef BALL_PLATFORM_WINDOWS
			return -1;
#else
			try
			{
				File cpuinfo("/proc/meminfo");
				char buffer[1024];
				String line;
				while (!cpuinfo.eof())
				{
					cpuinfo.getline(buffer, 1024);
					line.assign(buffer);
					if (line.hasPrefix("Cached:"))
					{
						line = line.after(":");
						line.trimLeft();
						line = line.before(" ");
						return line.toLong() * 1024;
					}
				}
			}
			catch(...)
			{
			}

			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1) return result;
			return info.bufferram;
#endif
		}

		Time getUptime()
		{
#ifdef BALL_PLATFORM_WINDOWS
			return -1;
#else
			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1) return result;
			return info.uptime;
#endif
		}

		Index getNumberOfProcessors()
		{
#ifdef BALL_PLATFORM_WINDOWS
			SYSTEM_INFO sysinfo;
			GetSystemInfo(&sysinfo);
			return sysinfo.dwNumberOfProcessors;
#else
			try
			{
				File cpuinfo("/proc/cpuinfo");
				char buffer[1024];
				String line;
				Index nr_processors = 0;
				while (!cpuinfo.eof())
				{
					cpuinfo.getline(buffer, 1024);
					line.assign(buffer);
					if (line.hasPrefix("processor"))
					{
						nr_processors++;
					}
				}

				if (nr_processors == 0) return -1;

				return nr_processors;
			}
			catch(...)
			{
			}

			return -1;
#endif
		}

		LongIndex getFreeSwapSpace()
		{
#ifdef BALL_PLATFORM_WINDOWS
 			MEMORYSTATUSEX statex;
			GlobalMemoryStatusEx (&statex);
			return (LongIndex) statex.ullAvailPageFile;
#else
			struct sysinfo info;
			LongIndex result = sysinfo(&info);
			if (result == -1) return result;
			return info.freeswap;
#endif

		}

	} // namespace SysInfo
} // namespace BALL

<|endoftext|>


<commit_before>//===-- UUID.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Utility/UUID.h"

// Other libraries and framework includes
// Project includes
#include "lldb/Utility/Stream.h"
#include "llvm/ADT/StringRef.h"

// C Includes
#include <ctype.h>
#include <stdio.h>
#include <string.h>

namespace lldb_private {

UUID::UUID() : m_num_uuid_bytes(16) { ::memset(m_uuid, 0, sizeof(m_uuid)); }

UUID::UUID(const UUID &rhs) {
  m_num_uuid_bytes = rhs.m_num_uuid_bytes;
  ::memcpy(m_uuid, rhs.m_uuid, sizeof(m_uuid));
}

UUID::UUID(const void *uuid_bytes, uint32_t num_uuid_bytes) {
  SetBytes(uuid_bytes, num_uuid_bytes);
}

const UUID &UUID::operator=(const UUID &rhs) {
  if (this != &rhs) {
    m_num_uuid_bytes = rhs.m_num_uuid_bytes;
    ::memcpy(m_uuid, rhs.m_uuid, sizeof(m_uuid));
  }
  return *this;
}

UUID::~UUID() {}

void UUID::Clear() {
  m_num_uuid_bytes = 16;
  ::memset(m_uuid, 0, sizeof(m_uuid));
}

const void *UUID::GetBytes() const { return m_uuid; }

std::string UUID::GetAsString(const char *separator) const {
  std::string result;
  char buf[256];
  if (!separator)
    separator = "-";
  const uint8_t *u = (const uint8_t *)GetBytes();
  if (sizeof(buf) >
      (size_t)snprintf(buf, sizeof(buf), "%2.2X%2.2X%2.2X%2.2X%s%2.2X%2.2X%s%2."
                                         "2X%2.2X%s%2.2X%2.2X%s%2.2X%2.2X%2.2X%"
                                         "2.2X%2.2X%2.2X",
                       u[0], u[1], u[2], u[3], separator, u[4], u[5], separator,
                       u[6], u[7], separator, u[8], u[9], separator, u[10],
                       u[11], u[12], u[13], u[14], u[15])) {
    result.append(buf);
    if (m_num_uuid_bytes == 20) {
      if (sizeof(buf) > (size_t)snprintf(buf, sizeof(buf),
                                         "%s%2.2X%2.2X%2.2X%2.2X", separator,
                                         u[16], u[17], u[18], u[19]))
        result.append(buf);
    }
  }
  return result;
}

void UUID::Dump(Stream *s) const {
  s->PutCString(GetAsString().c_str());
}

bool UUID::SetBytes(const void *uuid_bytes, uint32_t num_uuid_bytes) {
  if (uuid_bytes) {
    switch (num_uuid_bytes) {
    case 20:
      m_num_uuid_bytes = 20;
      break;
    case 16:
      m_num_uuid_bytes = 16;
      m_uuid[16] = m_uuid[17] = m_uuid[18] = m_uuid[19] = 0;
      break;
    default:
      // Unsupported UUID byte size
      m_num_uuid_bytes = 0;
      break;
    }

    if (m_num_uuid_bytes > 0) {
      ::memcpy(m_uuid, uuid_bytes, m_num_uuid_bytes);
      return true;
    }
  }
  ::memset(m_uuid, 0, sizeof(m_uuid));
  return false;
}

size_t UUID::GetByteSize() const { return m_num_uuid_bytes; }

bool UUID::IsValid() const {
  return m_uuid[0] || m_uuid[1] || m_uuid[2] || m_uuid[3] || m_uuid[4] ||
         m_uuid[5] || m_uuid[6] || m_uuid[7] || m_uuid[8] || m_uuid[9] ||
         m_uuid[10] || m_uuid[11] || m_uuid[12] || m_uuid[13] || m_uuid[14] ||
         m_uuid[15] || m_uuid[16] || m_uuid[17] || m_uuid[18] || m_uuid[19];
}

static inline int xdigit_to_int(char ch) {
  ch = tolower(ch);
  if (ch >= 'a' && ch <= 'f')
    return 10 + ch - 'a';
  return ch - '0';
}

llvm::StringRef UUID::DecodeUUIDBytesFromString(llvm::StringRef p,
                                                ValueType &uuid_bytes,
                                                uint32_t &bytes_decoded,
                                                uint32_t num_uuid_bytes) {
  ::memset(uuid_bytes, 0, sizeof(uuid_bytes));
  size_t uuid_byte_idx = 0;
  while (!p.empty()) {
    if (isxdigit(p[0]) && isxdigit(p[1])) {
      int hi_nibble = xdigit_to_int(p[0]);
      int lo_nibble = xdigit_to_int(p[1]);
      // Translate the two hex nibble characters into a byte
      uuid_bytes[uuid_byte_idx] = (hi_nibble << 4) + lo_nibble;

      // Skip both hex digits
      p = p.drop_front(2);

      // Increment the byte that we are decoding within the UUID value
      // and break out if we are done
      if (++uuid_byte_idx == num_uuid_bytes)
        break;
    } else if (p.front() == '-') {
      // Skip dashes
      p = p.drop_front();
    } else {
      // UUID values can only consist of hex characters and '-' chars
      break;
    }
  }

  // Clear trailing bytes to 0.
  for (uint32_t i = uuid_byte_idx; i < sizeof(ValueType); i++)
    uuid_bytes[i] = 0;
  bytes_decoded = uuid_byte_idx;
  return p;
}

size_t UUID::SetFromStringRef(llvm::StringRef str, uint32_t num_uuid_bytes) {
  llvm::StringRef p = str;

  // Skip leading whitespace characters
  p = p.ltrim();

  uint32_t bytes_decoded = 0;
  llvm::StringRef rest =
      UUID::DecodeUUIDBytesFromString(p, m_uuid, bytes_decoded, num_uuid_bytes);

  // If we successfully decoded a UUID, return the amount of characters that
  // were consumed
  if (bytes_decoded == num_uuid_bytes) {
    m_num_uuid_bytes = num_uuid_bytes;
    return str.size() - rest.size();
  }

  // Else return zero to indicate we were not able to parse a UUID value
  return 0;
}

size_t UUID::SetFromCString(const char *cstr, uint32_t num_uuid_bytes) {
  if (cstr == NULL)
    return 0;

  return SetFromStringRef(cstr, num_uuid_bytes);
}
}

bool lldb_private::operator==(const lldb_private::UUID &lhs,
                              const lldb_private::UUID &rhs) {
  return ::memcmp(lhs.GetBytes(), rhs.GetBytes(),
                  sizeof(lldb_private::UUID::ValueType)) == 0;
}

bool lldb_private::operator!=(const lldb_private::UUID &lhs,
                              const lldb_private::UUID &rhs) {
  return !(lhs == rhs);
}

bool lldb_private::operator<(const lldb_private::UUID &lhs,
                             const lldb_private::UUID &rhs) {
  return ::memcmp(lhs.GetBytes(), rhs.GetBytes(),
                  sizeof(lldb_private::UUID::ValueType)) < 0;
}

bool lldb_private::operator<=(const lldb_private::UUID &lhs,
                              const lldb_private::UUID &rhs) {
  return !(lhs > rhs);
}

bool lldb_private::operator>(const lldb_private::UUID &lhs,
                             const lldb_private::UUID &rhs) {
  return rhs < lhs;
}

bool lldb_private::operator>=(const lldb_private::UUID &lhs,
                              const lldb_private::UUID &rhs) {
  return !(lhs < rhs);
}
<commit_msg>Simplify UUID constructors<commit_after>//===-- UUID.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Utility/UUID.h"

// Other libraries and framework includes
// Project includes
#include "lldb/Utility/Stream.h"
#include "llvm/ADT/StringRef.h"

// C Includes
#include <ctype.h>
#include <stdio.h>
#include <string.h>

namespace lldb_private {

UUID::UUID() { Clear(); }

UUID::UUID(const UUID &rhs) {
  SetBytes(rhs.m_uuid, rhs.m_num_uuid_bytes);
}

UUID::UUID(const void *uuid_bytes, uint32_t num_uuid_bytes) {
  SetBytes(uuid_bytes, num_uuid_bytes);
}

const UUID &UUID::operator=(const UUID &rhs) {
  if (this != &rhs) {
    m_num_uuid_bytes = rhs.m_num_uuid_bytes;
    ::memcpy(m_uuid, rhs.m_uuid, sizeof(m_uuid));
  }
  return *this;
}

UUID::~UUID() {}

void UUID::Clear() {
  m_num_uuid_bytes = 16;
  ::memset(m_uuid, 0, sizeof(m_uuid));
}

const void *UUID::GetBytes() const { return m_uuid; }

std::string UUID::GetAsString(const char *separator) const {
  std::string result;
  char buf[256];
  if (!separator)
    separator = "-";
  const uint8_t *u = (const uint8_t *)GetBytes();
  if (sizeof(buf) >
      (size_t)snprintf(buf, sizeof(buf), "%2.2X%2.2X%2.2X%2.2X%s%2.2X%2.2X%s%2."
                                         "2X%2.2X%s%2.2X%2.2X%s%2.2X%2.2X%2.2X%"
                                         "2.2X%2.2X%2.2X",
                       u[0], u[1], u[2], u[3], separator, u[4], u[5], separator,
                       u[6], u[7], separator, u[8], u[9], separator, u[10],
                       u[11], u[12], u[13], u[14], u[15])) {
    result.append(buf);
    if (m_num_uuid_bytes == 20) {
      if (sizeof(buf) > (size_t)snprintf(buf, sizeof(buf),
                                         "%s%2.2X%2.2X%2.2X%2.2X", separator,
                                         u[16], u[17], u[18], u[19]))
        result.append(buf);
    }
  }
  return result;
}

void UUID::Dump(Stream *s) const {
  s->PutCString(GetAsString().c_str());
}

bool UUID::SetBytes(const void *uuid_bytes, uint32_t num_uuid_bytes) {
  if (uuid_bytes) {
    switch (num_uuid_bytes) {
    case 20:
      m_num_uuid_bytes = 20;
      break;
    case 16:
      m_num_uuid_bytes = 16;
      m_uuid[16] = m_uuid[17] = m_uuid[18] = m_uuid[19] = 0;
      break;
    default:
      // Unsupported UUID byte size
      m_num_uuid_bytes = 0;
      break;
    }

    if (m_num_uuid_bytes > 0) {
      ::memcpy(m_uuid, uuid_bytes, m_num_uuid_bytes);
      return true;
    }
  }
  ::memset(m_uuid, 0, sizeof(m_uuid));
  return false;
}

size_t UUID::GetByteSize() const { return m_num_uuid_bytes; }

bool UUID::IsValid() const {
  return m_uuid[0] || m_uuid[1] || m_uuid[2] || m_uuid[3] || m_uuid[4] ||
         m_uuid[5] || m_uuid[6] || m_uuid[7] || m_uuid[8] || m_uuid[9] ||
         m_uuid[10] || m_uuid[11] || m_uuid[12] || m_uuid[13] || m_uuid[14] ||
         m_uuid[15] || m_uuid[16] || m_uuid[17] || m_uuid[18] || m_uuid[19];
}

static inline int xdigit_to_int(char ch) {
  ch = tolower(ch);
  if (ch >= 'a' && ch <= 'f')
    return 10 + ch - 'a';
  return ch - '0';
}

llvm::StringRef UUID::DecodeUUIDBytesFromString(llvm::StringRef p,
                                                ValueType &uuid_bytes,
                                                uint32_t &bytes_decoded,
                                                uint32_t num_uuid_bytes) {
  ::memset(uuid_bytes, 0, sizeof(uuid_bytes));
  size_t uuid_byte_idx = 0;
  while (!p.empty()) {
    if (isxdigit(p[0]) && isxdigit(p[1])) {
      int hi_nibble = xdigit_to_int(p[0]);
      int lo_nibble = xdigit_to_int(p[1]);
      // Translate the two hex nibble characters into a byte
      uuid_bytes[uuid_byte_idx] = (hi_nibble << 4) + lo_nibble;

      // Skip both hex digits
      p = p.drop_front(2);

      // Increment the byte that we are decoding within the UUID value
      // and break out if we are done
      if (++uuid_byte_idx == num_uuid_bytes)
        break;
    } else if (p.front() == '-') {
      // Skip dashes
      p = p.drop_front();
    } else {
      // UUID values can only consist of hex characters and '-' chars
      break;
    }
  }

  // Clear trailing bytes to 0.
  for (uint32_t i = uuid_byte_idx; i < sizeof(ValueType); i++)
    uuid_bytes[i] = 0;
  bytes_decoded = uuid_byte_idx;
  return p;
}

size_t UUID::SetFromStringRef(llvm::StringRef str, uint32_t num_uuid_bytes) {
  llvm::StringRef p = str;

  // Skip leading whitespace characters
  p = p.ltrim();

  uint32_t bytes_decoded = 0;
  llvm::StringRef rest =
      UUID::DecodeUUIDBytesFromString(p, m_uuid, bytes_decoded, num_uuid_bytes);

  // If we successfully decoded a UUID, return the amount of characters that
  // were consumed
  if (bytes_decoded == num_uuid_bytes) {
    m_num_uuid_bytes = num_uuid_bytes;
    return str.size() - rest.size();
  }

  // Else return zero to indicate we were not able to parse a UUID value
  return 0;
}

size_t UUID::SetFromCString(const char *cstr, uint32_t num_uuid_bytes) {
  if (cstr == NULL)
    return 0;

  return SetFromStringRef(cstr, num_uuid_bytes);
}
}

bool lldb_private::operator==(const lldb_private::UUID &lhs,
                              const lldb_private::UUID &rhs) {
  return ::memcmp(lhs.GetBytes(), rhs.GetBytes(),
                  sizeof(lldb_private::UUID::ValueType)) == 0;
}

bool lldb_private::operator!=(const lldb_private::UUID &lhs,
                              const lldb_private::UUID &rhs) {
  return !(lhs == rhs);
}

bool lldb_private::operator<(const lldb_private::UUID &lhs,
                             const lldb_private::UUID &rhs) {
  return ::memcmp(lhs.GetBytes(), rhs.GetBytes(),
                  sizeof(lldb_private::UUID::ValueType)) < 0;
}

bool lldb_private::operator<=(const lldb_private::UUID &lhs,
                              const lldb_private::UUID &rhs) {
  return !(lhs > rhs);
}

bool lldb_private::operator>(const lldb_private::UUID &lhs,
                             const lldb_private::UUID &rhs) {
  return rhs < lhs;
}

bool lldb_private::operator>=(const lldb_private::UUID &lhs,
                              const lldb_private::UUID &rhs) {
  return !(lhs < rhs);
}
<|endoftext|>


<commit_before>#ifndef __CHUNK_HPP_INCLUDED
#define __CHUNK_HPP_INCLUDED

#include "code/ylikuutio/ontology/model.hpp"

// Each `Chunk` contains `Triangle3D` objects.
// The `Chunk` in which a given `Triangle3D` belongs to is based on either
// on its center or its centroid. Each `Triangle3D` belongs to exactly one
// `Chunk`. Moving the vertices of the `Triangle3D` may move it to some
// other `Chunk` (to an adjacent `Chunk` or to a farther `Chunk`), as
// moving vertices moves the centroid and the center of the `Triangle3D`.
//
// The content of any `Chunk` can be based either on some predefined
// data (eg. height map data, laser scanning data etc.) or procedurally
// (eg. Perlin noise or some other fractal). The parent of `Chunk` objects
// is a `ChunkMaster` object, that has a callback for retrieving or
// producing the content, and also the code for dividing the content into
// appropriate `Chunk` objects.
//
// Centroid:
//
// Center:
//
// From rendering point of view, `Chunk` is like `Species`, with the
// exception that `Chunk` normally contains only 1 `Object`.

namespace space_partition
{
    class Chunk: ontology::Model
    {
        public:
            // constructor.
            Chunk();

            // destructor.
            ~Chunk();

        private:
            void bind_to_parent();

            void render();
    };
}

#endif
<commit_msg>`ontology::Material* parent_pointer`.<commit_after>#ifndef __CHUNK_HPP_INCLUDED
#define __CHUNK_HPP_INCLUDED

#include "code/ylikuutio/ontology/model.hpp"

// Each `Chunk` contains `Triangle3D` objects.
// The `Chunk` in which a given `Triangle3D` belongs to is based on either
// on its center or its centroid. Each `Triangle3D` belongs to exactly one
// `Chunk`. Moving the vertices of the `Triangle3D` may move it to some
// other `Chunk` (to an adjacent `Chunk` or to a farther `Chunk`), as
// moving vertices moves the centroid and the center of the `Triangle3D`.
//
// The content of any `Chunk` can be based either on some predefined
// data (eg. height map data, laser scanning data etc.) or procedurally
// (eg. Perlin noise or some other fractal). The parent of `Chunk` objects
// is a `ChunkMaster` object, that has a callback for retrieving or
// producing the content, and also the code for dividing the content into
// appropriate `Chunk` objects.
//
// Centroid:
//
// Center:
//
// From rendering point of view, `Chunk` is like `Species`, with the
// exception that `Chunk` normally contains only 1 `Object`.

namespace space_partition
{
    class Chunk: ontology::Model
    {
        public:
            // constructor.
            Chunk();

            // destructor.
            ~Chunk();

        private:
            void bind_to_parent();

            void render();

            ontology::Material* parent_pointer;  // pointer to `Material`.
    };
}

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SFX_MACROCONF_HXX
#define _SFX_MACROCONF_HXX

#include "sal/config.h"
#include "sfx2/dllapi.h"
#include "sal/types.h"
#include <tools/errcode.hxx>
#define _SVSTDARR_USHORTS
#include <svl/svstdarr.hxx>     // SvUShorts
#include <sfx2/evntconf.hxx>

class SfxMacroInfo;
class SfxSlot;
class SfxMacroInfoItem;
class SfxObjectShell;
class BasicManager;
struct SfxMacroConfig_Impl;
class SbMethod;
class SbxValue;
class SbxObject;
class SbxArray;
class SvStream;
class SvxMacro;

typedef SfxMacroInfo* SfxMacroInfoPtr;
SV_DECL_PTRARR(SfxMacroInfoArr_Impl, SfxMacroInfoPtr, 5, 5)

class SFX2_DLLPUBLIC SfxMacroInfo
{
friend class SfxMacroConfig;
friend class SfxEventConfiguration;
friend SvStream& operator >> (SvStream& rStream, SfxMacroInfo& rInfo);
friend SvStream& operator << (SvStream& rStream, const SfxMacroInfo& rInfo);

    String*                 pHelpText;
    sal_uInt16                  nRefCnt;
    sal_Bool                    bAppBasic;
    String                  aLibName;
    String                  aModuleName;
    String                  aMethodName;
    sal_uInt16                  nSlotId;
    SfxSlot*                pSlot;

public:
    SfxMacroInfo( const String& rURL );
    SfxMacroInfo( bool _bAppBasic = true );
    SfxMacroInfo( bool _bAppBasic, const String& rQualifiedName );
    SfxMacroInfo(SfxMacroInfo& rOther);
    SfxMacroInfo(bool _bAppBasic, const String& rLibName,
                    const String& rModuleName, const String& rMethodName);
    ~SfxMacroInfo();
    sal_Bool operator==(const SfxMacroInfo& rOther) const;
    int Load (SvStream&);
    int Store (SvStream&);
    String              GetMacroName() const;
    String              GetQualifiedName() const;
    String              GetFullQualifiedName() const;
    BasicManager*       GetBasicManager() const;
    String              GetBasicName() const;
    String              GetHelpText() const;
    sal_Bool                IsAppMacro() const
                        { return bAppBasic; }
    const String&       GetModuleName() const
                        { return aModuleName; }
    const String&       GetLibName() const
                        { return aLibName; }
    const String&       GetMethodName() const
                        { return aMethodName; }
    sal_uInt16              GetSlotId() const
                        { return nSlotId; }
    SfxSlot*            GetSlot() const
                        { return pSlot; }

    sal_Bool                Compare( const SvxMacro& ) const;
    void                SetHelpText( const String& rText );
    String              GetURL() const;
};

//ASDBG obsolete >= 582
//ASDBG class ::com::sun::star::uno::Reference< ::com::sun::star::script::XEngine > ;
//ASDBG class ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > ;

class SFX2_DLLPUBLIC SfxMacroConfig
{
friend class SfxEventConfiguration;

    SAL_DLLPRIVATE static SfxMacroConfig* pMacroConfig;

    SfxMacroConfig_Impl*    pImp;
    SvUShorts               aIdArray;

public:
                            SfxMacroConfig();
                            ~SfxMacroConfig();

    static SfxMacroConfig*  GetOrCreate();

    static String           RequestHelp( sal_uInt16 nId );
    static sal_Bool             IsMacroSlot( sal_uInt16 nId );
    static sal_Bool             IsBasic( SbxObject*, const String&, BasicManager* );
    static ErrCode          Call( SbxObject*, const String&, BasicManager*,
                                SbxArray *pArgs=NULL, SbxValue *pRet=NULL );
//ASDBG obsolete >= 582
//ASDBG     static void CallStarScript( const ::com::sun::star::uno::Reference< ::com::sun::star::script::XEngine > & rxEngine, const String & rCode,
//ASDBG     const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & rSource, void *pArgs, void *pRet );
    static SbMethod*        GetMethod_Impl( const String&, BasicManager* );

    sal_uInt16                  GetSlotId(SfxMacroInfoPtr);
    void                    ReleaseSlotId(sal_uInt16 nId);
    void                    RegisterSlotId(sal_uInt16 nId);
    SfxMacroInfo*           GetMacroInfo(sal_uInt16 nId) const;
    sal_Bool                    ExecuteMacro(sal_uInt16 nId, const String& rArgs ) const;
    sal_Bool                    ExecuteMacro( SfxObjectShell*, const SvxMacro*, const String& ) const;
    sal_Bool                    CheckMacro(sal_uInt16 nId) const;
    sal_Bool                    CheckMacro( SfxObjectShell*, const SvxMacro* ) const;

    SAL_DLLPRIVATE static void Release_Impl();
    SAL_DLLPRIVATE const SfxMacroInfo* GetMacroInfo_Impl( const SvxMacro *pMacro ) const;
    DECL_DLLPRIVATE_LINK( CallbackHdl_Impl, SfxMacroConfig*);
    DECL_DLLPRIVATE_LINK( EventHdl_Impl, SfxMacroInfo*);
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>~SfxMacroInfo::Store declared, but never defined<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SFX_MACROCONF_HXX
#define _SFX_MACROCONF_HXX

#include "sal/config.h"
#include "sfx2/dllapi.h"
#include "sal/types.h"
#include <tools/errcode.hxx>
#define _SVSTDARR_USHORTS
#include <svl/svstdarr.hxx>     // SvUShorts
#include <sfx2/evntconf.hxx>

class SfxMacroInfo;
class SfxSlot;
class SfxMacroInfoItem;
class SfxObjectShell;
class BasicManager;
struct SfxMacroConfig_Impl;
class SbMethod;
class SbxValue;
class SbxObject;
class SbxArray;
class SvStream;
class SvxMacro;

typedef SfxMacroInfo* SfxMacroInfoPtr;
SV_DECL_PTRARR(SfxMacroInfoArr_Impl, SfxMacroInfoPtr, 5, 5)

class SFX2_DLLPUBLIC SfxMacroInfo
{
friend class SfxMacroConfig;
friend class SfxEventConfiguration;
friend SvStream& operator >> (SvStream& rStream, SfxMacroInfo& rInfo);
friend SvStream& operator << (SvStream& rStream, const SfxMacroInfo& rInfo);

    String*                 pHelpText;
    sal_uInt16                  nRefCnt;
    sal_Bool                    bAppBasic;
    String                  aLibName;
    String                  aModuleName;
    String                  aMethodName;
    sal_uInt16                  nSlotId;
    SfxSlot*                pSlot;

public:
    SfxMacroInfo( const String& rURL );
    SfxMacroInfo( bool _bAppBasic = true );
    SfxMacroInfo( bool _bAppBasic, const String& rQualifiedName );
    SfxMacroInfo(SfxMacroInfo& rOther);
    SfxMacroInfo(bool _bAppBasic, const String& rLibName,
                    const String& rModuleName, const String& rMethodName);
    ~SfxMacroInfo();
    sal_Bool operator==(const SfxMacroInfo& rOther) const;
    int Load (SvStream&);
    String              GetMacroName() const;
    String              GetQualifiedName() const;
    String              GetFullQualifiedName() const;
    BasicManager*       GetBasicManager() const;
    String              GetBasicName() const;
    String              GetHelpText() const;
    sal_Bool                IsAppMacro() const
                        { return bAppBasic; }
    const String&       GetModuleName() const
                        { return aModuleName; }
    const String&       GetLibName() const
                        { return aLibName; }
    const String&       GetMethodName() const
                        { return aMethodName; }
    sal_uInt16              GetSlotId() const
                        { return nSlotId; }
    SfxSlot*            GetSlot() const
                        { return pSlot; }

    sal_Bool                Compare( const SvxMacro& ) const;
    void                SetHelpText( const String& rText );
    String              GetURL() const;
};

//ASDBG obsolete >= 582
//ASDBG class ::com::sun::star::uno::Reference< ::com::sun::star::script::XEngine > ;
//ASDBG class ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > ;

class SFX2_DLLPUBLIC SfxMacroConfig
{
friend class SfxEventConfiguration;

    SAL_DLLPRIVATE static SfxMacroConfig* pMacroConfig;

    SfxMacroConfig_Impl*    pImp;
    SvUShorts               aIdArray;

public:
                            SfxMacroConfig();
                            ~SfxMacroConfig();

    static SfxMacroConfig*  GetOrCreate();

    static String           RequestHelp( sal_uInt16 nId );
    static sal_Bool             IsMacroSlot( sal_uInt16 nId );
    static sal_Bool             IsBasic( SbxObject*, const String&, BasicManager* );
    static ErrCode          Call( SbxObject*, const String&, BasicManager*,
                                SbxArray *pArgs=NULL, SbxValue *pRet=NULL );
//ASDBG obsolete >= 582
//ASDBG     static void CallStarScript( const ::com::sun::star::uno::Reference< ::com::sun::star::script::XEngine > & rxEngine, const String & rCode,
//ASDBG     const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & rSource, void *pArgs, void *pRet );
    static SbMethod*        GetMethod_Impl( const String&, BasicManager* );

    sal_uInt16                  GetSlotId(SfxMacroInfoPtr);
    void                    ReleaseSlotId(sal_uInt16 nId);
    void                    RegisterSlotId(sal_uInt16 nId);
    SfxMacroInfo*           GetMacroInfo(sal_uInt16 nId) const;
    sal_Bool                    ExecuteMacro(sal_uInt16 nId, const String& rArgs ) const;
    sal_Bool                    ExecuteMacro( SfxObjectShell*, const SvxMacro*, const String& ) const;
    sal_Bool                    CheckMacro(sal_uInt16 nId) const;
    sal_Bool                    CheckMacro( SfxObjectShell*, const SvxMacro* ) const;

    SAL_DLLPRIVATE static void Release_Impl();
    SAL_DLLPRIVATE const SfxMacroInfo* GetMacroInfo_Impl( const SvxMacro *pMacro ) const;
    DECL_DLLPRIVATE_LINK( CallbackHdl_Impl, SfxMacroConfig*);
    DECL_DLLPRIVATE_LINK( EventHdl_Impl, SfxMacroInfo*);
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/ivf_video_source.h"
#include "test/util.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vpx_mem/vpx_mem.h"

namespace {

struct DecodeParam {
  int threads;
  const char *filename;
};

std::ostream &operator<<(std::ostream &os, const DecodeParam &dp) {
  return os << "threads: " << dp.threads << " file: " << dp.filename;
}

class InvalidFileTest : public ::libvpx_test::DecoderTest,
                        public ::libvpx_test::CodecTestWithParam<DecodeParam> {
 protected:
  InvalidFileTest() : DecoderTest(GET_PARAM(0)), res_file_(NULL) {}

  virtual ~InvalidFileTest() {
    if (res_file_ != NULL) fclose(res_file_);
  }

  void OpenResFile(const std::string &res_file_name_) {
    res_file_ = libvpx_test::OpenTestDataFile(res_file_name_);
    ASSERT_TRUE(res_file_ != NULL) << "Result file open failed. Filename: "
                                   << res_file_name_;
  }

  virtual bool HandleDecodeResult(
      const vpx_codec_err_t res_dec,
      const libvpx_test::CompressedVideoSource &video,
      libvpx_test::Decoder *decoder) {
    EXPECT_TRUE(res_file_ != NULL);
    int expected_res_dec;

    // Read integer result.
    const int res = fscanf(res_file_, "%d", &expected_res_dec);
    EXPECT_NE(res, EOF) << "Read result data failed";

    // Check results match.
    const DecodeParam input = GET_PARAM(1);
    if (input.threads > 1) {
      // The serial decode check is too strict for tile-threaded decoding as
      // there is no guarantee on the decode order nor which specific error
      // will take precedence. Currently a tile-level error is not forwarded so
      // the frame will simply be marked corrupt.
      EXPECT_TRUE(res_dec == expected_res_dec ||
                  res_dec == VPX_CODEC_CORRUPT_FRAME)
          << "Results don't match: frame number = " << video.frame_number()
          << ". (" << decoder->DecodeError()
          << "). Expected: " << expected_res_dec << " or "
          << VPX_CODEC_CORRUPT_FRAME;
    } else {
      EXPECT_EQ(expected_res_dec, res_dec)
          << "Results don't match: frame number = " << video.frame_number()
          << ". (" << decoder->DecodeError() << ")";
    }

    return !HasFailure();
  }

  void RunTest() {
    const DecodeParam input = GET_PARAM(1);
    vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();
    cfg.threads = input.threads;
    const std::string filename = input.filename;

    // Open compressed video file.
    testing::internal::scoped_ptr<libvpx_test::CompressedVideoSource> video;
    if (filename.substr(filename.length() - 3, 3) == "ivf") {
      video.reset(new libvpx_test::IVFVideoSource(filename));
    } else if (filename.substr(filename.length() - 4, 4) == "webm") {
#if CONFIG_WEBM_IO
      video.reset(new libvpx_test::WebMVideoSource(filename));
#else
      fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n",
              filename.c_str());
      return;
#endif
    }
    ASSERT_TRUE(video.get() != NULL);
    video->Init();

    // Construct result file name. The file holds a list of expected integer
    // results, one for each decoded frame.  Any result that doesn't match
    // the files list will cause a test failure.
    const std::string res_filename = filename + ".res";
    OpenResFile(res_filename);

    // Decode frame, and check the md5 matching.
    ASSERT_NO_FATAL_FAILURE(RunLoop(video.get(), cfg));
  }

 private:
  FILE *res_file_;
};

TEST_P(InvalidFileTest, ReturnCode) { RunTest(); }

const DecodeParam kVP9InvalidFileTests[] = {
  { 1, "invalid-vp90-02-v2.webm" },
#if CONFIG_VP9_HIGHBITDEPTH
  { 1, "invalid-vp90-2-00-quantizer-00.webm.ivf.s5861_r01-05_b6-.v2.ivf" },
#endif
  { 1, "invalid-vp90-03-v3.webm" },
  { 1, "invalid-vp90-2-00-quantizer-11.webm.ivf.s52984_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-00-quantizer-11.webm.ivf.s52984_r01-05_b6-z.ivf" },
// This file will cause a large allocation which is expected to fail in 32-bit
// environments. Test x86 for coverage purposes as the allocation failure will
// be in platform agnostic code.
#if ARCH_X86
  { 1, "invalid-vp90-2-00-quantizer-63.ivf.kf_65527x61446.ivf" },
#endif
  { 1, "invalid-vp90-2-12-droppable_1.ivf.s3676_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-05-resize.ivf.s59293_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-09-subpixel-00.ivf.s20492_r01-05_b6-.v2.ivf" },
  { 1, "invalid-vp91-2-mixedrefcsp-444to420.ivf" },
  { 1, "invalid-vp90-2-12-droppable_1.ivf.s73804_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-03-size-224x196.webm.ivf.s44156_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-03-size-202x210.webm.ivf.s113306_r01-05_b6-.ivf" },
};

VP9_INSTANTIATE_TEST_CASE(InvalidFileTest,
                          ::testing::ValuesIn(kVP9InvalidFileTests));

// This class will include test vectors that are expected to fail
// peek. However they are still expected to have no fatal failures.
class InvalidFileInvalidPeekTest : public InvalidFileTest {
 protected:
  InvalidFileInvalidPeekTest() : InvalidFileTest() {}
  virtual void HandlePeekResult(libvpx_test::Decoder *const /*decoder*/,
                                libvpx_test::CompressedVideoSource * /*video*/,
                                const vpx_codec_err_t /*res_peek*/) {}
};

TEST_P(InvalidFileInvalidPeekTest, ReturnCode) { RunTest(); }

const DecodeParam kVP8InvalidFileTests[] = {
  { 1, "invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf" },
};

VP8_INSTANTIATE_TEST_CASE(InvalidFileInvalidPeekTest,
                          ::testing::ValuesIn(kVP8InvalidFileTests));

const DecodeParam kVP9InvalidFileInvalidPeekTests[] = {
  { 1, "invalid-vp90-01-v3.webm" },
};

VP9_INSTANTIATE_TEST_CASE(InvalidFileInvalidPeekTest,
                          ::testing::ValuesIn(kVP9InvalidFileInvalidPeekTests));

#if CONFIG_VP9_DECODER
const DecodeParam kMultiThreadedVP9InvalidFileTests[] = {
  { 4, "invalid-vp90-2-08-tile_1x4_frame_parallel_all_key.webm" },
  { 4,
    "invalid-"
    "vp90-2-08-tile_1x2_frame_parallel.webm.ivf.s47039_r01-05_b6-.ivf" },
  { 4,
    "invalid-vp90-2-08-tile_1x8_frame_parallel.webm.ivf.s288_r01-05_b6-.ivf" },
  { 2, "invalid-vp90-2-09-aq2.webm.ivf.s3984_r01-05_b6-.v2.ivf" },
  { 4, "invalid-vp90-2-09-subpixel-00.ivf.s19552_r01-05_b6-.v2.ivf" },
};

INSTANTIATE_TEST_CASE_P(
    VP9MultiThreaded, InvalidFileTest,
    ::testing::Combine(
        ::testing::Values(
            static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP9)),
        ::testing::ValuesIn(kMultiThreadedVP9InvalidFileTests)));
#endif  // CONFIG_VP9_DECODER
}  // namespace
<commit_msg>invalid_file_test: quiet -Wunused-const-variable warnings<commit_after>/*
 *  Copyright (c) 2014 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/ivf_video_source.h"
#include "test/util.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vpx_mem/vpx_mem.h"

namespace {

struct DecodeParam {
  int threads;
  const char *filename;
};

std::ostream &operator<<(std::ostream &os, const DecodeParam &dp) {
  return os << "threads: " << dp.threads << " file: " << dp.filename;
}

class InvalidFileTest : public ::libvpx_test::DecoderTest,
                        public ::libvpx_test::CodecTestWithParam<DecodeParam> {
 protected:
  InvalidFileTest() : DecoderTest(GET_PARAM(0)), res_file_(NULL) {}

  virtual ~InvalidFileTest() {
    if (res_file_ != NULL) fclose(res_file_);
  }

  void OpenResFile(const std::string &res_file_name_) {
    res_file_ = libvpx_test::OpenTestDataFile(res_file_name_);
    ASSERT_TRUE(res_file_ != NULL) << "Result file open failed. Filename: "
                                   << res_file_name_;
  }

  virtual bool HandleDecodeResult(
      const vpx_codec_err_t res_dec,
      const libvpx_test::CompressedVideoSource &video,
      libvpx_test::Decoder *decoder) {
    EXPECT_TRUE(res_file_ != NULL);
    int expected_res_dec;

    // Read integer result.
    const int res = fscanf(res_file_, "%d", &expected_res_dec);
    EXPECT_NE(res, EOF) << "Read result data failed";

    // Check results match.
    const DecodeParam input = GET_PARAM(1);
    if (input.threads > 1) {
      // The serial decode check is too strict for tile-threaded decoding as
      // there is no guarantee on the decode order nor which specific error
      // will take precedence. Currently a tile-level error is not forwarded so
      // the frame will simply be marked corrupt.
      EXPECT_TRUE(res_dec == expected_res_dec ||
                  res_dec == VPX_CODEC_CORRUPT_FRAME)
          << "Results don't match: frame number = " << video.frame_number()
          << ". (" << decoder->DecodeError()
          << "). Expected: " << expected_res_dec << " or "
          << VPX_CODEC_CORRUPT_FRAME;
    } else {
      EXPECT_EQ(expected_res_dec, res_dec)
          << "Results don't match: frame number = " << video.frame_number()
          << ". (" << decoder->DecodeError() << ")";
    }

    return !HasFailure();
  }

  void RunTest() {
    const DecodeParam input = GET_PARAM(1);
    vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();
    cfg.threads = input.threads;
    const std::string filename = input.filename;

    // Open compressed video file.
    testing::internal::scoped_ptr<libvpx_test::CompressedVideoSource> video;
    if (filename.substr(filename.length() - 3, 3) == "ivf") {
      video.reset(new libvpx_test::IVFVideoSource(filename));
    } else if (filename.substr(filename.length() - 4, 4) == "webm") {
#if CONFIG_WEBM_IO
      video.reset(new libvpx_test::WebMVideoSource(filename));
#else
      fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n",
              filename.c_str());
      return;
#endif
    }
    ASSERT_TRUE(video.get() != NULL);
    video->Init();

    // Construct result file name. The file holds a list of expected integer
    // results, one for each decoded frame.  Any result that doesn't match
    // the files list will cause a test failure.
    const std::string res_filename = filename + ".res";
    OpenResFile(res_filename);

    // Decode frame, and check the md5 matching.
    ASSERT_NO_FATAL_FAILURE(RunLoop(video.get(), cfg));
  }

 private:
  FILE *res_file_;
};

TEST_P(InvalidFileTest, ReturnCode) { RunTest(); }

const DecodeParam kVP9InvalidFileTests[] = {
  { 1, "invalid-vp90-02-v2.webm" },
#if CONFIG_VP9_HIGHBITDEPTH
  { 1, "invalid-vp90-2-00-quantizer-00.webm.ivf.s5861_r01-05_b6-.v2.ivf" },
#endif
  { 1, "invalid-vp90-03-v3.webm" },
  { 1, "invalid-vp90-2-00-quantizer-11.webm.ivf.s52984_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-00-quantizer-11.webm.ivf.s52984_r01-05_b6-z.ivf" },
// This file will cause a large allocation which is expected to fail in 32-bit
// environments. Test x86 for coverage purposes as the allocation failure will
// be in platform agnostic code.
#if ARCH_X86
  { 1, "invalid-vp90-2-00-quantizer-63.ivf.kf_65527x61446.ivf" },
#endif
  { 1, "invalid-vp90-2-12-droppable_1.ivf.s3676_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-05-resize.ivf.s59293_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-09-subpixel-00.ivf.s20492_r01-05_b6-.v2.ivf" },
  { 1, "invalid-vp91-2-mixedrefcsp-444to420.ivf" },
  { 1, "invalid-vp90-2-12-droppable_1.ivf.s73804_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-03-size-224x196.webm.ivf.s44156_r01-05_b6-.ivf" },
  { 1, "invalid-vp90-2-03-size-202x210.webm.ivf.s113306_r01-05_b6-.ivf" },
};

VP9_INSTANTIATE_TEST_CASE(InvalidFileTest,
                          ::testing::ValuesIn(kVP9InvalidFileTests));

// This class will include test vectors that are expected to fail
// peek. However they are still expected to have no fatal failures.
class InvalidFileInvalidPeekTest : public InvalidFileTest {
 protected:
  InvalidFileInvalidPeekTest() : InvalidFileTest() {}
  virtual void HandlePeekResult(libvpx_test::Decoder *const /*decoder*/,
                                libvpx_test::CompressedVideoSource * /*video*/,
                                const vpx_codec_err_t /*res_peek*/) {}
};

TEST_P(InvalidFileInvalidPeekTest, ReturnCode) { RunTest(); }

#if CONFIG_VP8_DECODER
const DecodeParam kVP8InvalidFileTests[] = {
  { 1, "invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf" },
};

VP8_INSTANTIATE_TEST_CASE(InvalidFileInvalidPeekTest,
                          ::testing::ValuesIn(kVP8InvalidFileTests));
#endif  // CONFIG_VP8_DECODER

#if CONFIG_VP9_DECODER
const DecodeParam kVP9InvalidFileInvalidPeekTests[] = {
  { 1, "invalid-vp90-01-v3.webm" },
};

VP9_INSTANTIATE_TEST_CASE(InvalidFileInvalidPeekTest,
                          ::testing::ValuesIn(kVP9InvalidFileInvalidPeekTests));

const DecodeParam kMultiThreadedVP9InvalidFileTests[] = {
  { 4, "invalid-vp90-2-08-tile_1x4_frame_parallel_all_key.webm" },
  { 4,
    "invalid-"
    "vp90-2-08-tile_1x2_frame_parallel.webm.ivf.s47039_r01-05_b6-.ivf" },
  { 4,
    "invalid-vp90-2-08-tile_1x8_frame_parallel.webm.ivf.s288_r01-05_b6-.ivf" },
  { 2, "invalid-vp90-2-09-aq2.webm.ivf.s3984_r01-05_b6-.v2.ivf" },
  { 4, "invalid-vp90-2-09-subpixel-00.ivf.s19552_r01-05_b6-.v2.ivf" },
};

INSTANTIATE_TEST_CASE_P(
    VP9MultiThreaded, InvalidFileTest,
    ::testing::Combine(
        ::testing::Values(
            static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP9)),
        ::testing::ValuesIn(kMultiThreadedVP9InvalidFileTests)));
#endif  // CONFIG_VP9_DECODER
}  // namespace
<|endoftext|>