<commit_before>/*
 * File:   test.cpp
 *
 * Created on November 5, 2010, 2:30 PM
 */

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include "EDFFile.h"
#include "EDFUtil.h"
#include "EDFHeader.h"
#include "EDFAnnotation.h"
#include "EDFSignalData.h"

using namespace std;

void printHeaderInfo(string filename, EDFHeader* head) {
    cout << "File \"" << filename << "\"" << endl << endl << endl;
    cout << "Header Info" << endl << endl;
    cout << "File Type            | ";
    if (head->getFiletype() == EDFHeader::EDF)
        cout << "EDF" << endl;
    else
        cout << "EDF+" << (head->getContinuity() == 0 ? "C" : "D") << endl;
    cout << "Signal Count         | " << head->getSignalCount() << endl;
    cout << "Recording Length     | " << head->getDataRecordCount() * head->getDataRecordDuration() << " seconds" << endl;
    cout << "Start Date           | " << head->getDate() << endl;
    cout << "Start Time           | " << head->getStartTime() << endl;
    cout << "Recording            | " << head->getRecording() << endl;
    cout << "Patient Info ---------" << endl << head->getPatient() << endl;
    cout << "Admin Code           | " << head->getAdminCode() << endl;
    cout << "Technician           | " << head->getTechnician() << endl;
    cout << "Equipment            | " << head->getEquipment() << endl;
    cout << "Recording Additional | " << head->getRecordingAdditional() << endl;
    cout << "Record Duration      | " << head->getDataRecordDuration() << " seconds" << endl;
    cout << "Data Record Count    | " << head->getDataRecordCount() << endl;
    cout << "Data Record Size     | " << head->getDataRecordSize() << endl;
    cout << "Annotation Signal    | " << head->getAnnotationIndex() + 1 << endl;
    cout << endl << endl;
}

void printAnnotationInfo(vector<EDFAnnotation>* annot) {
    cout << fixed << setprecision(1);
    cout << "Annotation Info" << endl << endl;
    cout << "Annotation Count     | " << annot->size() << endl;
    for (size_t i = 0; i < annot->size(); i++) {
        cout << " Onset " << annot->at(i).getOnset() << "s";
        cout << " Duration " << annot->at(i).getDuration() << "s";
        for (size_t j = 0; j < annot->at(i).getStrings().size(); j++)
            cout << " \"" << (annot->at(i).getStrings())[j] << "\" ";
        cout << endl;
    }
}

void printSignalInfo(int sig, EDFHeader* head) {
    cout << fixed << setprecision(4);
    cout << "Signal (" << sig + 1 << ") Info" << endl << endl;
    cout << "Label                | " << head->getLabel(sig) << endl;
    cout << "Record Samples       | " << head->getDataRecordCount() * head->getSignalSampleCount(sig) << endl;
    cout << "Sample Count         | " << head->getSignalSampleCount(sig) << endl;
    cout << "Physical Max         | " << head->getPhysicalMax(sig) << endl;
    cout << "Physical Min         | " << head->getPhysicalMin(sig) << endl;
    cout << "Physical Dimension   | " << head->getPhysicalDimension(sig) << endl;
    cout << "Digital Max          | " << head->getDigitalMax(sig) << endl;
    cout << "Digital Min          | " << head->getDigitalMin(sig) << endl;
    cout << "Prefilter            | " << head->getPrefilter(sig) << endl;
    cout << "Transducer           | " << head->getTransducer(sig) << endl;
    cout << endl << endl;
}

void printAllSignalInfo(EDFHeader* head) {
    cout << fixed << setprecision(4);
    for (int sig = 0; sig < head->getSignalCount() && sig != head->getAnnotationIndex(); sig++) {
        cout << "Signal (" << sig + 1 << ") Info" << endl << endl;
        cout << "Label                | " << head->getLabel(sig) << endl;
        cout << "Record Samples       | " << head->getDataRecordCount() * head->getSignalSampleCount(sig) << endl;
        cout << "Sample Count         | " << head->getSignalSampleCount(sig) << endl;
        cout << "Physical Max         | " << head->getPhysicalMax(sig) << endl;
        cout << "Physical Min         | " << head->getPhysicalMin(sig) << endl;
        cout << "Physical Dimension   | " << head->getPhysicalDimension(sig) << endl;
        cout << "Digital Max          | " << head->getDigitalMax(sig) << endl;
        cout << "Digital Min          | " << head->getDigitalMin(sig) << endl;
        cout << "Prefilter            | " << head->getPrefilter(sig) << endl;
        cout << "Transducer           | " << head->getTransducer(sig) << endl;
        cout << endl << endl;
    }
}

void printSignalData(EDFFile& file, int signal, float start, float length) {
    EDFSignalData* sigData = file.getSignalData(signal, start, length);
    if (sigData) {
        vector<int16_t> data = sigData->getData();
        cout << endl << sigData->getLength() / sigData->getFrequency() << " seconds  " << sigData->getLength() << " samples" << endl;

        int i = 0;
        for (vector<int16_t>::iterator it = data.begin(); it != data.end(); it++, i++) {
            if (i % 20 == 0)
                cout << endl << i << ":  ";
            cout << *it << " ";
        }
        cout << endl << endl;
    }
}

int main(int argc, char** argv) {
    EDFFile newFile(argv[1]);
    int signal = atoi(argv[2]) - 1;

    EDFHeader* header = newFile.getHeader();
    vector<EDFAnnotation>* annotations = newFile.getAnnotations();

    //printHeaderInfo(argv[1], header);
    printSignalInfo(signal, header);
    //printAnnotationInfo(annotations);
    double startTime = 0.0; // seconds
    double length = 2.0; // seconds
    cout << startTime << "s -> " << startTime + length << "s" << endl;
    printSignalData(newFile, signal, startTime, length);

    startTime = 1.0; // seconds
    length = 1.0; // seconds
    cout << startTime << "s -> " << startTime + length << "s" << endl;
    printSignalData(newFile, signal, startTime, length);

    return EXIT_SUCCESS;
}

<commit_msg>minor changes<commit_after>/*
 * File:   test.cpp
 *
 * Created on November 5, 2010, 2:30 PM
 */

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include "EDFLib.h"

using namespace std;

void printHeaderInfo(string filename, EDFHeader* head) {
    cout << "File \"" << filename << "\"" << endl << endl << endl;
    cout << "Header Info" << endl << endl;
    cout << "File Type            | ";
    if (head->getFiletype() == FileType::EDF)
        cout << "EDF" << endl;
    else
        cout << "EDF+" << (head->getContinuity() == Continuity::CONTINUOUS ? "C" : "D") << endl;
    cout << "Signal Count         | " << head->getSignalCount() << endl;
    cout << "Recording Length     | " << head->getDataRecordCount() * head->getDataRecordDuration() << " seconds" << endl;
    cout << "Start Date           | " << head->getDate() << endl;
    cout << "Start Time           | " << head->getStartTime() << endl;
    cout << "Recording            | " << head->getRecording() << endl;
    cout << "Patient Info ---------" << endl << head->getPatient() << endl;
    cout << "Admin Code           | " << head->getAdminCode() << endl;
    cout << "Technician           | " << head->getTechnician() << endl;
    cout << "Equipment            | " << head->getEquipment() << endl;
    cout << "Recording Additional | " << head->getRecordingAdditional() << endl;
    cout << "Record Duration      | " << head->getDataRecordDuration() << " seconds" << endl;
    cout << "Data Record Count    | " << head->getDataRecordCount() << endl;
    cout << "Data Record Size     | " << head->getDataRecordSize() << endl;
    cout << "Annotation Signal    | " << head->getAnnotationIndex() + 1 << endl;
    cout << endl << endl;
}

void printAnnotationInfo(vector<EDFAnnotation>* annot) {
    cout << fixed << setprecision(1);
    cout << "Annotation Info" << endl << endl;
    cout << "Annotations" << endl;

    int onsetWidth = 2;
    EDFAnnotation last = *(--annot->end());
    int l = last.getOnset();
    while (l > 0) {
        l /= 10;
        onsetWidth++;
    }

    int idxWidth = 0;
    l = annot->size();
    while (l > 0) {
        l /= 10;
        idxWidth++;
    }

    for (size_t i = 0; i < annot->size(); i++) {
        cout << " " << std::setw(idxWidth) << i+1;
        cout << " Onset " << std::setw(onsetWidth) << annot->at(i).getOnset() << "s";
        cout << " Duration " << std::setw(8) << annot->at(i).getDuration() << "s";
        for (size_t j = 0; j < annot->at(i).getStrings().size(); j++)
            cout << " \"" << (annot->at(i).getStrings())[j] << "\" ";
        cout << endl;
    }
    cout << endl;
}

void printSignalInfo(int sig, EDFHeader* head) {
    cout << fixed << setprecision(4);
    cout << "Signal (" << sig + 1 << ") Info" << endl << endl;
    cout << "Label                | " << head->getLabel(sig) << endl;
    cout << "Record Samples       | " << head->getDataRecordCount() * head->getSignalSampleCount(sig) << endl;
    cout << "Sample Count         | " << head->getSignalSampleCount(sig) << endl;
    cout << "Physical Max         | " << head->getPhysicalMax(sig) << endl;
    cout << "Physical Min         | " << head->getPhysicalMin(sig) << endl;
    cout << "Physical Dimension   | " << head->getPhysicalDimension(sig) << endl;
    cout << "Digital Max          | " << head->getDigitalMax(sig) << endl;
    cout << "Digital Min          | " << head->getDigitalMin(sig) << endl;
    cout << "Prefilter            | " << head->getPrefilter(sig) << endl;
    cout << "Transducer           | " << head->getTransducer(sig) << endl;
    cout << endl << endl;
}

void printAllSignalInfo(EDFHeader* head) {
    cout << fixed << setprecision(4);
    for (int sig = 0; sig < head->getSignalCount() && sig != head->getAnnotationIndex(); sig++) {
        cout << "Signal (" << sig + 1 << ") Info" << endl << endl;
        cout << "Label                | " << head->getLabel(sig) << endl;
        cout << "Record Samples       | " << head->getDataRecordCount() * head->getSignalSampleCount(sig) << endl;
        cout << "Sample Count         | " << head->getSignalSampleCount(sig) << endl;
        cout << "Physical Max         | " << head->getPhysicalMax(sig) << endl;
        cout << "Physical Min         | " << head->getPhysicalMin(sig) << endl;
        cout << "Physical Dimension   | " << head->getPhysicalDimension(sig) << endl;
        cout << "Digital Max          | " << head->getDigitalMax(sig) << endl;
        cout << "Digital Min          | " << head->getDigitalMin(sig) << endl;
        cout << "Prefilter            | " << head->getPrefilter(sig) << endl;
        cout << "Transducer           | " << head->getTransducer(sig) << endl;
        cout << endl << endl;
    }
}

void printSignalData(EDFFile& file, int signal, float start, float length) {
    EDFSignalData* sigData = file.getSignalData(signal, start, length);
    cout << *sigData;
}

int main(int argc, char** argv) {
    EDFFile *newFile = new EDFFile(argv[1]);
    int signal = atoi(argv[2]) - 1;

    EDFHeader* header = newFile->getHeader();
    vector<EDFAnnotation>* annotations = newFile->getAnnotations();

    printHeaderInfo(argv[1], header);
    printSignalInfo(signal, header);
    printAnnotationInfo(annotations);

    double startTime = 0.0; // seconds
    double length = 2.0; // seconds
    cout << startTime << "s -> " << startTime + length << "s" << endl;
    printSignalData(*newFile, signal, startTime, length);

    startTime = 1.0;
    length = 1.0;
    cout << startTime << "s -> " << startTime + length << "s" << endl;
    printSignalData(*newFile, signal, startTime, length);

    delete newFile;

    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>void loadlibs ()
{
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libminicern");
  gSystem->Load("$(ROOTSYS)/lib/libPhysics");
  gSystem->Load("$(ROOTSYS)/lib/libEG");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTGeant3Dummy");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libhijing.so");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTHijing");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummypythia6");
  gSystem->Load("$(ROOTSYS)/lib/libEGPythia6");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libEVGEN");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRALICE");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libFMD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libMUON");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPHOS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPMD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRICH");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTRUCT");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTOF");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTPC");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTRD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libZDC");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libITS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCASTOR");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTART");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCONTAINERS");
}
<commit_msg>libCONTAINERS loaded first<commit_after>void loadlibs ()
{
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libminicern");
  gSystem->Load("$(ROOTSYS)/lib/libPhysics");
  gSystem->Load("$(ROOTSYS)/lib/libEG");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTGeant3Dummy");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libhijing.so");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTHijing");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummypythia6");
  gSystem->Load("$(ROOTSYS)/lib/libEGPythia6");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCONTAINERS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libEVGEN");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRALICE");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libFMD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libMUON");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPHOS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPMD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRICH");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTRUCT");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTOF");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTPC");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTRD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libZDC");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libITS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCASTOR");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTART");
}
<|endoftext|>


<commit_before>//
// Created by peixot_b on 23/05/17.
//

#include <iostream>
#include "Fire.hpp"
#include "map.hpp"
#include <irrlicht.h>

const std::map<FireDirection, std::function<void(irr::core::vector3di &pos)>> Fire::_DIRECTIONS_ACTION = {
	{FORWARD,  [](irr::core::vector3di &pos) { pos.X += 1; }},
	{BACKWARD, [](irr::core::vector3di &pos) { pos.X -= 1; }},
	{RIGHT,    [](irr::core::vector3di &pos) { pos.Y += 1; }},
	{LEFT,     [](irr::core::vector3di &pos) { pos.Y -= 1; }}
};

Fire::Fire(is:: map &map, irr::scene::ISceneManager* smgr, irr::video::IVideoDriver* driver,
	   irr::core::vector3df Position, irr::core::vector3df posMap, FireDirection Direction, float power) :
	_power(power),
	_map(map),
	_pos({posMap.X, posMap.Y, posMap.Z}),
	_dir(Direction)
{
  initMapDir();
  std::cout << "power = " << power << std::endl;
  _fireText = driver->getTexture("./gfx/fire.bmp");
  _ps = smgr->addParticleSystemSceneNode(false);
  createBox(Direction, power);
  createFire(smgr, Position);
  _ps->setEmitter(0);
}

Fire::~Fire()
{
}

void Fire::startFire()
{
  irr::core::vector3di  pos(this->_pos);

  _ps->setEmitter(_em);
  std::cerr << "START FIRE" << std::endl;
  for (float i = 0.0f ; i < _power ; i += 1)
    {
      std::cout << "START FIRE pos.x = " << pos.X << " pos.y = " << pos.Y << " pos.z = " << pos.Z<< std::endl;
      this->_map.addObject(is::Type::FIRE, {pos.X, pos.Y, pos.Z});
      _DIRECTIONS_ACTION.at(this->_dir)(pos);
    }
  std::cerr << "START FIRE" << std::endl;
}

void Fire::stopFire()
{
  _ps->setEmitter(0);
  std::cerr << "DELETE FIRE" << std::endl;
  irr::core::vector3di  pos(this->_pos);
  for (float i = 0.0f ; i <= _power ; i += 1)
    {
      std::cout << "DELETE FIRE pos.x = " << pos.X << " pos.y = " << pos.Y << " pos.z = " << pos.Z<< std::endl;
      this->_map.delObject({pos.X, pos.Y, pos.Z});
      _DIRECTIONS_ACTION.at(this->_dir)(pos);
    }
  std::cerr << "DELETE FIRE" << std::endl;
  _em->drop();
  _ps->remove();
}

void	Fire::initMapDir()
{
  std::map<FireDirection, irr::core::vector3df> m;
  m = {{FORWARD, irr::core::vector3df(0.00f, 0.00f, 0.015f)},
       {BACKWARD, irr::core::vector3df(0.00f, 0.00f, -0.015f)},
       {LEFT, irr::core::vector3df(-0.015f, 0.0f, 0.0f)},
       {RIGHT, irr::core::vector3df(0.015f, 0.00f, 0.0f)},
       {TOP, irr::core::vector3df(0.00f, 0.015f, 0.0f)},
       {DOWN, irr::core::vector3df(0.00f, -0.015f, 0.0f)}};
  _direction = m;
}

void	Fire::createBox(FireDirection Direction, irr::f32 power)
{
  irr::core::vector3df	newPower(power * 1.5, power * 1.5, power * 1.5);

  for (auto it = _direction.begin(); it != _direction.end(); it++)
    {
      if (it->first == Direction)
	{
	  _em = _ps->createBoxEmitter(
		  irr::core::aabbox3d<irr::f32>(-7, 0, -7, 7, 1, 7),
		  irr::core::vector3df(it->second * newPower),
		  80, 100,
		  irr::video::SColor(0, 255, 255, 0),
		  irr::video::SColor(0, 255, 255, 0),
		  200, 800, 0,
		  irr::core::dimension2df(10.f, 10.f),
		  irr::core::dimension2df(20.f, 20.f));
	  break;
	}
    }
}

void	Fire::createFire(irr::scene::ISceneManager* smgr, irr::core::vector3df Position)
{
  _ps->setEmitter(_em);
  _paf = _ps->createFadeOutParticleAffector();
  _ps->addAffector(_paf);
  _paf->drop();
  _ps->setPosition(Position);
  _ps->setScale(irr::core::vector3df(0.001 * (SCALE - 1), 0.001 * (SCALE - 1), 0.001 * (SCALE - 1)));
  _ps->setMaterialFlag(irr::video::EMF_LIGHTING, false);
  _ps->setMaterialFlag(irr::video::EMF_ZWRITE_ENABLE, false);
  _ps->setMaterialTexture(0, _fireText);
  _ps->setMaterialType(irr::video::EMT_TRANSPARENT_ADD_COLOR);
  std::cout << "debut createFire" << std::endl;
}

void	Fire::setPosition(irr::core::vector3df position)
{
  _ps->setPosition(position);
}

void	Fire::setScale(irr::core::vector3df scale)
{
  _ps->setScale(scale);
}

void Fire::draw()
{
  _ps->render();
}
<commit_msg>Maj fire<commit_after>//
// Created by peixot_b on 23/05/17.
//

#include <iostream>
#include "Fire.hpp"
#include "map.hpp"
#include <irrlicht.h>

const std::map<FireDirection, std::function<void(irr::core::vector3di &pos)>> Fire::_DIRECTIONS_ACTION = {
	{FORWARD,  [](irr::core::vector3di &pos) { pos.X += 1; }},
	{BACKWARD, [](irr::core::vector3di &pos) { pos.X -= 1; }},
	{RIGHT,    [](irr::core::vector3di &pos) { pos.Y += 1; }},
	{LEFT,     [](irr::core::vector3di &pos) { pos.Y -= 1; }}
};

Fire::Fire(is:: map &map, irr::scene::ISceneManager* smgr, irr::video::IVideoDriver* driver,
	   irr::core::vector3df Position, irr::core::vector3df posMap, FireDirection Direction, float power) :
	_power(power),
	_map(map),
	_pos({posMap.X, posMap.Y, posMap.Z}),
	_dir(Direction)
{
  initMapDir();
  std::cout << "power = " << power << std::endl;
  _fireText = driver->getTexture("./gfx/fire.bmp");
  _ps = smgr->addParticleSystemSceneNode(false);
  createBox(Direction, power);
  createFire(smgr, Position);
  _ps->setEmitter(0);
}

Fire::~Fire()
{
}

void Fire::startFire()
{
  irr::core::vector3di  pos(this->_pos);

  _ps->setEmitter(_em);
  std::cerr << "START FIRE" << std::endl;
  for (float i = 0.0f ; i <= _power ; i += 1)
    {
      std::cout << "START FIRE pos.x = " << pos.X << " pos.y = " << pos.Y << " pos.z = " << pos.Z<< std::endl;
      this->_map.addObject(is::Type::FIRE, {pos.X, pos.Y, pos.Z});
      _DIRECTIONS_ACTION.at(this->_dir)(pos);
    }
  std::cerr << "START FIRE" << std::endl;
}

void Fire::stopFire()
{
  _ps->setEmitter(0);
  _em->drop();
  _ps->remove();
  std::cerr << "DELETE FIRE" << std::endl;
  irr::core::vector3di  pos(this->_pos);
  for (float i = 0.0f ; i <= _power ; i += 1)
    {
      std::cout << "DELETE FIRE pos.x = " << pos.X << " pos.y = " << pos.Y << " pos.z = " << pos.Z<< std::endl;
      this->_map.delObject({pos.X, pos.Y, pos.Z});
      _DIRECTIONS_ACTION.at(this->_dir)(pos);
    }
  std::cerr << "DELETE FIRE" << std::endl;
}

void	Fire::initMapDir()
{
  std::map<FireDirection, irr::core::vector3df> m;
  m = {{FORWARD, irr::core::vector3df(0.00f, 0.00f, 0.015f)},
       {BACKWARD, irr::core::vector3df(0.00f, 0.00f, -0.015f)},
       {LEFT, irr::core::vector3df(-0.015f, 0.0f, 0.0f)},
       {RIGHT, irr::core::vector3df(0.015f, 0.00f, 0.0f)},
       {TOP, irr::core::vector3df(0.00f, 0.015f, 0.0f)},
       {DOWN, irr::core::vector3df(0.00f, -0.015f, 0.0f)}};
  _direction = m;
}

void	Fire::createBox(FireDirection Direction, irr::f32 power)
{
  irr::core::vector3df	newPower(power * 1.5, power * 1.5, power * 1.5);

  for (auto it = _direction.begin(); it != _direction.end(); it++)
    {
      if (it->first == Direction)
	{
	  _em = _ps->createBoxEmitter(
		  irr::core::aabbox3d<irr::f32>(-7, 0, -7, 7, 1, 7),
		  irr::core::vector3df(it->second * newPower),
		  80, 100,
		  irr::video::SColor(0, 255, 255, 0),
		  irr::video::SColor(0, 255, 255, 0),
		  200, 800, 0,
		  irr::core::dimension2df(10.f, 10.f),
		  irr::core::dimension2df(20.f, 20.f));
	  break;
	}
    }
}

void	Fire::createFire(irr::scene::ISceneManager* smgr, irr::core::vector3df Position)
{
  _ps->setEmitter(_em);
  _paf = _ps->createFadeOutParticleAffector();
  _ps->addAffector(_paf);
  _paf->drop();
  _ps->setPosition(Position);
  _ps->setScale(irr::core::vector3df(0.001 * (SCALE - 1), 0.001 * (SCALE - 1), 0.001 * (SCALE - 1)));
  _ps->setMaterialFlag(irr::video::EMF_LIGHTING, false);
  _ps->setMaterialFlag(irr::video::EMF_ZWRITE_ENABLE, false);
  _ps->setMaterialTexture(0, _fireText);
  _ps->setMaterialType(irr::video::EMT_TRANSPARENT_ADD_COLOR);
  std::cout << "debut createFire" << std::endl;
}

void	Fire::setPosition(irr::core::vector3df position)
{
  _ps->setPosition(position);
}

void	Fire::setScale(irr::core::vector3df scale)
{
  _ps->setScale(scale);
}

void Fire::draw()
{
  _ps->render();
}
<|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;

struct MountainWalk {
	int cellsVisited(vector <string> m, int k) {
		int x = 0, y = 0;
		int w = sz(m), h = sz(m[0]);
		int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
		int c = 1;
		vector<string> t = m;
		for (;;) {
			bool f = true;
			fr(i, 4) {
				int nx = x + dx[i];
				int ny = y + dy[i];
				cout << '-' << abs(m[x][y] - m[nx][ny]) << endl;
				if (0 <= nx && nx < w && 0 <= ny && ny < h && t[nx][ny] != '-' && abs(m[x][y] - m[nx][ny]) <= k) {
					x = nx;
					y = ny;
					t[x][y] = '-';
					++c;
					f = false;
					break;
				}
			}
			if (f) break;
		}
		return c;
	}
};

// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, int p1, bool hasAnswer, int p2) {
	cout << "Test " << testNum << ": [" << "{";
	for (int i = 0; int(p0.size()) > i; ++i) {
		if (i > 0) {
			cout << ",";
		}
		cout << "\"" << p0[i] << "\"";
	}
	cout << "}" << "," << p1;
	cout << "]" << endl;
	MountainWalk *obj;
	int answer;
	obj = new MountainWalk();
	clock_t startTime = clock();
	answer = obj->cellsVisited(p0, p1);
	clock_t endTime = clock();
	delete obj;
	bool res;
	res = true;
	cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
	if (hasAnswer) {
		cout << "Desired answer:" << endl;
		cout << "\t" << p2 << endl;
	}
	cout << "Your answer:" << endl;
	cout << "\t" << answer << endl;
	if (hasAnswer) {
		res = answer == p2;
	}
	if (!res) {
		cout << "DOESN'T MATCH!!!!" << endl;
	} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
		cout << "FAIL the timeout" << endl;
		res = false;
	} else if (hasAnswer) {
		cout << "Match :-)" << endl;
	} else {
		cout << "OK, but is it right?" << endl;
	}
	cout << "" << endl;
	return res;
}
int main() {
	bool all_right;
	bool disabled;
	bool tests_disabled;
	all_right = true;
	tests_disabled = false;

	vector <string> p0;
	int p1;
	int p2;

	// ----- test 0 -----
	disabled = false;
	p0 = {"056","135","234"};
	p1 = 1;
	p2 = 5;
	all_right = (disabled || KawigiEdit_RunTest(0, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 1 -----
	disabled = false;
	p0 = {"056","195","234"};
	p1 = 1;
	p2 = 8;
	all_right = (disabled || KawigiEdit_RunTest(1, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 2 -----
	disabled = false;
	p0 = {"865","123","111"};
	p1 = 3;
	p2 = 9;
	all_right = (disabled || KawigiEdit_RunTest(2, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 3 -----
	disabled = false;
	p0 = {"00009876543210","00009876543210","00009876543210","00009876543210"};
	p1 = 8;
	p2 = 16;
	all_right = (disabled || KawigiEdit_RunTest(3, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 4 -----
	disabled = false;
	p0 = {"0000","0000","0000","0000","9999","8888","7777","6666","5555","4444","3333","2222","1111","0000"};
	p1 = 3;
	p2 = 16;
	all_right = (disabled || KawigiEdit_RunTest(4, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 5 -----
	disabled = false;
	p0 = {"173642855131893831828253420","126290035950506994475683704","381277675415026563959463393","019782700912864681764582260","496448425114634806770407597","049628433145840178727435051","117194708226266248973780562","398138380998246682323622510","408178777661559971959512111"};
	p1 = 8;
	p2 = 135;
	all_right = (disabled || KawigiEdit_RunTest(5, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 6 -----
	disabled = false;
	p0 = {"9"};
	p1 = 0;
	p2 = 1;
	all_right = (disabled || KawigiEdit_RunTest(6, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	if (all_right) {
		if (tests_disabled) {
			cout << "You're a stud (but some test cases were disabled)!" << endl;
		} else {
			cout << "You're a stud (at least on given cases)!" << endl;
		}
	} else {
		cout << "Some of the test cases had errors." << endl;
	}
	return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>MountainWalk<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;

struct MountainWalk {
	int cellsVisited(vector <string> m, int k) {
		int x = 0, y = 0;
		int w = sz(m), h = sz(m[0]);
		int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
		int c = 1;
		vector<string> t = m;
		for (;;) {
			bool f = true;
			fr(i, 4) {
				int nx = x + dx[i];
				int ny = y + dy[i];
				if (0 <= nx && nx < w && 0 <= ny && ny < h && t[nx][ny] != '-' && abs(m[x][y] - m[nx][ny]) <= k) {
					x = nx;
					y = ny;
					t[x][y] = '-';
					++c;
					f = false;
					break;
				}
			}
			if (f) break;
		}
		return c;
	}
};

// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, int p1, bool hasAnswer, int p2) {
	cout << "Test " << testNum << ": [" << "{";
	for (int i = 0; int(p0.size()) > i; ++i) {
		if (i > 0) {
			cout << ",";
		}
		cout << "\"" << p0[i] << "\"";
	}
	cout << "}" << "," << p1;
	cout << "]" << endl;
	MountainWalk *obj;
	int answer;
	obj = new MountainWalk();
	clock_t startTime = clock();
	answer = obj->cellsVisited(p0, p1);
	clock_t endTime = clock();
	delete obj;
	bool res;
	res = true;
	cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
	if (hasAnswer) {
		cout << "Desired answer:" << endl;
		cout << "\t" << p2 << endl;
	}
	cout << "Your answer:" << endl;
	cout << "\t" << answer << endl;
	if (hasAnswer) {
		res = answer == p2;
	}
	if (!res) {
		cout << "DOESN'T MATCH!!!!" << endl;
	} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
		cout << "FAIL the timeout" << endl;
		res = false;
	} else if (hasAnswer) {
		cout << "Match :-)" << endl;
	} else {
		cout << "OK, but is it right?" << endl;
	}
	cout << "" << endl;
	return res;
}
int main() {
	bool all_right;
	bool disabled;
	bool tests_disabled;
	all_right = true;
	tests_disabled = false;

	vector <string> p0;
	int p1;
	int p2;

	// ----- test 0 -----
	disabled = false;
	p0 = {"056","135","234"};
	p1 = 1;
	p2 = 5;
	all_right = (disabled || KawigiEdit_RunTest(0, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 1 -----
	disabled = false;
	p0 = {"056","195","234"};
	p1 = 1;
	p2 = 8;
	all_right = (disabled || KawigiEdit_RunTest(1, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 2 -----
	disabled = false;
	p0 = {"865","123","111"};
	p1 = 3;
	p2 = 9;
	all_right = (disabled || KawigiEdit_RunTest(2, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 3 -----
	disabled = false;
	p0 = {"00009876543210","00009876543210","00009876543210","00009876543210"};
	p1 = 8;
	p2 = 16;
	all_right = (disabled || KawigiEdit_RunTest(3, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 4 -----
	disabled = false;
	p0 = {"0000","0000","0000","0000","9999","8888","7777","6666","5555","4444","3333","2222","1111","0000"};
	p1 = 3;
	p2 = 16;
	all_right = (disabled || KawigiEdit_RunTest(4, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 5 -----
	disabled = false;
	p0 = {"173642855131893831828253420","126290035950506994475683704","381277675415026563959463393","019782700912864681764582260","496448425114634806770407597","049628433145840178727435051","117194708226266248973780562","398138380998246682323622510","408178777661559971959512111"};
	p1 = 8;
	p2 = 135;
	all_right = (disabled || KawigiEdit_RunTest(5, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 6 -----
	disabled = false;
	p0 = {"9"};
	p1 = 0;
	p2 = 1;
	all_right = (disabled || KawigiEdit_RunTest(6, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	if (all_right) {
		if (tests_disabled) {
			cout << "You're a stud (but some test cases were disabled)!" << endl;
		} else {
			cout << "You're a stud (at least on given cases)!" << endl;
		}
	} else {
		cout << "Some of the test cases had errors." << endl;
	}
	return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|>


<commit_before>#include <QTRSensors.h>
#include <ZumoReflectanceSensorArray.h>
#include <Pushbutton.h>
#include <LSM303.h>
#include <Wire.h>

/***
    Dev Notes:
        -Acceleration seems to read only in X,Y directions. I guess Z
            could work, I'd have to look further into the header, but
            I don't think that is important
        -From what I've seen, compass does not give three points of data,
            just a single heading. There are a few other functions that were
            provided by examples and put into an array. But it will not be
            traditional X, Y, Z points. Currently it's one int- the average heading over ten reads.
        -Can I find those libraries? I don't think I have them.
        -Stuff like `contact` needs calibration. What is "X" and "Y" relative to the front of the bot?
***/
#define NUM_SENSORS 6
#define QTR_THRESHOLD 1000 // microseconds (This is for determining white from black)

#define CALIBRATION_SAMPLES 70 // Number of compass readings to take when calibrating
#define CRB_REG_M_2_5GAUSS 0x60 // CRB_REG_M value for magnetometer +/-2.5 gauss full scale
#define CRA_REG_M_220HZ 0x1C // CRA_REG_M value for magnetometer 220 Hz update rate

unsigned int sensor_values[NUM_SENSORS];
ZumoReflectanceSensorArray sensors(QTR_NO_EMITTER_PIN);
Pushbutton button(ZUMO_BUTTON); // pushbutton on pin 12
LSM303 compass;

typedef struct sensors_t_ {
  unsigned int ir[6];
  float acc[3];
  float comp[3];
  bool pushbutton;
  float vbat;
  bool contact;
  bool contactLeft;
  bool lineLeft;
  bool lineRight;
  bool slip;
  int angleOfIncidence;
} sensors_t;
// Accelerometer Class -- extends the LSM303 Library to support reading and averaging the x-y acceleration
// vectors from the onboard LSM303DLHC accelerometer/magnetometer
class Accelerometer : public LSM303
{
  typedef struct acc_data_xy
  {
  unsigned long timestamp;
  int x;
  int y;
  float dir;
  } acc_data_xy;
  public:
  Accelerometer() : ra_x(RA_SIZE), ra_y(RA_SIZE) {};
  ~Accelerometer() {};
  void enable(void);
  void getLogHeader(void);
  void readAcceleration(unsigned long timestamp);
  float len_xy() const;
  float dir_xy() const;
  int x_avg(void) const;
  int y_avg(void) const;
  long ss_xy_avg(void) const;
  float dir_xy_avg(void) const;
  private:
  acc_data_xy last;
  RunningAverage<int> ra_x;
  RunningAverage<int> ra_y;
};
Accelerometer lsm303;

void setup() {
   // Initiate LSM303
  lsm303.init();
  lsm303.enable();
  LSM303::vector<int16_t> running_min = {32767, 32767, 32767}, running_max = {-32767, -32767, -32767};
  Serial.begin(9600);
   // Initiate LSM303
  compass.init();
  // Enables accelerometer and magnetometer
  compass.enableDefault();
  compass.writeReg(LSM303::CRB_REG_M, CRB_REG_M_2_5GAUSS); // +/- 2.5 gauss sensitivity to hopefully avoid overflow problems
  compass.writeReg(LSM303::CRA_REG_M, CRA_REG_M_220HZ); // 220 Hz compass update rate

  //How much calibration do we really need to do for a useless sensor?
  for(index = 0; index < CALIBRATION_SAMPLES; index ++)
  {
    // Take a reading of the magnetic vector and store it in compass.m
    compass.read();
    running_min.x = min(running_min.x, compass.m.x);
    running_min.y = min(running_min.y, compass.m.y);
    running_max.x = max(running_max.x, compass.m.x);
    running_max.y = max(running_max.y, compass.m.y);
    Serial.println(index);
    delay(50);
  }
  // Set calibrated values to compass.m_max and compass.m_min
  compass.m_max.x = running_max.x;
  compass.m_max.y = running_max.y;
  compass.m_min.x = running_min.x;
  compass.m_min.y = running_min.y;

}
void loop() {
  sensors.read(sensor_values);
  loop_start_time = millis();
  lsm303.readAcceleration(loop_start_time);
  //Raw Data
  sensors_t.ir = sensor_values;
  //TODO Z
  sensors_t.acc = lsm303.getAcceleration();
  //FIXME One int, not 3
  sensors_t.comp = averageHeading();
  sensors_t.pushbutton = button.isPressed();
  //TODO Look up data
  sensors_t.vbat = 0;
  //Parse Data
  sensors_t.contact = sensors_t.acc[0] > 1;
  sensors_t.contactLeft = sensors_t.acc[1] > 1;
  sensors_t.lineLeft = sensor_values[0] < QTR_THRESHOLD;
  sensors_t.lineRight = sensor_values[5] < QTR_THRESHOLD;
  sensors_t.slip = sensors_t.acc[0] > 2;
  //HMM - Just made something up
  sensors_t.angleOfIncidence = sin(sensors_t.acc[0]+sensors_t.acc[1]);
  /*
  typedef struct {
		unsigned int ir[6];
		float acc[3];
		float comp[3];
		bool pushbutton;
		float vbat;
		bool contact;
		bool contactLeft;
		bool lineLeft;
		bool lineRight;
		bool slip;
		int angleOfIncidence;
	} sensors_t;
  */
}

/***
*      ACCELEROMETER  *
*      ACCELERATOR    *
*      ACCELERATION   *
***/
// class Accelerometer -- member function definitions
// enable accelerometer only
// to enable both accelerometer and magnetometer, call enableDefault() instead
void Accelerometer::enable(void)
  {
  // Enable Accelerometer
  // 0x27 = 0b00100111
  // Normal power mode, all axes enabled
  writeAccReg(LSM303::CTRL_REG1_A, 0x27);
  if (getDeviceType() == LSM303::device_DLHC)
  writeAccReg(LSM303::CTRL_REG4_A, 0x08); // DLHC: enable high resolution mode
  }
  void Accelerometer::getLogHeader(void)
  {
  Serial.print("millis x y len dir | len_avg dir_avg | avg_len");
  Serial.println();
  }
  int[3] Accelerometer::getAcceleration(unsigned long timestamp) {
     int foo[] = {last.x, last.y};
     return foo;
  }
  void Accelerometer::readAcceleration(unsigned long timestamp)
  {
  readAcc();
  if (a.x == last.x && a.y == last.y) return;
  last.timestamp = timestamp;
  last.x = a.x;
  last.y = a.y;
  ra_x.addValue(last.x);
  ra_y.addValue(last.y);
  #ifdef LOG_SERIAL
  Serial.print(last.timestamp);
  Serial.print(" ");
  Serial.print(last.x);
  Serial.print(" ");
  Serial.print(last.y);
  Serial.print(" ");
  Serial.print(len_xy());
  Serial.print(" ");
  Serial.print(dir_xy());
  Serial.print(" | ");
  Serial.print(sqrt(static_cast<float>(ss_xy_avg())));
  Serial.print(" ");
  Serial.print(dir_xy_avg());
  Serial.println();
  #endif
  }
  float Accelerometer::len_xy() const
  {
  return sqrt(last.x*a.x + last.y*a.y);
  }
  float Accelerometer::dir_xy() const
  {
  return atan2(last.x, last.y) * 180.0 / M_PI;
  }
  int Accelerometer::x_avg(void) const
  {
  return ra_x.getAverage();
  }
  int Accelerometer::y_avg(void) const
  {
  return ra_y.getAverage();
  }
  long Accelerometer::ss_xy_avg(void) const
  {
  long x_avg_long = static_cast<long>(x_avg());
  long y_avg_long = static_cast<long>(y_avg());
  return x_avg_long*x_avg_long + y_avg_long*y_avg_long;
  }
  float Accelerometer::dir_xy_avg(void) const
  {
  return atan2(static_cast<float>(x_avg()), static_cast<float>(y_avg())) * 180.0 / M_PI;
  }
  // RunningAverage class
  // based on RunningAverage library for Arduino
  // source: http://playground.arduino.cc/Main/RunningAverage
  // author: Rob.Tillart@gmail.com
  // Released to the public domain
  template <typename T>
  T RunningAverage<T>::zero = static_cast<T>(0);
  template <typename T>
  RunningAverage<T>::RunningAverage(int n)
  {
  _size = n;
  _ar = (T*) malloc(_size * sizeof(T));
  clear();
  }
  template <typename T>
  RunningAverage<T>::~RunningAverage()
  {
  free(_ar);
  }
  // resets all counters
  template <typename T>
  void RunningAverage<T>::clear()
  {
  _cnt = 0;
  _idx = 0;
  _sum = zero;
  for (int i = 0; i< _size; i++) _ar[i] = zero; // needed to keep addValue simple
  }
  // adds a new value to the data-set
  template <typename T>
  void RunningAverage<T>::addValue(T f)
  {
  _sum -= _ar[_idx];
  _ar[_idx] = f;
  _sum += _ar[_idx];
  _idx++;
  if (_idx == _size) _idx = 0; // faster than %
  if (_cnt < _size) _cnt++;
  }
  // returns the average of the data-set added so far
  template <typename T>
  T RunningAverage<T>::getAverage() const
  {
  if (_cnt == 0) return zero; // NaN ? math.h
  return _sum / _cnt;
  }
  // fill the average with a value
  // the param number determines how often value is added (weight)
  // number should preferably be between 1 and size
  template <typename T>
  void RunningAverage<T>::fillValue(T value, int number)
  {
  clear();
  for (int i = 0; i < number; i++)
  {
  addValue(value);
  }
}

/***
*                 *
*      COMPASS    *
*                 *
***/
// Converts x and y components of a vector to a heading in degrees.
// This function is used instead of LSM303::heading() because we don't
// want the acceleration of the Zumo to factor spuriously into the
// tilt compensation that LSM303::heading() performs. This calculation
// assumes that the Zumo is always level.
template <typename T> float heading(LSM303::vector<T> v)
{
  float x_scaled = 2.0*(float)(v.x - compass.m_min.x) / ( compass.m_max.x - compass.m_min.x) - 1.0;
  float y_scaled = 2.0*(float)(v.y - compass.m_min.y) / (compass.m_max.y - compass.m_min.y) - 1.0;
  float angle = atan2(y_scaled, x_scaled)*180 / M_PI;
  if (angle < 0)
  angle += 360;
  return angle;
}
// Yields the angle difference in degrees between two headings
float relativeHeading(float heading_from, float heading_to)
{
  float relative_heading = heading_to - heading_from;
  // constrain to -180 to 180 degree range
  if (relative_heading > 180)
  relative_heading -= 360;
  if (relative_heading < -180)
  relative_heading += 360;
  return relative_heading;
}
// Average 10 vectors to get a better measurement and help smooth out
// the motors' magnetic interference.
float averageHeading()
{
  LSM303::vector<int32_t> avg = {0, 0, 0};
  for(int i = 0; i < 10; i ++)
  {
  compass.read();
  avg.x += compass.m.x;
  avg.y += compass.m.y;
  }
  avg.x /= 10.0;
  avg.y /= 10.0;
  // avg is the average measure of the magnetic vector.
  return heading(avg);
}

<commit_msg>Cleanup<commit_after>#include <QTRSensors.h>
#include <ZumoReflectanceSensorArray.h>
#include <Pushbutton.h>
#include <LSM303.h>
#include <Wire.h>

/***
    Dev Notes:
        -Acceleration seems to read only in X,Y directions. I guess Z
            could work, I'd have to look further into the header, but
            I don't think that is important
        -From what I've seen, compass does not give three points of data,
            just a single heading. There are a few other functions that were
            provided by examples and put into an array. But it will not be
            traditional X, Y, Z points. Currently it's one int- the average heading over ten reads.
        -Can I find those libraries? I don't think I have them.
        -Stuff like `contact` needs calibration. What is "X" and "Y" relative to the front of the bot?

        Tasks to complete
        [ ] Where can I find the specs for the voltage tester?
        [ ] For the accel, which direction is "X"?
        [ ] Is the external LSM library included with the examples?
        [ ] If not, is this library needed? What's up with LSM303.h and Wire.h
        [ ] Calibrate values
        [ ] Angle of Incidence math
        [X] Discover exactly what versino of the accel/magne that is available: LSM303DLHC (http://www.pololu.com/catalog/product/2124)
        [ ] There's probably other stuff to be done, like the voltage regulator specs

        https://github.com/pololu/lsm303-arduino

***/
#define NUM_SENSORS 6
#define QTR_THRESHOLD 1000 // microseconds (This is for determining white from black)
#define ACC_THRESHOLD 1 //In odd units -- this is just something that needs plenty of calibration
#define SLIP_THRESHOLD 2 //In odd units -- this is the acceleration detection for slippage

#define CALIBRATION_SAMPLES 70 // Number of compass readings to take when calibrating
#define CRB_REG_M_2_5GAUSS 0x60 // CRB_REG_M value for magnetometer +/-2.5 gauss full scale
#define CRA_REG_M_220HZ 0x1C // CRA_REG_M value for magnetometer 220 Hz update rate

unsigned int sensor_values[NUM_SENSORS];
ZumoReflectanceSensorArray sensors(QTR_NO_EMITTER_PIN);
Pushbutton button(ZUMO_BUTTON); // pushbutton on pin 12
LSM303 compass;

typedef struct sensors_t_ {
  //commented with suggested types instead
  unsigned int ir[6];
  float acc[3];
  //float acc[2]
  float comp[3];
  //float comp
  bool pushbutton;
  float vbat;
  bool contact;
  bool contactLeft;
  bool lineLeft;
  bool lineRight;
  bool slip;
  int angleOfIncidence;
} sensors_t;
// Accelerometer Class -- extends the LSM303 Library to support reading and averaging the x-y acceleration
// vectors from the onboard LSM303DLHC accelerometer/magnetometer
class Accelerometer : public LSM303 {
  typedef struct acc_data_xy {
    unsigned long timestamp;
    int x;
    int y;
    float dir;
  } acc_data_xy;

  public:
    Accelerometer() : ra_x(RA_SIZE), ra_y(RA_SIZE) {};
    ~Accelerometer() {};
    void enable(void);
    void getLogHeader(void);
    void readAcceleration(unsigned long timestamp);
    float len_xy() const;
    float dir_xy() const;
    int x_avg(void) const;
    int y_avg(void) const;
    long ss_xy_avg(void) const;
    float dir_xy_avg(void) const;
  private:
    acc_data_xy last;
    RunningAverage<int> ra_x;
    RunningAverage<int> ra_y;
};
Accelerometer accelerometer;

void setup() {
  Wire.begin();
   // Initiate Accelerometer
  accelerometer.init();
  accelerometer.enable();
  LSM303::vector<int16_t> running_min = {32767, 32767, 32767}, running_max = {-32767, -32767, -32767};
  Serial.begin(9600);
   // Initiate LSM303
  compass.init();
  // Enables accelerometer and magnetometer
  compass.enableDefault();
  compass.writeReg(LSM303::CRB_REG_M, CRB_REG_M_2_5GAUSS); // +/- 2.5 gauss sensitivity to hopefully avoid overflow problems
  compass.writeReg(LSM303::CRA_REG_M, CRA_REG_M_220HZ); // 220 Hz compass update rate

  //TODO How much calibration do we really need to do for a useless sensor? Adjust num;
  for(index = 0; index < CALIBRATION_SAMPLES; index ++) {
    // Take a reading of the magnetic vector and store it in compass.m
    compass.read();
    running_min.x = min(running_min.x, compass.m.x);
    running_min.y = min(running_min.y, compass.m.y);
    running_max.x = max(running_max.x, compass.m.x);
    running_max.y = max(running_max.y, compass.m.y);
    Serial.println(index);
    delay(50);
  }
  // Set calibrated values to compass.m_max and compass.m_min
  compass.m_max.x = running_max.x;
  compass.m_max.y = running_max.y;
  compass.m_min.x = running_min.x;
  compass.m_min.y = running_min.y;

}
void loop() {
  sensors.read(sensor_values);
  loop_start_time = millis();
  accelerometer.readAcceleration(loop_start_time);
  //Raw Data
  sensors_t.ir = sensor_values;
  //TODO Z or change struct
  sensors_t.acc = accelerometer.getAcceleration();
  //FIXME One int, not 3
  sensors_t.comp = averageHeading();
  sensors_t.pushbutton = button.isPressed();
  //TODO Look up how to do that
  sensors_t.vbat = 0;
  //Parse Data
  sensors_t.contact = sensors_t.acc[0] > ACC_THRESHOLD;
  sensors_t.contactLeft = sensors_t.acc[1] > ACC_THRESHOLD;
  sensors_t.lineLeft = sensor_values[0] < QTR_THRESHOLD;
  sensors_t.lineRight = sensor_values[5] < QTR_THRESHOLD;
  sensors_t.slip = sensors_t.acc[0] > SLIP_THRESHOLD;
  //HMM - Just made something up. In theory some sort of trigonometric expression should correctly find the bot.
  sensors_t.angleOfIncidence = sin(sensors_t.acc[0]+sensors_t.acc[1]);
}

/***
*      ACCELEROMETER  *
*      ACCELERATOR    *
*      ACCELERATION   *
***/
// class Accelerometer -- member function definitions
// enable accelerometer only
// to enable both accelerometer and magnetometer, call enableDefault() instead
  void Accelerometer::enable(void) {
    // Enable Accelerometer
    // 0x27 = 0b00100111
    // Normal power mode, all axes enabled
    writeAccReg(LSM303::CTRL_REG1_A, 0x27);
    if (getDeviceType() == LSM303::device_DLHC)
      writeAccReg(LSM303::CTRL_REG4_A, 0x08); // DLHC: enable high resolution mode
  }
  void Accelerometer::getLogHeader(void) {
    Serial.print("millis x y len dir | len_avg dir_avg | avg_len");
    Serial.println();
  }
  //Gets the current acceleration of the device, no printing
  int[3] Accelerometer::getAcceleration(unsigned long timestamp) {
     int foo[] = {last.x, last.y};
     return foo;
  }
  void Accelerometer::readAcceleration(unsigned long timestamp) {
    readAcc();
    if (a.x == last.x && a.y == last.y) return;
    last.timestamp = timestamp;
    last.x = a.x;
    last.y = a.y;
    ra_x.addValue(last.x);
    ra_y.addValue(last.y);
    #ifdef LOG_SERIAL
    Serial.print(last.timestamp);
    Serial.print(" ");
    Serial.print(last.x);
    Serial.print(" ");
    Serial.print(last.y);
    Serial.print(" ");
    Serial.print(len_xy());
    Serial.print(" ");
    Serial.print(dir_xy());
    Serial.print(" | ");
    Serial.print(sqrt(static_cast<float>(ss_xy_avg())));
    Serial.print(" ");
    Serial.print(dir_xy_avg());
    Serial.println();
    #endif
  }
  float Accelerometer::len_xy() const {
    return sqrt(last.x*a.x + last.y*a.y);
  }
  float Accelerometer::dir_xy() const {
    return atan2(last.x, last.y) * 180.0 / M_PI;
  }
  int Accelerometer::x_avg(void) const {
    return ra_x.getAverage();
  }
  int Accelerometer::y_avg(void) const {
    return ra_y.getAverage();
  }
  long Accelerometer::ss_xy_avg(void) const {
    long x_avg_long = static_cast<long>(x_avg());
    long y_avg_long = static_cast<long>(y_avg());
    return x_avg_long*x_avg_long + y_avg_long*y_avg_long;
  }
  float Accelerometer::dir_xy_avg(void) const {
    return atan2(static_cast<float>(x_avg()), static_cast<float>(y_avg())) * 180.0 / M_PI;
  }
  // RunningAverage class
  // based on RunningAverage library for Arduino
  // source: http://playground.arduino.cc/Main/RunningAverage
  // author: Rob.Tillart@gmail.com
  // Released to the public domain
  template <typename T>
  T RunningAverage<T>::zero = static_cast<T>(0);
  template <typename T>
  RunningAverage<T>::RunningAverage(int n) {
    _size = n;
    _ar = (T*) malloc(_size * sizeof(T));
    clear();
  }
  template <typename T>
  RunningAverage<T>::~RunningAverage() {
    free(_ar);
  }
  // resets all counters
  template <typename T>
  void RunningAverage<T>::clear() {
    _cnt = 0;
    _idx = 0;
    _sum = zero;
    for (int i = 0; i< _size; i++) _ar[i] = zero; // needed to keep addValue simple
  }
  // adds a new value to the data-set
  template <typename T>
  void RunningAverage<T>::addValue(T f) {
    _sum -= _ar[_idx];
    _ar[_idx] = f;
    _sum += _ar[_idx];
    _idx++;
    if (_idx == _size) _idx = 0; // faster than %
    if (_cnt < _size) _cnt++;
  }
  // returns the average of the data-set added so far
  template <typename T>
  T RunningAverage<T>::getAverage() const {
    if (_cnt == 0) return zero; // NaN ? math.h
    return _sum / _cnt;
  }
  // fill the average with a value
  // the param number determines how often value is added (weight)
  // number should preferably be between 1 and size
  template <typename T>
  void RunningAverage<T>::fillValue(T value, int number) {
    clear();
    for (int i = 0; i < number; i++) {
      addValue(value);
    }
  }

/***
*                 *
*      COMPASS    *
*                 *
***/
// Converts x and y components of a vector to a heading in degrees.
// This function is used instead of LSM303::heading() because we don't
// want the acceleration of the Zumo to factor spuriously into the
// tilt compensation that LSM303::heading() performs. This calculation
// assumes that the Zumo is always level.
template <typename T> float heading(LSM303::vector<T> v) {
  float x_scaled = 2.0*(float)(v.x - compass.m_min.x) / ( compass.m_max.x - compass.m_min.x) - 1.0;
  float y_scaled = 2.0*(float)(v.y - compass.m_min.y) / (compass.m_max.y - compass.m_min.y) - 1.0;
  float angle = atan2(y_scaled, x_scaled)*180 / M_PI;
  if (angle < 0)
  angle += 360;
  return angle;
}
// Yields the angle difference in degrees between two headings
float relativeHeading(float heading_from, float heading_to) {
  float relative_heading = heading_to - heading_from;
  // constrain to -180 to 180 degree range
  if (relative_heading > 180)
  relative_heading -= 360;
  if (relative_heading < -180)
  relative_heading += 360;
  return relative_heading;
}
// Average 10 vectors to get a better measurement and help smooth out
// the motors' magnetic interference.
float averageHeading() {
  LSM303::vector<int32_t> avg = {0, 0, 0};
  for(int i = 0; i < 10; i ++) {
    compass.read();
    avg.x += compass.m.x;
    avg.y += compass.m.y;
  }
  avg.x /= 10.0;
  avg.y /= 10.0;
  // avg is the average measure of the magnetic vector.
  return heading(avg);
}
<|endoftext|>


<commit_before>#include "profileapplet.h"
#include "profiletranslation.h"
#include "profilewidget.h"
#include "profilebrief.h"

#include "dcpprofile.h"
#include "dcpwidget.h"

#include <QtGui>
#include <QDebug>

#include <DuiTheme>
#include <DuiAction>

Q_EXPORT_PLUGIN2(profileapplet, ProfileApplet)

const QString cssDir = "/usr/share/duicontrolpanel/themes/style/";

///////////////////////////
#include <DuiSceneManager>
void ProfileApplet::doRotation()
{
    int orientation = (int)DuiSceneManager::instance()->orientationAngle();
    orientation += 90;
    orientation %= 360;
    DuiSceneManager::instance()->setOrientationAngle((Dui::OrientationAngle) orientation);
}
void ProfileApplet::startRotation()
{
    QTimer *rotation = new QTimer(0);
    rotation->setInterval(15*1000);
    rotation->start();
    QObject::connect(rotation, SIGNAL(timeout()), this, SLOT(doRotation()));
}
///////////////////////////

void ProfileApplet::init(QString part)
{
    Q_UNUSED(part);
    DuiTheme::loadCSS(cssDir + "profileapplet.css");

    /* Un/comment this for rotation */

    startRotation();

    /**/
}

DcpWidget* ProfileApplet::constructWidget(int widgetId)
{
    switch (widgetId) {
        case DcpProfile::Main:
            return pageMain();
        break;
        default:
            qDebug() << "Page Unknown";
            return 0;
        break;
    }
}

DcpWidget* ProfileApplet::pageMain()
{
    qDebug() << "ProfileApplet::pageMain" << (QObject*)main;
    if(main == NULL)
        main = new ProfileWidget();
    return main;
}

QString ProfileApplet::title() const
{
    return DcpProfile::AppletTitle;
}

QVector<DuiAction*> ProfileApplet::viewMenuItems()
{
    QVector<DuiAction*> vector;
    DuiAction* helpAction = new DuiAction(DcpProfile::MenuHelpText, pageMain());
    vector.append(helpAction);
    return vector;
}

DcpBrief* ProfileApplet::constructBrief()
{
    return new ProfileBrief((ProfileWidget*)pageMain());
}
<commit_msg>Test rotation removed from applets.<commit_after>#include "profileapplet.h"
#include "profiletranslation.h"
#include "profilewidget.h"
#include "profilebrief.h"

#include "dcpprofile.h"
#include "dcpwidget.h"

#include <QtGui>
#include <QDebug>

#include <DuiTheme>
#include <DuiAction>

Q_EXPORT_PLUGIN2(profileapplet, ProfileApplet)

const QString cssDir = "/usr/share/duicontrolpanel/themes/style/";

///////////////////////////
#include <DuiSceneManager>
void ProfileApplet::doRotation()
{
    int orientation = (int)DuiSceneManager::instance()->orientationAngle();
    orientation += 90;
    orientation %= 360;
    DuiSceneManager::instance()->setOrientationAngle((Dui::OrientationAngle) orientation);
}
void ProfileApplet::startRotation()
{
    QTimer *rotation = new QTimer(0);
    rotation->setInterval(15*1000);
    rotation->start();
    QObject::connect(rotation, SIGNAL(timeout()), this, SLOT(doRotation()));
}
///////////////////////////

void ProfileApplet::init(QString part)
{
    Q_UNUSED(part);
    DuiTheme::loadCSS(cssDir + "profileapplet.css");

    /* Un/comment this for rotation *

    startRotation();

    **/
}

DcpWidget* ProfileApplet::constructWidget(int widgetId)
{
    switch (widgetId) {
        case DcpProfile::Main:
            return pageMain();
        break;
        default:
            qDebug() << "Page Unknown";
            return 0;
        break;
    }
}

DcpWidget* ProfileApplet::pageMain()
{
    qDebug() << "ProfileApplet::pageMain" << (QObject*)main;
    if(main == NULL)
        main = new ProfileWidget();
    return main;
}

QString ProfileApplet::title() const
{
    return DcpProfile::AppletTitle;
}

QVector<DuiAction*> ProfileApplet::viewMenuItems()
{
    QVector<DuiAction*> vector;
    DuiAction* helpAction = new DuiAction(DcpProfile::MenuHelpText, pageMain());
    vector.append(helpAction);
    return vector;
}

DcpBrief* ProfileApplet::constructBrief()
{
    return new ProfileBrief((ProfileWidget*)pageMain());
}
<|endoftext|>


<commit_before>/**
 *  Copyright 2015 MongoDB, Inc.
 *
 *  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.
 */

#include "bson.h"
#include <iostream>

extern "C" {
#include "libbson/src/bson/bson.h"
#include "libmongoc/src/mongoc/mongoc.h"
}

namespace HPHP {

int VariantToBsonConverter::_isPackedArray(const Array &a)
{
	int idx = 0, key_value = 0;

	for (ArrayIter iter(a); iter; ++iter) {
		Variant key(iter.first());

		if (!key.isInteger()) {
			return false;
		}

		key_value = key.toInt32();
		std::cout << idx << "key: " << key_value << "\n";

		if (idx != key_value) {
			return false;
		}

		idx++;
	}
	return true;
}

VariantToBsonConverter::VariantToBsonConverter(const Variant& document)
{
	m_document = document;
	m_level = 0;
}

void VariantToBsonConverter::convert(bson_t *bson)
{
	return convert(bson, m_document);
}

void VariantToBsonConverter::convert(bson_t *bson, Variant v)
{
	std::cout << "convert Variant\n";

	if (v.isObject()) {
		convert(bson, v.toObject());
	} else if (v.isArray()) {
		convert(bson, v.toArray());
	} else {
		std::cout << "convert *unimplemented*: " << getDataTypeString(v.getType()).c_str() << "\n";
	}
}

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, Variant v)
{
	switch (v.getType()) {
		case KindOfUninit:
		case KindOfNull:
			convertPart(bson, key);
			break;
		case KindOfBoolean:
			convertPart(bson, key, v.toBoolean());
			break;
		case KindOfInt64:
			convertPart(bson, key, v.toInt64());
			break;
		case KindOfDouble:
			convertPart(bson, key, v.toDouble());
			break;
		case KindOfStaticString:
		case KindOfString:
			convertPart(bson, key, v.toString());
			break;
		case KindOfArray:
			convertPart(bson, key, v.toArray(), true);
			break;
		case KindOfObject:
			convertPart(bson, key, v.toObject());
			break;
		default:
			break;
	}
}

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key)
{
	std::cout << "null\n";
	bson_append_null(bson, key, -1);
};

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, bool v)
{
	std::cout << "bool\n";
	bson_append_bool(bson, key, -1, v);
};

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, int64_t v)
{
	std::cout << "int64\n";
	bson_append_int64(bson, key, -1, v);
};

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, double v)
{
	std::cout << "double\n";
	bson_append_double(bson, key, -1, v);
};

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, String v)
{
	std::cout << "key: " << key << ", utf8: " << v.c_str() << "\n";
	bson_append_utf8(bson, key, -1, v.c_str(), v.size());
}

char *VariantToBsonConverter::_getUnmangledPropertyName(String key)
{
	const char *ckey = key.c_str();

	if (ckey[0] == '\0' && key.length()) {
		const char *cls = ckey + 1;
		if (*cls == '*') { // protected
			return strdup(ckey + 3);
		} else {
			int l = strlen(cls);
			return strdup(cls + l + 1);
		}
	} else {
		return strdup(ckey);
	}
}

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, Array v, bool wrap)
{
	bson_t child;
	int unmangle = 0;

	std::cout << "array\n";

	if (_isPackedArray(v)) {
		if (wrap) {
			bson_append_array_begin(bson, key, -1, &child);
		}
	} else {
		unmangle = 1;
		if (wrap) {
			bson_append_document_begin(bson, key, -1, &child);
		}
	}

	for (ArrayIter iter(v); iter; ++iter) {
		Variant key(iter.first());
		const Variant& data(iter.secondRef());

		if (unmangle) {
			const char *unmangledName;

			unmangledName = _getUnmangledPropertyName(key.toString());
			convertPart(wrap ? &child : bson, unmangledName, data);
			free((void*) unmangledName);
		} else {
			convertPart(wrap ? &child : bson, key.toString().c_str(), data);
		}
	}

	if (wrap) {
		if (_isPackedArray(v)) {
			bson_append_array_end(bson, &child);
		} else {
			bson_append_document_end(bson, &child);
		}
	}
}

/* {{{ Serialization of types */
const StaticString s_MongoDriverBsonType_className("MongoDB\\BSON\\Type");

/* {{{ MongoDriver\BSON\Regex */
const StaticString s_MongoDriverBsonRegex_className("MongoDB\\BSON\\Regex");
const StaticString s_MongoDriverBsonRegex_pattern("pattern");
const StaticString s_MongoDriverBsonRegex_flags("flags");

void VariantToBsonConverter::_convertRegex(bson_t *bson, const char *key, Object v)
{
	String regex = v.o_get(s_MongoDriverBsonRegex_pattern, false, s_MongoDriverBsonRegex_className);
	String flags = v.o_get(s_MongoDriverBsonRegex_flags, false, s_MongoDriverBsonRegex_className);

	bson_append_regex(bson, key, -1, regex.c_str(), flags.c_str());
}
/* }}} */

/* }}} */

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, Object v)
{
	std::cout << v->getClassName().c_str() << " object converted to ";

	if (v.instanceof(s_MongoDriverBsonType_className)) {
		std::cout << "internal type ";
		if (v.instanceof(s_MongoDriverBsonRegex_className)) {
			std::cout << "Regex\n";
			_convertRegex(bson, key, v);
		}
	} else {
		convertPart(bson, key, v.toArray());
	}
}

void VariantToBsonConverter::convert(bson_t *bson, Array a)
{
	std::cout << "convert Top Level Array\n";

	convertPart(bson, NULL, a, false);
}

void VariantToBsonConverter::convert(bson_t *bson, Object o)
{
	std::cout << "convert Top Level Object\n";

	convert(bson, o.toArray());
}

} /* namespace HPHP */
<commit_msg>Removed debug info from BSON serialization<commit_after>/**
 *  Copyright 2015 MongoDB, Inc.
 *
 *  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.
 */

#include "bson.h"
#include <iostream>

extern "C" {
#include "libbson/src/bson/bson.h"
#include "libmongoc/src/mongoc/mongoc.h"
}

namespace HPHP {

int VariantToBsonConverter::_isPackedArray(const Array &a)
{
	int idx = 0, key_value = 0;

	for (ArrayIter iter(a); iter; ++iter) {
		Variant key(iter.first());

		if (!key.isInteger()) {
			return false;
		}

		key_value = key.toInt32();

		if (idx != key_value) {
			return false;
		}

		idx++;
	}
	return true;
}

VariantToBsonConverter::VariantToBsonConverter(const Variant& document)
{
	m_document = document;
	m_level = 0;
}

void VariantToBsonConverter::convert(bson_t *bson)
{
	return convert(bson, m_document);
}

void VariantToBsonConverter::convert(bson_t *bson, Variant v)
{
	if (v.isObject()) {
		convert(bson, v.toObject());
	} else if (v.isArray()) {
		convert(bson, v.toArray());
	} else {
		std::cout << "convert *unimplemented*: " << getDataTypeString(v.getType()).c_str() << "\n";
	}
}

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, Variant v)
{
	switch (v.getType()) {
		case KindOfUninit:
		case KindOfNull:
			convertPart(bson, key);
			break;
		case KindOfBoolean:
			convertPart(bson, key, v.toBoolean());
			break;
		case KindOfInt64:
			convertPart(bson, key, v.toInt64());
			break;
		case KindOfDouble:
			convertPart(bson, key, v.toDouble());
			break;
		case KindOfStaticString:
		case KindOfString:
			convertPart(bson, key, v.toString());
			break;
		case KindOfArray:
			convertPart(bson, key, v.toArray(), true);
			break;
		case KindOfObject:
			convertPart(bson, key, v.toObject());
			break;
		default:
			break;
	}
}

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key)
{
	bson_append_null(bson, key, -1);
};

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, bool v)
{
	bson_append_bool(bson, key, -1, v);
};

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, int64_t v)
{
	bson_append_int64(bson, key, -1, v);
};

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, double v)
{
	bson_append_double(bson, key, -1, v);
};

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, String v)
{
	bson_append_utf8(bson, key, -1, v.c_str(), v.size());
}

char *VariantToBsonConverter::_getUnmangledPropertyName(String key)
{
	const char *ckey = key.c_str();

	if (ckey[0] == '\0' && key.length()) {
		const char *cls = ckey + 1;
		if (*cls == '*') { // protected
			return strdup(ckey + 3);
		} else {
			int l = strlen(cls);
			return strdup(cls + l + 1);
		}
	} else {
		return strdup(ckey);
	}
}

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, Array v, bool wrap)
{
	bson_t child;
	int unmangle = 0;

	if (_isPackedArray(v)) {
		if (wrap) {
			bson_append_array_begin(bson, key, -1, &child);
		}
	} else {
		unmangle = 1;
		if (wrap) {
			bson_append_document_begin(bson, key, -1, &child);
		}
	}

	for (ArrayIter iter(v); iter; ++iter) {
		Variant key(iter.first());
		const Variant& data(iter.secondRef());

		if (unmangle) {
			const char *unmangledName;

			unmangledName = _getUnmangledPropertyName(key.toString());
			convertPart(wrap ? &child : bson, unmangledName, data);
			free((void*) unmangledName);
		} else {
			convertPart(wrap ? &child : bson, key.toString().c_str(), data);
		}
	}

	if (wrap) {
		if (_isPackedArray(v)) {
			bson_append_array_end(bson, &child);
		} else {
			bson_append_document_end(bson, &child);
		}
	}
}

/* {{{ Serialization of types */
const StaticString s_MongoDriverBsonType_className("MongoDB\\BSON\\Type");

/* {{{ MongoDriver\BSON\Regex */
const StaticString s_MongoDriverBsonRegex_className("MongoDB\\BSON\\Regex");
const StaticString s_MongoDriverBsonRegex_pattern("pattern");
const StaticString s_MongoDriverBsonRegex_flags("flags");

void VariantToBsonConverter::_convertRegex(bson_t *bson, const char *key, Object v)
{
	String regex = v.o_get(s_MongoDriverBsonRegex_pattern, false, s_MongoDriverBsonRegex_className);
	String flags = v.o_get(s_MongoDriverBsonRegex_flags, false, s_MongoDriverBsonRegex_className);

	bson_append_regex(bson, key, -1, regex.c_str(), flags.c_str());
}
/* }}} */

/* }}} */

void VariantToBsonConverter::convertPart(bson_t *bson, const char *key, Object v)
{
	if (v.instanceof(s_MongoDriverBsonType_className)) {
		if (v.instanceof(s_MongoDriverBsonRegex_className)) {
			_convertRegex(bson, key, v);
		}
	} else {
		convertPart(bson, key, v.toArray());
	}
}

void VariantToBsonConverter::convert(bson_t *bson, Array a)
{
	convertPart(bson, NULL, a, false);
}

void VariantToBsonConverter::convert(bson_t *bson, Object o)
{
	convert(bson, o.toArray());
}

} /* namespace HPHP */
<|endoftext|>