<commit_before>// Created on: 2013-01-17
// Created by: Kirill GAVRILOV
// Copyright (c) 2013 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.

#ifdef HAVE_CONFIG_H
  #include <oce-config.h>
#endif

#include <Standard_CLocaleSentry.hxx>

#include <Standard_TypeDef.hxx>

#include <cstring>

namespace
{

  //! CLocalePtr - static object representing C locale
  class CLocalePtr
  {
  public:

    CLocalePtr()
    #ifdef HAVE_XLOCALE_H
    : myLocale (newlocale (LC_ALL_MASK, "C", NULL))
    #elif defined(_WIN32) && !defined(__BORLANDC__)
    : myLocale (_create_locale (LC_ALL, "C"))
    #else
    : myLocale (NULL)
    #endif
    {}

    ~CLocalePtr()
    {
    #ifdef HAVE_XLOCALE_H
      freelocale (myLocale);
    #elif defined(_WIN32) && !defined(__BORLANDC__)
      _free_locale (myLocale);
    #endif
    }

  public:

    Standard_CLocaleSentry::clocale_t myLocale;

  };

  static CLocalePtr theCLocale;

};

// =======================================================================
// function : GetCLocale
// purpose  :
// =======================================================================
Standard_CLocaleSentry::clocale_t Standard_CLocaleSentry::GetCLocale()
{
  return theCLocale.myLocale;
}

// =======================================================================
// function : Standard_CLocaleSentry
// purpose  :
// =======================================================================
Standard_CLocaleSentry::Standard_CLocaleSentry()
#ifdef HAVE_XLOCALE_H
: myPrevLocale (uselocale (theCLocale.myLocale)) // switch to C locale within this thread only using xlocale API
#else
: myPrevLocale (setlocale (LC_ALL, 0))
#if defined(_MSC_VER) && (_MSC_VER > 1400)
, myPrevTLocaleState (_configthreadlocale (_ENABLE_PER_THREAD_LOCALE))
#endif
#endif
{
#ifndef HAVE_XLOCALE_H
  const char* aPrevLocale = (const char* )myPrevLocale;
  if (aPrevLocale[0] == 'C' && aPrevLocale[1] == '\0')
  {
    myPrevLocale = NULL; // already C locale
    return;
  }
  // copy string as following setlocale calls may invalidate returned pointer
  Standard_Size aLen = std::strlen (aPrevLocale) + 1;
  myPrevLocale = new char[aLen];
  memcpy (myPrevLocale, aPrevLocale, aLen);

  setlocale (LC_ALL, "C");
#endif
}

// =======================================================================
// function : ~Standard_CLocaleSentry
// purpose  :
// =======================================================================
Standard_CLocaleSentry::~Standard_CLocaleSentry()
{
#ifdef HAVE_XLOCALE_H
  uselocale ((locale_t )myPrevLocale);
#else
  if (myPrevLocale != NULL)
  {
    const char* aPrevLocale = (const char* )myPrevLocale;
    setlocale (LC_ALL, aPrevLocale);
    delete[] aPrevLocale;
  }
#if defined(_MSC_VER) && (_MSC_VER > 1400)
  if (myPrevTLocaleState != _ENABLE_PER_THREAD_LOCALE)
  {
    _configthreadlocale (myPrevTLocaleState);
  }
#endif
#endif
}
<commit_msg>mem.h header needed for memcpy under bcc.<commit_after>// Created on: 2013-01-17
// Created by: Kirill GAVRILOV
// Copyright (c) 2013 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.

#ifdef HAVE_CONFIG_H
  #include <oce-config.h>
#endif

#include <Standard_CLocaleSentry.hxx>

#include <Standard_TypeDef.hxx>

#include <cstring>

#if defined(__BORLANDC__)
#include <mem.h>
#endif

namespace
{

  //! CLocalePtr - static object representing C locale
  class CLocalePtr
  {
  public:

    CLocalePtr()
    #ifdef HAVE_XLOCALE_H
    : myLocale (newlocale (LC_ALL_MASK, "C", NULL))
    #elif defined(_WIN32) && !defined(__BORLANDC__)
    : myLocale (_create_locale (LC_ALL, "C"))
    #else
    : myLocale (NULL)
    #endif
    {}

    ~CLocalePtr()
    {
    #ifdef HAVE_XLOCALE_H
      freelocale (myLocale);
    #elif defined(_WIN32) && !defined(__BORLANDC__)
      _free_locale (myLocale);
    #endif
    }

  public:

    Standard_CLocaleSentry::clocale_t myLocale;

  };

  static CLocalePtr theCLocale;

};

// =======================================================================
// function : GetCLocale
// purpose  :
// =======================================================================
Standard_CLocaleSentry::clocale_t Standard_CLocaleSentry::GetCLocale()
{
  return theCLocale.myLocale;
}

// =======================================================================
// function : Standard_CLocaleSentry
// purpose  :
// =======================================================================
Standard_CLocaleSentry::Standard_CLocaleSentry()
#ifdef HAVE_XLOCALE_H
: myPrevLocale (uselocale (theCLocale.myLocale)) // switch to C locale within this thread only using xlocale API
#else
: myPrevLocale (setlocale (LC_ALL, 0))
#if defined(_MSC_VER) && (_MSC_VER > 1400)
, myPrevTLocaleState (_configthreadlocale (_ENABLE_PER_THREAD_LOCALE))
#endif
#endif
{
#ifndef HAVE_XLOCALE_H
  const char* aPrevLocale = (const char* )myPrevLocale;
  if (aPrevLocale[0] == 'C' && aPrevLocale[1] == '\0')
  {
    myPrevLocale = NULL; // already C locale
    return;
  }
  // copy string as following setlocale calls may invalidate returned pointer
  Standard_Size aLen = std::strlen (aPrevLocale) + 1;
  myPrevLocale = new char[aLen];
  memcpy (myPrevLocale, aPrevLocale, aLen);

  setlocale (LC_ALL, "C");
#endif
}

// =======================================================================
// function : ~Standard_CLocaleSentry
// purpose  :
// =======================================================================
Standard_CLocaleSentry::~Standard_CLocaleSentry()
{
#ifdef HAVE_XLOCALE_H
  uselocale ((locale_t )myPrevLocale);
#else
  if (myPrevLocale != NULL)
  {
    const char* aPrevLocale = (const char* )myPrevLocale;
    setlocale (LC_ALL, aPrevLocale);
    delete[] aPrevLocale;
  }
#if defined(_MSC_VER) && (_MSC_VER > 1400)
  if (myPrevTLocaleState != _ENABLE_PER_THREAD_LOCALE)
  {
    _configthreadlocale (myPrevTLocaleState);
  }
#endif
#endif
}
<|endoftext|>


<commit_before>
#pragma once

#include <iostream>
#include <stdio.h>
#include <unistd.h>

#define TRACE_SPAM  0
#define TRACE_DEBUG 1
#define TRACE_INFO  2
#define TRACE_WARN  3
#define TRACE_ERROR 4
#define TRACE_CRIT  5

#define TRACE_GENERAL 1
#define TRACE_VM      2
#define TRACE_GC      4

#ifndef TRACE_LEVEL
#define TRACE_LEVEL 4
#endif

#ifndef TRACE_SUB
#define TRACE_SUB ((1<<30)-1) //subscribe to everything by default
#endif

#define tprintf(...) fprintf(stderr, __VA_ARGS__)
#define ctrace std::cerr

inline void trace_out_header(int facility, int level, const char * file, int line){
	static const char
//		*black     = "\033[30m",
		*red       = "\033[31m",
		*green     = "\033[32m",
		*yellow    = "\033[33m",
		*blue      = "\033[34m",
//		*purple    = "\033[35m",
		*cyan      = "\033[36m",
		*white     = "\033[37m",
//		*bold      = "\033[1m",
//		*underline = "\033[4m",
		*reset     = "\033[0m";

	static const char * levelcolor[] = { white, white, green, yellow, red, red };

	static bool color = isatty(2); //stderr

	if(color) ctrace << cyan;
	switch(facility){
		case TRACE_GENERAL: ctrace << "general";   break;
		case TRACE_VM:      ctrace << "vm";        break;
		case TRACE_GC:      ctrace << "gc";        break;
		default: ctrace << "unknown " << facility; break;
	}
	if(color) ctrace << reset;

	ctrace << ".";

	if(color) ctrace << levelcolor[level];
	switch(level){
		case TRACE_SPAM:  ctrace << "spam";     break;
		case TRACE_DEBUG: ctrace << "debug";    break;
		case TRACE_INFO:  ctrace << "info";     break;
		case TRACE_WARN:  ctrace << "warn";     break;
		case TRACE_ERROR: ctrace << "error";    break;
		case TRACE_CRIT:  ctrace << "critical"; break;
		default:          ctrace << "unknown";  break;
	}

	if(color) ctrace << blue;
	ctrace << " " << file << ":" << line << ": "; \
	if(color) ctrace << reset;
}

#define TRACE_OUT(facility, level) \
	if(((TRACE_SUB) & (facility)) && (TRACE_LEVEL) <= (level)){ \
		trace_out_header(facility, level, __FILE__, __LINE__); \
	} \
	if(((TRACE_SUB) & (facility)) && (TRACE_LEVEL) <= (level))

#define TRACE_CERR(facility, level, str) \
	TRACE_OUT(facility, level) ctrace

#define TRACE_PRINTF(facility, level, ...) \
	TRACE_OUT(facility, level) tprintf(__VA_ARGS__)

<commit_msg>Make it so you can 'do' trace things without the header output.<commit_after>
#pragma once

#include <iostream>
#include <stdio.h>
#include <unistd.h>

#define TRACE_SPAM  0
#define TRACE_DEBUG 1
#define TRACE_INFO  2
#define TRACE_WARN  3
#define TRACE_ERROR 4
#define TRACE_CRIT  5

#define TRACE_GENERAL 1
#define TRACE_VM      2
#define TRACE_GC      4

#ifndef TRACE_LEVEL
#define TRACE_LEVEL 4
#endif

#ifndef TRACE_SUB
#define TRACE_SUB ((1<<30)-1) //subscribe to everything by default
#endif

#define tprintf(...) fprintf(stderr, __VA_ARGS__)
#define ctrace std::cerr

inline void trace_out_header(int facility, int level, const char * file, int line){
	static const char
//		*black     = "\033[30m",
		*red       = "\033[31m",
		*green     = "\033[32m",
		*yellow    = "\033[33m",
		*blue      = "\033[34m",
//		*purple    = "\033[35m",
		*cyan      = "\033[36m",
		*white     = "\033[37m",
//		*bold      = "\033[1m",
//		*underline = "\033[4m",
		*reset     = "\033[0m";

	static const char * levelcolor[] = { white, white, green, yellow, red, red };

	static bool color = isatty(2); //stderr

	if(color) ctrace << cyan;
	switch(facility){
		case TRACE_GENERAL: ctrace << "general";   break;
		case TRACE_VM:      ctrace << "vm";        break;
		case TRACE_GC:      ctrace << "gc";        break;
		default: ctrace << "unknown " << facility; break;
	}
	if(color) ctrace << reset;

	ctrace << ".";

	if(color) ctrace << levelcolor[level];
	switch(level){
		case TRACE_SPAM:  ctrace << "spam";     break;
		case TRACE_DEBUG: ctrace << "debug";    break;
		case TRACE_INFO:  ctrace << "info";     break;
		case TRACE_WARN:  ctrace << "warn";     break;
		case TRACE_ERROR: ctrace << "error";    break;
		case TRACE_CRIT:  ctrace << "critical"; break;
		default:          ctrace << "unknown";  break;
	}

	if(color) ctrace << blue;
	ctrace << " " << file << ":" << line << ": "; \
	if(color) ctrace << reset;
}

#define TRACE_DO(facility, level) \
	if(((TRACE_SUB) & (facility)) && (TRACE_LEVEL) <= (level))

#define TRACE_OUT(facility, level) \
	TRACE_DO(facility, level) \
		trace_out_header(facility, level, __FILE__, __LINE__); \
	TRACE_DO(facility, level)

#define TRACE_CERR(facility, level, str) \
	TRACE_OUT(facility, level) ctrace

#define TRACE_PRINTF(facility, level, ...) \
	TRACE_OUT(facility, level) tprintf(__VA_ARGS__)

<|endoftext|>


<commit_before>/*
    open source routing machine
    Copyright (C) Dennis Luxen, others 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

#include "typedefs.h"
#include "Extractor/ExtractorCallbacks.h"
#include "Extractor/ExtractionContainers.h"
#include "Extractor/ScriptingEnvironment.h"
#include "Extractor/PBFParser.h"
#include "Extractor/XMLParser.h"
#include "Util/BaseConfiguration.h"
#include "Util/InputFileUtil.h"
#include "Util/MachineInfo.h"
#include "Util/StringUtil.h"

typedef BaseConfiguration ExtractorConfiguration;

ExtractorCallbacks * extractCallBacks;

int main (int argc, char *argv[]) {
    if(argc < 2) {
        ERR("usage: \n" << argv[0] << " <file.osm/.osm.bz2/.osm.pbf> [<profile.lua>]");
    }

    /*** Setup Scripting Environment ***/
    ScriptingEnvironment scriptingEnvironment((argc > 2 ? argv[2] : "profile.lua"));

    unsigned numberOfThreads = omp_get_num_procs();
    if(testDataFile("extractor.ini")) {
        ExtractorConfiguration extractorConfig("extractor.ini");
        unsigned rawNumber = stringToInt(extractorConfig.GetParameter("Threads"));
        if( rawNumber != 0 && rawNumber <= numberOfThreads)
            numberOfThreads = rawNumber;
    }
    omp_set_num_threads(numberOfThreads);

    INFO("extracting data from input file " << argv[1]);
    bool isPBF(false);
    std::string outputFileName(argv[1]);
    std::string restrictionsFileName(argv[1]);
    std::string::size_type pos = outputFileName.find(".osm.bz2");
    if(pos==std::string::npos) {
        pos = outputFileName.find(".osm.pbf");
        if(pos!=std::string::npos) {
            isPBF = true;
        }
    }
    if(pos!=std::string::npos) {
        outputFileName.replace(pos, 8, ".osrm");
        restrictionsFileName.replace(pos, 8, ".osrm.restrictions");
    } else {
        pos=outputFileName.find(".osm");
        if(pos!=std::string::npos) {
            outputFileName.replace(pos, 5, ".osrm");
            restrictionsFileName.replace(pos, 5, ".osrm.restrictions");
        } else {
            outputFileName.append(".osrm");
            restrictionsFileName.append(".osrm.restrictions");
        }
    }

    unsigned amountOfRAM = 1;
    unsigned installedRAM = GetPhysicalmemory();
    if(installedRAM < 2048264) {
        WARN("Machine has less than 2GB RAM.");
    }

    StringMap stringMap;
    ExtractionContainers externalMemory;

    stringMap[""] = 0;
    extractCallBacks = new ExtractorCallbacks(&externalMemory, &stringMap);
    BaseParser<ExtractorCallbacks, _Node, _RawRestrictionContainer, _Way> * parser;
    if(isPBF) {
        parser = new PBFParser(argv[1]);
    } else {
        parser = new XMLParser(argv[1]);
    }
    parser->RegisterCallbacks(extractCallBacks);
    parser->RegisterScriptingEnvironment(scriptingEnvironment);

    if(!parser->Init())
        ERR("Parser not initialized!");
    double time = get_timestamp();
    parser->Parse();
    INFO("parsing finished after " << get_timestamp() - time << " seconds");

    externalMemory.PrepareData(outputFileName, restrictionsFileName, amountOfRAM);

    stringMap.clear();
    delete parser;
    delete extractCallBacks;
    INFO("finished");
    std::cout << "\nRun:\n"
                   "./osrm-prepare " << outputFileName << " " << restrictionsFileName << std::endl;
    return 0;
}
<commit_msg>show total running time when extracting<commit_after>/*
    open source routing machine
    Copyright (C) Dennis Luxen, others 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

#include "typedefs.h"
#include "Extractor/ExtractorCallbacks.h"
#include "Extractor/ExtractionContainers.h"
#include "Extractor/ScriptingEnvironment.h"
#include "Extractor/PBFParser.h"
#include "Extractor/XMLParser.h"
#include "Util/BaseConfiguration.h"
#include "Util/InputFileUtil.h"
#include "Util/MachineInfo.h"
#include "Util/StringUtil.h"

typedef BaseConfiguration ExtractorConfiguration;

ExtractorCallbacks * extractCallBacks;

int main (int argc, char *argv[]) {
    double earliestTime = get_timestamp();

    if(argc < 2) {
        ERR("usage: \n" << argv[0] << " <file.osm/.osm.bz2/.osm.pbf> [<profile.lua>]");
    }

    /*** Setup Scripting Environment ***/
    ScriptingEnvironment scriptingEnvironment((argc > 2 ? argv[2] : "profile.lua"));

    unsigned numberOfThreads = omp_get_num_procs();
    if(testDataFile("extractor.ini")) {
        ExtractorConfiguration extractorConfig("extractor.ini");
        unsigned rawNumber = stringToInt(extractorConfig.GetParameter("Threads"));
        if( rawNumber != 0 && rawNumber <= numberOfThreads)
            numberOfThreads = rawNumber;
    }
    omp_set_num_threads(numberOfThreads);

    INFO("extracting data from input file " << argv[1]);
    bool isPBF(false);
    std::string outputFileName(argv[1]);
    std::string restrictionsFileName(argv[1]);
    std::string::size_type pos = outputFileName.find(".osm.bz2");
    if(pos==std::string::npos) {
        pos = outputFileName.find(".osm.pbf");
        if(pos!=std::string::npos) {
            isPBF = true;
        }
    }
    if(pos!=std::string::npos) {
        outputFileName.replace(pos, 8, ".osrm");
        restrictionsFileName.replace(pos, 8, ".osrm.restrictions");
    } else {
        pos=outputFileName.find(".osm");
        if(pos!=std::string::npos) {
            outputFileName.replace(pos, 5, ".osrm");
            restrictionsFileName.replace(pos, 5, ".osrm.restrictions");
        } else {
            outputFileName.append(".osrm");
            restrictionsFileName.append(".osrm.restrictions");
        }
    }

    unsigned amountOfRAM = 1;
    unsigned installedRAM = GetPhysicalmemory();
    if(installedRAM < 2048264) {
        WARN("Machine has less than 2GB RAM.");
    }

    StringMap stringMap;
    ExtractionContainers externalMemory;

    stringMap[""] = 0;
    extractCallBacks = new ExtractorCallbacks(&externalMemory, &stringMap);
    BaseParser<ExtractorCallbacks, _Node, _RawRestrictionContainer, _Way> * parser;
    if(isPBF) {
        parser = new PBFParser(argv[1]);
    } else {
        parser = new XMLParser(argv[1]);
    }
    parser->RegisterCallbacks(extractCallBacks);
    parser->RegisterScriptingEnvironment(scriptingEnvironment);

    if(!parser->Init())
        ERR("Parser not initialized!");
    double time = get_timestamp();
    parser->Parse();
    INFO("parsing finished after " << get_timestamp() - time << " seconds");

    externalMemory.PrepareData(outputFileName, restrictionsFileName, amountOfRAM);

    stringMap.clear();
    delete parser;
    delete extractCallBacks;
    INFO("finished after " << get_timestamp() - earliestTime << "s");

    std::cout << "\nRun:\n"
                   "./osrm-prepare " << outputFileName << " " << restrictionsFileName << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include "ParticleSystem.h"

bool comparisonFunction(Particle * a, Particle * b) {
    return a->pos.x < b->pos.x;
}

ParticleSystem::ParticleSystem(){
    isActive        = true;         // Particle system is active?

    bornRate        = 0;            // Number of particles born per frame
    velocity        = 0;            // Initial velocity magnitude of newborn particles
    velocityRnd     = 0;            // Magnitude randomness % of the initial velocity
    velocityMotion  = 0;            // Marker motion contribution to the initial velocity
    emitterSize     = 1.0f;         // Size of the emitter area
    lifetime        = 5;            // Lifetime of particles
    lifetimeRnd     = 0;            // Randomness of lifetime
    color           = ofColor(255); // Color of the particles
    radius          = 3;            // Radius of the particles
    radiusRnd       = 0;            // Randomness of radius

    immortal        = false;        // Can particles die?
    sizeAge         = false;        // Decrease size when particles get older?
    opacityAge      = false;        // Decrease opacity when particles get older?
    flickersAge     = false;        // Particle flickers opacity when about to die?
    colorAge        = false;        // Change color when particles get older?
    isEmpty         = false;        // Draw only contours of the particles?
    drawLine        = false;        // Draw a line instead of a circle for the particle?
    bounce          = false;        // Bounce particles with the walls of the window?

    friction        = 20;           // Friction to velocity 0~100
    gravity         = 0.0f;         // Makes particles fall down in a natural way
}

ParticleSystem::~ParticleSystem(){
    for (int i = 0; i < particles.size(); i++) {
        delete particles.at(i);
        particles.at(i) = NULL;
    }
    particles.clear();
}

void ParticleSystem::setup(ParticleMode particleMode, InputSource inputSource, int width , int height){

    this->particleMode = particleMode;
    this->inputSource = inputSource;
    this->width = width;
    this->height = height;

    if(particleMode == GRID){
        immortal = true;
        gridRes = 10;
        createParticleGrid(width, height);
    }

    else if(particleMode == RANDOM){
        immortal = true;
        nParticles = 1500;
        addParticles(nParticles);
    }

    else if(particleMode == BOIDS){ // TODO: BOIDS == RANDOM?
        nParticles = 500;
        addParticles(nParticles);
    }
}

void ParticleSystem::update(float dt, vector<irMarker> &markers, Contour& contour){
    if(isActive){
        // sort particles so it is more effective to do particle/particle interactions
        sort(particles.begin(), particles.end(), comparisonFunction);

        // ---------- (1) Delete inactive particles
        int i = 0;
        while (i < particles.size()){
            if (!particles[i]->isAlive){
                delete particles.at(i);
                particles.erase(particles.begin() + i);
                numParticles--;
            }
            else{
                i++;
            }
        }

        // TODO: not do the calculations depending on particle creation mode but on which interactions we want
        // being able to combine flocking with emitter?

        // ---------- (2) Calculate specific particle system behavior
        if(particleMode == GRID){
            float scale = 5;
            for(int i = 0; i < particles.size(); i++){
                if(inputSource == MARKERS){
                    float markerRadius = 50;
                    // Get closest marker to particle
                    ofPoint closestMarker = getClosestMarker(*particles[i], markers, markerRadius);
//                    dir = closestMarker - particles[i]->pos;
//                    dir.normalize();

                    if(closestMarker != ofPoint(-1, -1)){
                        particles[i]->addRepulsionForce(closestMarker.x, closestMarker.y, markerRadius*markerRadius, scale);
//                      ofPoint gravityForce(0, gravity*particles[i]->mass);
//                      particles[i]->addForce(gravityForce);
//                      particles[i]->isTouched = true;
                    }
                }
                particles[i]->xenoToOrigin(0.03);
            }
        }

        else if(particleMode == BOIDS){
            flockParticles();
            for(int i = 0; i < particles.size(); i++){
                particles[i]->addFlockingForces();
            }
        }

        else if(particleMode == EMITTER){

            // Born new particles
            if(inputSource == MARKERS){
                for(unsigned int i = 0; i < markers.size(); i++){
                    if (markers[i].hasDisappeared) markers[i].bornRate -= 0.5;
                    else markers[i].bornRate = bornRate;
                    addParticles(markers[i].bornRate, markers[i]);
                }
            }
            else if(inputSource == CONTOUR){
                for(unsigned int i = 0; i < contour.contours.size(); i++){
                    addParticles(bornRate, contour.contours[i]);
                }
            }
        }

//        if(repulseParticles) repulseParticles();

        // Update the particles
        for(int i = 0; i < particles.size(); i++){
            ofPoint gravityForce(0, gravity*particles[i]->mass/10);
            particles[i]->addForce(gravityForce);

//            particles[i]->addNoise(15.0, 0.5, dt);

//            ofPoint windForce(0.05, -0.02); // TODO: add some turbulence
//            ofPoint windForce(ofRandom(-0.1, 0.1), ofRandom(-0.08, 0.06)); // TODO: add some turbulence
//            particles[i]->addForce(windForce*particles[i]->mass);

            particles[i]->update(dt);
        }
    }
}

void ParticleSystem::draw(){
    if(isActive){
        for(int i = 0; i < particles.size(); i++){
            particles[i]->draw();
        }
    }
}

void ParticleSystem::addParticle(ofPoint pos, ofPoint vel, ofColor color, float radius, float lifetime){
    Particle * newParticle = new Particle();
    float id = totalParticlesCreated;

    newParticle->immortal       = immortal;
    newParticle->sizeAge        = sizeAge;
    newParticle->opacityAge     = opacityAge;
    newParticle->flickersAge    = flickersAge;
    newParticle->colorAge       = colorAge;
    newParticle->isEmpty        = isEmpty;
    newParticle->drawLine       = drawLine;
    newParticle->bounces        = bounce;
    newParticle->friction       = 1-friction/1000; // so we have a range between 0.90 and 1

    newParticle->width = width;
    newParticle->height = height;

    newParticle->setup(id, pos, vel, color, radius, lifetime);
    particles.push_back(newParticle);

    numParticles++;
    totalParticlesCreated++;
}

void ParticleSystem::addParticles(int n){
    for(int i = 0; i < n; i++){
        ofPoint pos = ofPoint(ofRandom(width), ofRandom(height));
        ofPoint vel = randomVector()*(velocity+randomRange(velocityRnd, velocity));

        float initialRadius = radius + randomRange(radiusRnd, radius);
        float lifetime = this->lifetime + randomRange(lifetimeRnd, this->lifetime);

        addParticle(pos, vel, color, initialRadius, lifetime);
    }
}

void ParticleSystem::addParticles(int n, const irMarker &marker){
    for(int i = 0; i < n; i++){
        ofPoint pos = marker.smoothPos + randomVector()*ofRandom(0, emitterSize);
        ofPoint vel = randomVector()*(velocity+randomRange(velocityRnd, velocity));
        vel += marker.velocity*(velocityMotion/100)*6;

        float initialRadius = radius + randomRange(radiusRnd, radius);
        float lifetime = this->lifetime + randomRange(lifetimeRnd, this->lifetime);

        addParticle(pos, vel, marker.color, initialRadius, lifetime);
    }
}

void ParticleSystem::addParticles(int n, const ofPolyline &contour){
    for(int i = 0; i < n; i++){
        // Create particles only inside contour polyline
        ofRectangle box = contour.getBoundingBox();
        ofPoint center = box.getCenter();
        ofPoint pos;
        pos.x = center.x + (ofRandom(1.0f) - 0.5f) * box.getWidth();
        pos.y = center.y + (ofRandom(1.0f) - 0.5f) * box.getHeight();

        while(!contour.inside(pos)){
            pos.x = center.x + (ofRandom(1.0f) - 0.5f) * box.getWidth();
            pos.y = center.y + (ofRandom(1.0f) - 0.5f) * box.getHeight();
        }

        ofPoint vel = randomVector()*(velocity+randomRange(velocityRnd, velocity));
//        vel += contour.velocity*(velocityMotion/100)*6;

        float initialRadius = radius + randomRange(radiusRnd, radius);
        float lifetime = this->lifetime + randomRange(lifetimeRnd, this->lifetime);

        addParticle(pos, vel, color, initialRadius, lifetime);
    }
}

void ParticleSystem::createParticleGrid(int width, int height){
    for(int y = 0; y < height/gridRes; y++){
        for(int x = 0; x < width/gridRes; x++){
            int xi = (x + 0.5f) * gridRes;
            int yi = (y + 0.5f) * gridRes;
//            float initialRadius = (float)gridRes / 2.0f;
//            float initialRadius = ofRandom(1.0f, 6.0f);
//            float initialRadius = cos(yi * 0.1f) + sin(xi * 0.1f) + 2.0f;
//            float initialRadius = (sin(yi * xi) + 1.0f) * 2.0f;
//            float xyOffset = sin( cos( sin( yi * 0.3183f ) + cos( xi * 0.3183f ) ) ) + 1.0f;
//            float initialRadius = xyOffset * xyOffset * 1.8f;
            ofPoint vel = ofPoint(0, 0);
            addParticle(ofPoint(xi, yi), vel, color, radius, lifetime);
        }
    }
}

void ParticleSystem::removeParticles(int n){
    for(int i = 0; i < n; i++){
        particles[i]->immortal = false;
        numParticles--;
    }
}

void ParticleSystem::killParticles(){
    // TODO: fadeOut when we desactivate the ps
    for(int i = 0; i < particles.size(); i++){
        particles[i]->immortal = false;
        numParticles--; // should be 0 at the end
    }
}

void ParticleSystem::bornParticles(){
    // Kill all the remaining particles before creating new ones
    for(int i = 0; i < particles.size(); i++){
        particles[i]->isAlive = false;
    }

    if(particleMode == RANDOM){
        immortal = true;
        nParticles = 1500;
        addParticles(nParticles);
    }
    else if(particleMode == GRID){
        immortal = true;
        createParticleGrid(width, height);
    }
}

void ParticleSystem::repulseParticles(){
    for(int i = 0; i < particles.size(); i++){
        for(int j = i-1; j >= 0; j--){
            if ( fabs(particles[j]->pos.x - particles[i]->pos.x) > radius*3) break; // to speed the loop
//            particles[i]->addRepulsionForce( *particles[j], radius, 1.0);
            particles[i]->addRepulsionForce( *particles[j], 1.0);
        }
    }
}

void ParticleSystem::flockParticles(){
    int flockRegionRadius = 100;
    for(int i = 0; i < particles.size(); i++){
        for(int j = i-1; j >= 0; j--){
            if ( fabs(particles[j]->pos.x - particles[i]->pos.x) > flockRegionRadius) break;
            particles[i]->addForFlocking(*particles[j]);
        }
    }
}

ofPoint ParticleSystem::randomVector(){
    float angle = ofRandom((float)M_PI * 2.0f);
    return ofPoint(cos(angle), sin(angle));
}

float ParticleSystem::randomRange(float percentage, float value){
    return ofRandom(-(percentage/100)*value, (percentage/100)*value);
}

ofPoint ParticleSystem::getClosestMarker(const Particle &particle, const vector<irMarker> &markers, float markerRadius){
    ofPoint closestMarker(-1, -1);
    float minDistSqrd = markerRadius*markerRadius;

    // Get closest marker to particle
    for(int markerIndex = 0; markerIndex < markers.size(); markerIndex++){
        if (!markers[markerIndex].hasDisappeared){
            float markerDistSqrd = particle.pos.squareDistance(markers[markerIndex].smoothPos);
            if(markerDistSqrd < minDistSqrd){
                minDistSqrd = markerDistSqrd;
                closestMarker = markers[markerIndex].smoothPos;
            }
        }
    }

    return closestMarker;
}
<commit_msg>Add simple comment direction vector to closest marker<commit_after>#include "ParticleSystem.h"

bool comparisonFunction(Particle * a, Particle * b) {
    return a->pos.x < b->pos.x;
}

ParticleSystem::ParticleSystem(){
    isActive        = true;         // Particle system is active?

    bornRate        = 0;            // Number of particles born per frame
    velocity        = 0;            // Initial velocity magnitude of newborn particles
    velocityRnd     = 0;            // Magnitude randomness % of the initial velocity
    velocityMotion  = 0;            // Marker motion contribution to the initial velocity
    emitterSize     = 1.0f;         // Size of the emitter area
    lifetime        = 5;            // Lifetime of particles
    lifetimeRnd     = 0;            // Randomness of lifetime
    color           = ofColor(255); // Color of the particles
    radius          = 3;            // Radius of the particles
    radiusRnd       = 0;            // Randomness of radius

    immortal        = false;        // Can particles die?
    sizeAge         = false;        // Decrease size when particles get older?
    opacityAge      = false;        // Decrease opacity when particles get older?
    flickersAge     = false;        // Particle flickers opacity when about to die?
    colorAge        = false;        // Change color when particles get older?
    isEmpty         = false;        // Draw only contours of the particles?
    drawLine        = false;        // Draw a line instead of a circle for the particle?
    bounce          = false;        // Bounce particles with the walls of the window?

    friction        = 20;           // Friction to velocity 0~100
    gravity         = 0.0f;         // Makes particles fall down in a natural way
}

ParticleSystem::~ParticleSystem(){
    for (int i = 0; i < particles.size(); i++) {
        delete particles.at(i);
        particles.at(i) = NULL;
    }
    particles.clear();
}

void ParticleSystem::setup(ParticleMode particleMode, InputSource inputSource, int width , int height){

    this->particleMode = particleMode;
    this->inputSource = inputSource;
    this->width = width;
    this->height = height;

    if(particleMode == GRID){
        immortal = true;
        gridRes = 10;
        createParticleGrid(width, height);
    }

    else if(particleMode == RANDOM){
        immortal = true;
        nParticles = 1500;
        addParticles(nParticles);
    }

    else if(particleMode == BOIDS){ // TODO: BOIDS == RANDOM?
        nParticles = 500;
        addParticles(nParticles);
    }
}

void ParticleSystem::update(float dt, vector<irMarker> &markers, Contour& contour){
    if(isActive){
        // sort particles so it is more effective to do particle/particle interactions
        sort(particles.begin(), particles.end(), comparisonFunction);

        // ---------- (1) Delete inactive particles
        int i = 0;
        while (i < particles.size()){
            if (!particles[i]->isAlive){
                delete particles.at(i);
                particles.erase(particles.begin() + i);
                numParticles--;
            }
            else{
                i++;
            }
        }

        // TODO: not do the calculations depending on particle creation mode but on which interactions we want
        // being able to combine flocking with emitter?

        // ---------- (2) Calculate specific particle system behavior
        if(particleMode == GRID){
            float scale = 5;
            for(int i = 0; i < particles.size(); i++){
                if(inputSource == MARKERS){
                    float markerRadius = 50;

                    // Get closest marker to particle
                    ofPoint closestMarker = getClosestMarker(*particles[i], markers, markerRadius);

                    // Get direction vector to closest marker
//                    dir = closestMarker - particles[i]->pos;
//                    dir.normalize();

                    if(closestMarker != ofPoint(-1, -1)){
                        particles[i]->addRepulsionForce(closestMarker.x, closestMarker.y, markerRadius*markerRadius, scale);
//                      ofPoint gravityForce(0, gravity*particles[i]->mass);
//                      particles[i]->addForce(gravityForce);
//                      particles[i]->isTouched = true;
                    }
                }
                particles[i]->xenoToOrigin(0.03);
            }
        }

        else if(particleMode == BOIDS){
            flockParticles();
            for(int i = 0; i < particles.size(); i++){
                particles[i]->addFlockingForces();
            }
        }

        else if(particleMode == EMITTER){

            // Born new particles
            if(inputSource == MARKERS){
                for(unsigned int i = 0; i < markers.size(); i++){
                    if (markers[i].hasDisappeared) markers[i].bornRate -= 0.5;
                    else markers[i].bornRate = bornRate;
                    addParticles(markers[i].bornRate, markers[i]);
                }
            }
            else if(inputSource == CONTOUR){
                for(unsigned int i = 0; i < contour.contours.size(); i++){
                    addParticles(bornRate, contour.contours[i]);
                }
            }
        }

//        if(repulseParticles) repulseParticles();

        // Update the particles
        for(int i = 0; i < particles.size(); i++){
            ofPoint gravityForce(0, gravity*particles[i]->mass/10);
            particles[i]->addForce(gravityForce);

//            particles[i]->addNoise(15.0, 0.5, dt);

//            ofPoint windForce(0.05, -0.02); // TODO: add some turbulence
//            ofPoint windForce(ofRandom(-0.1, 0.1), ofRandom(-0.08, 0.06)); // TODO: add some turbulence
//            particles[i]->addForce(windForce*particles[i]->mass);

            particles[i]->update(dt);
        }
    }
}

void ParticleSystem::draw(){
    if(isActive){
        for(int i = 0; i < particles.size(); i++){
            particles[i]->draw();
        }
    }
}

void ParticleSystem::addParticle(ofPoint pos, ofPoint vel, ofColor color, float radius, float lifetime){
    Particle * newParticle = new Particle();
    float id = totalParticlesCreated;

    newParticle->immortal       = immortal;
    newParticle->sizeAge        = sizeAge;
    newParticle->opacityAge     = opacityAge;
    newParticle->flickersAge    = flickersAge;
    newParticle->colorAge       = colorAge;
    newParticle->isEmpty        = isEmpty;
    newParticle->drawLine       = drawLine;
    newParticle->bounces        = bounce;
    newParticle->friction       = 1-friction/1000; // so we have a range between 0.90 and 1

    newParticle->width = width;
    newParticle->height = height;

    newParticle->setup(id, pos, vel, color, radius, lifetime);
    particles.push_back(newParticle);

    numParticles++;
    totalParticlesCreated++;
}

void ParticleSystem::addParticles(int n){
    for(int i = 0; i < n; i++){
        ofPoint pos = ofPoint(ofRandom(width), ofRandom(height));
        ofPoint vel = randomVector()*(velocity+randomRange(velocityRnd, velocity));

        float initialRadius = radius + randomRange(radiusRnd, radius);
        float lifetime = this->lifetime + randomRange(lifetimeRnd, this->lifetime);

        addParticle(pos, vel, color, initialRadius, lifetime);
    }
}

void ParticleSystem::addParticles(int n, const irMarker &marker){
    for(int i = 0; i < n; i++){
        ofPoint pos = marker.smoothPos + randomVector()*ofRandom(0, emitterSize);
        ofPoint vel = randomVector()*(velocity+randomRange(velocityRnd, velocity));
        vel += marker.velocity*(velocityMotion/100)*6;

        float initialRadius = radius + randomRange(radiusRnd, radius);
        float lifetime = this->lifetime + randomRange(lifetimeRnd, this->lifetime);

        addParticle(pos, vel, marker.color, initialRadius, lifetime);
    }
}

void ParticleSystem::addParticles(int n, const ofPolyline &contour){
    for(int i = 0; i < n; i++){
        // Create particles only inside contour polyline
        ofRectangle box = contour.getBoundingBox();
        ofPoint center = box.getCenter();
        ofPoint pos;
        pos.x = center.x + (ofRandom(1.0f) - 0.5f) * box.getWidth();
        pos.y = center.y + (ofRandom(1.0f) - 0.5f) * box.getHeight();

        while(!contour.inside(pos)){
            pos.x = center.x + (ofRandom(1.0f) - 0.5f) * box.getWidth();
            pos.y = center.y + (ofRandom(1.0f) - 0.5f) * box.getHeight();
        }

        ofPoint vel = randomVector()*(velocity+randomRange(velocityRnd, velocity));
//        vel += contour.velocity*(velocityMotion/100)*6;

        float initialRadius = radius + randomRange(radiusRnd, radius);
        float lifetime = this->lifetime + randomRange(lifetimeRnd, this->lifetime);

        addParticle(pos, vel, color, initialRadius, lifetime);
    }
}

void ParticleSystem::createParticleGrid(int width, int height){
    for(int y = 0; y < height/gridRes; y++){
        for(int x = 0; x < width/gridRes; x++){
            int xi = (x + 0.5f) * gridRes;
            int yi = (y + 0.5f) * gridRes;
//            float initialRadius = (float)gridRes / 2.0f;
//            float initialRadius = ofRandom(1.0f, 6.0f);
//            float initialRadius = cos(yi * 0.1f) + sin(xi * 0.1f) + 2.0f;
//            float initialRadius = (sin(yi * xi) + 1.0f) * 2.0f;
//            float xyOffset = sin( cos( sin( yi * 0.3183f ) + cos( xi * 0.3183f ) ) ) + 1.0f;
//            float initialRadius = xyOffset * xyOffset * 1.8f;
            ofPoint vel = ofPoint(0, 0);
            addParticle(ofPoint(xi, yi), vel, color, radius, lifetime);
        }
    }
}

void ParticleSystem::removeParticles(int n){
    for(int i = 0; i < n; i++){
        particles[i]->immortal = false;
        numParticles--;
    }
}

void ParticleSystem::killParticles(){
    // TODO: fadeOut when we desactivate the ps
    for(int i = 0; i < particles.size(); i++){
        particles[i]->immortal = false;
        numParticles--; // should be 0 at the end
    }
}

void ParticleSystem::bornParticles(){
    // Kill all the remaining particles before creating new ones
    for(int i = 0; i < particles.size(); i++){
        particles[i]->isAlive = false;
    }

    if(particleMode == RANDOM){
        immortal = true;
        nParticles = 1500;
        addParticles(nParticles);
    }
    else if(particleMode == GRID){
        immortal = true;
        createParticleGrid(width, height);
    }
}

void ParticleSystem::repulseParticles(){
    for(int i = 0; i < particles.size(); i++){
        for(int j = i-1; j >= 0; j--){
            if ( fabs(particles[j]->pos.x - particles[i]->pos.x) > radius*3) break; // to speed the loop
//            particles[i]->addRepulsionForce( *particles[j], radius, 1.0);
            particles[i]->addRepulsionForce( *particles[j], 1.0);
        }
    }
}

void ParticleSystem::flockParticles(){
    int flockRegionRadius = 100;
    for(int i = 0; i < particles.size(); i++){
        for(int j = i-1; j >= 0; j--){
            if ( fabs(particles[j]->pos.x - particles[i]->pos.x) > flockRegionRadius) break;
            particles[i]->addForFlocking(*particles[j]);
        }
    }
}

ofPoint ParticleSystem::randomVector(){
    float angle = ofRandom((float)M_PI * 2.0f);
    return ofPoint(cos(angle), sin(angle));
}

float ParticleSystem::randomRange(float percentage, float value){
    return ofRandom(-(percentage/100)*value, (percentage/100)*value);
}

ofPoint ParticleSystem::getClosestMarker(const Particle &particle, const vector<irMarker> &markers, float markerRadius){
    ofPoint closestMarker(-1, -1);
    float minDistSqrd = markerRadius*markerRadius;

    // Get closest marker to particle
    for(int markerIndex = 0; markerIndex < markers.size(); markerIndex++){
        if (!markers[markerIndex].hasDisappeared){
            float markerDistSqrd = particle.pos.squareDistance(markers[markerIndex].smoothPos);
            if(markerDistSqrd < minDistSqrd){
                minDistSqrd = markerDistSqrd;
                closestMarker = markers[markerIndex].smoothPos;
            }
        }
    }

    return closestMarker;
}
<|endoftext|>


<commit_before>// Copyright 2013 Google Inc. All Rights Reserved.
//
// 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 "version.h"

#include <stdlib.h>

#include "util.h"

const char* kNinjaVersion = "1.8.2.git";

void ParseVersion(const string& version, int* major, int* minor) {
  size_t end = version.find('.');
  *major = atoi(version.substr(0, end).c_str());
  *minor = 0;
  if (end != string::npos) {
    size_t start = end + 1;
    end = version.find('.', start);
    *minor = atoi(version.substr(start, end).c_str());
  }
}

void CheckNinjaVersion(const string& version) {
  int bin_major, bin_minor;
  ParseVersion(kNinjaVersion, &bin_major, &bin_minor);
  int file_major, file_minor;
  ParseVersion(version, &file_major, &file_minor);

  if (bin_major > file_major) {
    Warning("ninja executable version (%s) greater than build file "
            "ninja_required_version (%s); versions may be incompatible.",
            kNinjaVersion, version.c_str());
    return;
  }

  if ((bin_major == file_major && bin_minor < file_minor) ||
      bin_major < file_major) {
    Fatal("ninja version (%s) incompatible with build file "
          "ninja_required_version version (%s).",
          kNinjaVersion, version.c_str());
  }
}
<commit_msg>mark this 1.9.0.git<commit_after>// Copyright 2013 Google Inc. All Rights Reserved.
//
// 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 "version.h"

#include <stdlib.h>

#include "util.h"

const char* kNinjaVersion = "1.9.0.git";

void ParseVersion(const string& version, int* major, int* minor) {
  size_t end = version.find('.');
  *major = atoi(version.substr(0, end).c_str());
  *minor = 0;
  if (end != string::npos) {
    size_t start = end + 1;
    end = version.find('.', start);
    *minor = atoi(version.substr(start, end).c_str());
  }
}

void CheckNinjaVersion(const string& version) {
  int bin_major, bin_minor;
  ParseVersion(kNinjaVersion, &bin_major, &bin_minor);
  int file_major, file_minor;
  ParseVersion(version, &file_major, &file_minor);

  if (bin_major > file_major) {
    Warning("ninja executable version (%s) greater than build file "
            "ninja_required_version (%s); versions may be incompatible.",
            kNinjaVersion, version.c_str());
    return;
  }

  if ((bin_major == file_major && bin_minor < file_minor) ||
      bin_major < file_major) {
    Fatal("ninja version (%s) incompatible with build file "
          "ninja_required_version version (%s).",
          kNinjaVersion, version.c_str());
  }
}
<|endoftext|>


<commit_before>// Copyright 2012 the V8 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.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      67
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<commit_msg>[Auto-roll] Bump up version to 3.29.68.0<commit_after>// Copyright 2012 the V8 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.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      68
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>
#include "viewer.h"

nanogui::Screen *screen = nullptr;

void Viewer::init() {

  using namespace nanogui;

  glfwInit();
  glfwSetTime(0);

  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

  glfwWindowHint(GLFW_SAMPLES, 0);
  glfwWindowHint(GLFW_RED_BITS, 8);
  glfwWindowHint(GLFW_GREEN_BITS, 8);
  glfwWindowHint(GLFW_BLUE_BITS, 8);
  glfwWindowHint(GLFW_ALPHA_BITS, 8);
  glfwWindowHint(GLFW_STENCIL_BITS, 8);
  glfwWindowHint(GLFW_DEPTH_BITS, 24);
  glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);

  window = glfwCreateWindow(800, 800, "CAD app", nullptr, nullptr);
  glfwMakeContextCurrent(window);

  int width, height;
  glfwGetFramebufferSize(window, &width, &height);
  glViewport(0, 0, width, height);
  glfwSwapInterval(0);
  glfwSwapBuffers(window);

  int windowWidth, windowHeight;
  glfwGetWindowSize(window, &windowWidth, &windowHeight);

  screen = new Screen();
  screen->initialize(window, true);

  FormHelper *gui = new FormHelper(screen);
  nanogui::ref<Window> guiWindow = gui->addWindow(Eigen::Vector2i(10, 10), "Form helper example");
  gui->addGroup("Workspace");
  gui->addButton("Load", []() { std::cout << "Button pressed." << std::endl; });
    /*this->load(); });*/
  // gui->addButton("Save", [&]() { this->save(); });

  screen->setVisible(true);
  screen->performLayout();

}
void Viewer::load() {
  igl::readOBJ("../bunny.obj", vertices, vertexUvs, cornerNormals, faces, faceUvs, faceNormalIndices);
  mesh.set(vertices, faces);

  // this->mesh.setUv(vertexUvs, faceUvs);

  // core.align_camera_center(data.V,data.F);

}

void Viewer::save() {
  std::cout << "save" << std::endl;
}

void Viewer::launch() {
  init();
  setCallbacks();

  opengl.init();

  while (!glfwWindowShouldClose(window)) {

    glfwPollEvents();
    glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    float ratio;
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    ratio = width / (float) height;
    glViewport(0, 0, width, height);

    opengl.setMesh(mesh);
    opengl.bindMesh();

    Eigen::Matrix4f modelMatrix = Eigen::Matrix4f::Identity();
    Eigen::Matrix4f viewMatrix  = Eigen::Matrix4f::Identity();
    Eigen::Matrix4f projMatrix  = Eigen::Matrix4f::Identity();

    GLint model = opengl.shaderMesh.uniform("model");
    GLint view = opengl.shaderMesh.uniform("view");
    GLint proj = opengl.shaderMesh.uniform("proj");

    glUniformMatrix4fv(model, 1, GL_FALSE, modelMatrix.data());
    glUniformMatrix4fv(view, 1, GL_FALSE, viewMatrix.data());
    glUniformMatrix4fv(proj, 1, GL_FALSE, projMatrix.data());

    GLint specularExponent = opengl.shaderMesh.uniform("specular_exponent");
    GLint lightPositionWorld = opengl.shaderMesh.uniform("light_position_world");
    GLint lightingFactor = opengl.shaderMesh.uniform("lighting_factor");
    GLint fixedColor = opengl.shaderMesh.uniform("fixed_color");
    GLint textureFactor = opengl.shaderMesh.uniform("texture_factor");

    glUniform1f(textureFactor, 1.0f);
    opengl.drawMesh();
    glUniform1f(textureFactor, 0.0f);

    screen->drawContents();
    screen->drawWidgets();

    glfwSwapBuffers(window);
  }

  glfwTerminate();
}

void Viewer::setCallbacks() {
  glfwSetCursorPosCallback(window,
    [](GLFWwindow *, double x, double y) {
      screen->cursorPosCallbackEvent(x, y);
    }
  );

  glfwSetMouseButtonCallback(window,
    [](GLFWwindow *, int button, int action, int modifiers) {
      screen->mouseButtonCallbackEvent(button, action, modifiers);
    }
  );

  glfwSetKeyCallback(window,
    [](GLFWwindow *, int key, int scancode, int action, int mods) {
      screen->keyCallbackEvent(key, scancode, action, mods);
    }
  );

  glfwSetCharCallback(window,
    [](GLFWwindow *, unsigned int codepoint) {
      screen->charCallbackEvent(codepoint);
    }
  );

  glfwSetDropCallback(window,
    [](GLFWwindow *, int count, const char **filenames) {
      screen->dropCallbackEvent(count, filenames);
    }
  );

  glfwSetScrollCallback(window,
    [](GLFWwindow *, double x, double y) {
      screen->scrollCallbackEvent(x, y);
    }
  );

  glfwSetFramebufferSizeCallback(window,
    [](GLFWwindow *, int width, int height) {
      screen->resizeCallbackEvent(width, height);
    }
  );

}

<commit_msg>Load OBJ file from finder<commit_after>
#include "viewer.h"

nanogui::Screen *screen = nullptr;

void Viewer::init() {

  using namespace nanogui;

  glfwInit();
  glfwSetTime(0);

  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

  glfwWindowHint(GLFW_SAMPLES, 0);
  glfwWindowHint(GLFW_RED_BITS, 8);
  glfwWindowHint(GLFW_GREEN_BITS, 8);
  glfwWindowHint(GLFW_BLUE_BITS, 8);
  glfwWindowHint(GLFW_ALPHA_BITS, 8);
  glfwWindowHint(GLFW_STENCIL_BITS, 8);
  glfwWindowHint(GLFW_DEPTH_BITS, 24);
  glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);

  window = glfwCreateWindow(800, 800, "CAD app", nullptr, nullptr);
  glfwMakeContextCurrent(window);

  int width, height;
  glfwGetFramebufferSize(window, &width, &height);
  glViewport(0, 0, width, height);
  glfwSwapInterval(0);
  glfwSwapBuffers(window);

  int windowWidth, windowHeight;
  glfwGetWindowSize(window, &windowWidth, &windowHeight);

  screen = new Screen();
  screen->initialize(window, true);

  FormHelper *gui = new FormHelper(screen);
  nanogui::ref<Window> guiWindow = gui->addWindow(Eigen::Vector2i(10, 10), "Form helper example");
  gui->addGroup("Workspace");

  gui->addButton("Load", [&]() { this->load(); });
  // gui->addButton("Save", [&]() { this->save(); });

  screen->setVisible(true);
  screen->performLayout();

}
void Viewer::load() {
  std::string filename = nanogui::file_dialog({
    {"obj", "Wavefront OBJ"}
  }, false);
  std::cout << filename << std::endl;

  if (filename.empty()) {
    return;
  }

  igl::readOBJ(filename, vertices, vertexUvs, cornerNormals, faces, faceUvs, faceNormalIndices);
  mesh.set(vertices, faces);
  // this->mesh.setUv(vertexUvs, faceUvs);

  // core.align_camera_center(data.V,data.F);

}

void Viewer::save() {
  std::cout << "save" << std::endl;
}

void Viewer::launch() {
  init();
  setCallbacks();

  opengl.init();

  while (!glfwWindowShouldClose(window)) {

    glfwPollEvents();
    glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    float ratio;
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    ratio = width / (float) height;
    glViewport(0, 0, width, height);

    opengl.setMesh(mesh);
    opengl.bindMesh();

    Eigen::Matrix4f modelMatrix = Eigen::Matrix4f::Identity();
    Eigen::Matrix4f viewMatrix  = Eigen::Matrix4f::Identity();
    Eigen::Matrix4f projMatrix  = Eigen::Matrix4f::Identity();

    GLint model = opengl.shaderMesh.uniform("model");
    GLint view = opengl.shaderMesh.uniform("view");
    GLint proj = opengl.shaderMesh.uniform("proj");

    glUniformMatrix4fv(model, 1, GL_FALSE, modelMatrix.data());
    glUniformMatrix4fv(view, 1, GL_FALSE, viewMatrix.data());
    glUniformMatrix4fv(proj, 1, GL_FALSE, projMatrix.data());

    GLint specularExponent = opengl.shaderMesh.uniform("specular_exponent");
    GLint lightPositionWorld = opengl.shaderMesh.uniform("light_position_world");
    GLint lightingFactor = opengl.shaderMesh.uniform("lighting_factor");
    GLint fixedColor = opengl.shaderMesh.uniform("fixed_color");
    GLint textureFactor = opengl.shaderMesh.uniform("texture_factor");

    glUniform1f(textureFactor, 1.0f);
    opengl.drawMesh();
    glUniform1f(textureFactor, 0.0f);

    screen->drawContents();
    screen->drawWidgets();

    glfwSwapBuffers(window);
  }

  glfwTerminate();
}

void Viewer::setCallbacks() {
  glfwSetCursorPosCallback(window,
    [](GLFWwindow *, double x, double y) {
      screen->cursorPosCallbackEvent(x, y);
    }
  );

  glfwSetMouseButtonCallback(window,
    [](GLFWwindow *, int button, int action, int modifiers) {
      screen->mouseButtonCallbackEvent(button, action, modifiers);
    }
  );

  glfwSetKeyCallback(window,
    [](GLFWwindow *, int key, int scancode, int action, int mods) {
      screen->keyCallbackEvent(key, scancode, action, mods);
    }
  );

  glfwSetCharCallback(window,
    [](GLFWwindow *, unsigned int codepoint) {
      screen->charCallbackEvent(codepoint);
    }
  );

  glfwSetDropCallback(window,
    [](GLFWwindow *, int count, const char **filenames) {
      screen->dropCallbackEvent(count, filenames);
    }
  );

  glfwSetScrollCallback(window,
    [](GLFWwindow *, double x, double y) {
      screen->scrollCallbackEvent(x, y);
    }
  );

  glfwSetFramebufferSizeCallback(window,
    [](GLFWwindow *, int width, int height) {
      screen->resizeCallbackEvent(width, height);
    }
  );

}

<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This tool converts Hunspell .aff/.dic pairs to a combined binary dictionary
// format (.bdic). This format is more compact, and can be more efficiently
// read by the client application.
//
// We do this conversion manually before publishing dictionary files. It is not
// part of any build process.
//
// See PrintHelp() below for usage.

#include <stdio.h>

#include "base/at_exit.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "third_party/hunspell/google/bdict_reader.h"
#include "third_party/hunspell/google/bdict_writer.h"
#include "chrome/tools/convert_dict/aff_reader.h"
#include "chrome/tools/convert_dict/dic_reader.h"

namespace {

// Compares the given word list with the serialized trie to make sure they
// are the same.
bool VerifyWords(const convert_dict::DicReader::WordList& org_words,
                 const std::string& serialized) {
  hunspell::BDictReader reader;
  if (!reader.Init(reinterpret_cast<const unsigned char*>(serialized.data()),
                   serialized.size())) {
    printf("BDict is invalid\n");
    return false;
  }
  hunspell::WordIterator iter = reader.GetAllWordIterator();

  int affix_ids[hunspell::BDict::MAX_AFFIXES_PER_WORD];

  static const int buf_size = 128;
  char buf[buf_size];
  for (size_t i = 0; i < org_words.size(); i++) {
    int affix_matches = iter.Advance(buf, buf_size, affix_ids);
    if (affix_matches == 0) {
      printf("Found the end before we expected\n");
      return false;
    }

    if (org_words[i].first != buf) {
      printf("Word doesn't match, word #%s\n", buf);
      return false;
    }

    if (affix_matches != static_cast<int>(org_words[i].second.size())) {
      printf("Different number of affix indices, word #%s\n", buf);
      return false;
    }

    // Check the individual affix indices.
    for (size_t affix_index = 0; affix_index < org_words[i].second.size();
         affix_index++) {
      if (affix_ids[affix_index] != org_words[i].second[affix_index]) {
        printf("Index doesn't match, word #%s\n", buf);
        return false;
      }
    }
  }

  return true;
}

int PrintHelp() {
  printf("Usage: convert_dict <dicfile base name>\n\n");
  printf("Example:\n");
  printf("  convert_dict en-US\nwill read en-US.dic / en-US.aff and\n");
  printf("generate en-US.bdic\n\n");
  return 1;
}

}  // namespace

#if defined(OS_WIN)
int wmain(int argc, wchar_t* argv[]) {
#else
int main(int argc, char* argv[]) {
#endif
  base::EnableTerminationOnHeapCorruption();
  if (argc != 2)
    return PrintHelp();

  base::AtExitManager exit_manager;
  icu_util::Initialize();

  FilePath file_base = FilePath(argv[1]);

  FilePath aff_path = file_base.ReplaceExtension(FILE_PATH_LITERAL(".aff"));
  printf("Reading %" PRFilePath " ...\n", aff_path.value().c_str());
  convert_dict::AffReader aff_reader(aff_path);
  if (!aff_reader.Read()) {
    printf("Unable to read the aff file.\n");
    return 1;
  }

  FilePath dic_path = file_base.ReplaceExtension(FILE_PATH_LITERAL(".dic"));
  printf("Reading %" PRFilePath " ...\n", dic_path.value().c_str());
  convert_dict::DicReader dic_reader(dic_path);
  if (!dic_reader.Read(&aff_reader)) {
    printf("Unable to read the dic file.\n");
    return 1;
  }

  hunspell::BDictWriter writer;
  writer.SetComment(aff_reader.comments());
  writer.SetAffixRules(aff_reader.affix_rules());
  writer.SetAffixGroups(aff_reader.GetAffixGroups());
  writer.SetReplacements(aff_reader.replacements());
  writer.SetOtherCommands(aff_reader.other_commands());
  writer.SetWords(dic_reader.words());

  printf("Serializing...\n");
  std::string serialized = writer.GetBDict();

  printf("Verifying...\n");
  if (!VerifyWords(dic_reader.words(), serialized)) {
    printf("ERROR converting, the dictionary does not check out OK.");
    return 1;
  }

  FilePath out_path = file_base.ReplaceExtension(FILE_PATH_LITERAL(".bdic"));
  printf("Writing %" PRFilePath " ...\n", out_path.value().c_str());
  FILE* out_file = file_util::OpenFile(out_path, "wb");
  if (!out_file) {
    printf("ERROR writing file\n");
    return 1;
  }
  size_t written = fwrite(&serialized[0], 1, serialized.size(), out_file);
  CHECK(written == serialized.size());
  file_util::CloseFile(out_file);

  return 0;
}
<commit_msg>Slightly better docs for the convert_dict tool.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This tool converts Hunspell .aff/.dic pairs to a combined binary dictionary
// format (.bdic). This format is more compact, and can be more efficiently
// read by the client application.
//
// We do this conversion manually before publishing dictionary files. It is not
// part of any build process.
//
// See PrintHelp() below for usage.

#include <stdio.h>

#include "base/at_exit.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "third_party/hunspell/google/bdict_reader.h"
#include "third_party/hunspell/google/bdict_writer.h"
#include "chrome/tools/convert_dict/aff_reader.h"
#include "chrome/tools/convert_dict/dic_reader.h"

namespace {

// Compares the given word list with the serialized trie to make sure they
// are the same.
bool VerifyWords(const convert_dict::DicReader::WordList& org_words,
                 const std::string& serialized) {
  hunspell::BDictReader reader;
  if (!reader.Init(reinterpret_cast<const unsigned char*>(serialized.data()),
                   serialized.size())) {
    printf("BDict is invalid\n");
    return false;
  }
  hunspell::WordIterator iter = reader.GetAllWordIterator();

  int affix_ids[hunspell::BDict::MAX_AFFIXES_PER_WORD];

  static const int buf_size = 128;
  char buf[buf_size];
  for (size_t i = 0; i < org_words.size(); i++) {
    int affix_matches = iter.Advance(buf, buf_size, affix_ids);
    if (affix_matches == 0) {
      printf("Found the end before we expected\n");
      return false;
    }

    if (org_words[i].first != buf) {
      printf("Word doesn't match, word #%s\n", buf);
      return false;
    }

    if (affix_matches != static_cast<int>(org_words[i].second.size())) {
      printf("Different number of affix indices, word #%s\n", buf);
      return false;
    }

    // Check the individual affix indices.
    for (size_t affix_index = 0; affix_index < org_words[i].second.size();
         affix_index++) {
      if (affix_ids[affix_index] != org_words[i].second[affix_index]) {
        printf("Index doesn't match, word #%s\n", buf);
        return false;
      }
    }
  }

  return true;
}

int PrintHelp() {
  printf("Usage: convert_dict <dicfile base name>\n\n");
  printf("Example:\n");
  printf("  convert_dict en-US\nwill read en-US.dic, en-US.dic_delta, and "
         "en-US.aff from the current directory and generate en-US.bdic\n\n");
  return 1;
}

}  // namespace

#if defined(OS_WIN)
int wmain(int argc, wchar_t* argv[]) {
#else
int main(int argc, char* argv[]) {
#endif
  base::EnableTerminationOnHeapCorruption();
  if (argc != 2)
    return PrintHelp();

  base::AtExitManager exit_manager;
  icu_util::Initialize();

  FilePath file_base = FilePath(argv[1]);

  FilePath aff_path = file_base.ReplaceExtension(FILE_PATH_LITERAL(".aff"));
  printf("Reading %" PRFilePath " ...\n", aff_path.value().c_str());
  convert_dict::AffReader aff_reader(aff_path);
  if (!aff_reader.Read()) {
    printf("Unable to read the aff file.\n");
    return 1;
  }

  FilePath dic_path = file_base.ReplaceExtension(FILE_PATH_LITERAL(".dic"));
  printf("Reading %" PRFilePath " ...\n", dic_path.value().c_str());
  // DicReader will also read the .dic_delta file.
  convert_dict::DicReader dic_reader(dic_path);
  if (!dic_reader.Read(&aff_reader)) {
    printf("Unable to read the dic file.\n");
    return 1;
  }

  hunspell::BDictWriter writer;
  writer.SetComment(aff_reader.comments());
  writer.SetAffixRules(aff_reader.affix_rules());
  writer.SetAffixGroups(aff_reader.GetAffixGroups());
  writer.SetReplacements(aff_reader.replacements());
  writer.SetOtherCommands(aff_reader.other_commands());
  writer.SetWords(dic_reader.words());

  printf("Serializing...\n");
  std::string serialized = writer.GetBDict();

  printf("Verifying...\n");
  if (!VerifyWords(dic_reader.words(), serialized)) {
    printf("ERROR converting, the dictionary does not check out OK.");
    return 1;
  }

  FilePath out_path = file_base.ReplaceExtension(FILE_PATH_LITERAL(".bdic"));
  printf("Writing %" PRFilePath " ...\n", out_path.value().c_str());
  FILE* out_file = file_util::OpenFile(out_path, "wb");
  if (!out_file) {
    printf("ERROR writing file\n");
    return 1;
  }
  size_t written = fwrite(&serialized[0], 1, serialized.size(), out_file);
  CHECK(written == serialized.size());
  file_util::CloseFile(out_file);

  return 0;
}
<|endoftext|>


<commit_before>/*
 * QupZillaFormat.cpp
 * Copyright (c) 2015 Markus Himmel. All rights reserved.
 * Distributed under the terms of the MIT license.
 */

#include <fstream>
#include <iostream>

#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <Json.h>
#include <Path.h>

#include "BookmarksTree.h"
#include "BookmarksFormat.h"

QupZillaInput::QupZillaInput()
{
}

QupZillaInput::~QupZillaInput()
{
}

BookmarksEntry* QupZillaInput::Input(const char* source)
{
	BFile file(source, B_READ_ONLY);
	if (file.InitCheck() != B_OK)
		return NULL;

	off_t size;
	if (file.GetSize(&size) != B_OK)
		return NULL;

	char* buffer = new (std::nothrow) char[size];
	if (buffer == NULL)
		return NULL;

	if (file.Read(buffer, size) != size) {
		delete[] buffer;
		return NULL;
	}

	BString json(buffer);
	delete[] buffer;
	BMessage decoded;

	if (BJson::Parse(decoded, json) != B_OK)
		return NULL;

	BMessage roots;
	if (decoded.FindMessage("roots", &roots) != B_OK)
		return NULL;

	BookmarksFolder* top = new BookmarksFolder(), * child = NULL;

	BMessage folder;
	if (roots.FindMessage("bookmark_menu", &folder) == B_OK) {
		child = readDirectory(folder);
		if (child != NULL)
			top->push_back(child);
	}

	if (roots.FindMessage("bookmark_menu", &folder) == B_OK) {
		child = readDirectory(folder);
		if (child != NULL)
			top->push_back(child);
	}

	if (roots.FindMessage("other", &folder) == B_OK) {
		child = readDirectory(folder);
		if (child != NULL)
			top->push_back(child);
	}

	return top;
}

BookmarksFolder* QupZillaInput::readDirectory(BMessage& info)
{
	BMessage children;
	if (info.FindMessage("children", &children) != B_OK)
		return NULL;

	BookmarksFolder* thisDir = new BookmarksFolder();

	int currentIndex = 0;
	BMessage currentChild;
	while (children.FindMessage((BString() << currentIndex).String(),
		&currentChild) == B_OK) {
		currentIndex++;
		const char* type;
		if (currentChild.FindString("type", &type) != B_OK)
			continue;

		BString typeS(type);
		if (typeS == "url") {
			Bookmark* child = readItem(currentChild);
			if (child != NULL)
				thisDir->push_back(child);
		} else if (typeS == "folder") {
			BookmarksFolder* child = readDirectory(currentChild);
			if (child != NULL)
				thisDir->push_back(child);
		} else
			continue;
	}

	const char* name;
	if (info.FindString("name", &name) == B_OK)
		thisDir->SetName(name);
	else
		thisDir->SetName("Unknown");

	return thisDir;
}

Bookmark* QupZillaInput::readItem(BMessage& info)
{
	Bookmark* result = new Bookmark();

	const char* tmp;
	if (info.FindString("name", &tmp) == B_OK)
		result->SetTitle(tmp);
	else
		result->SetTitle("Unknown");

	if (info.FindString("url", &tmp) == B_OK)
		result->SetURL(tmp);
	else
		result->SetURL("Unknown");

	if (info.FindString("keyword", &tmp) == B_OK)
		result->SetKeywords(tmp);

	return result;
}

const int kBaseOffset = 3;

void QupZillaOutput::Output(BookmarksEntry* entry, const char* destination)
{
	BPath dir;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK) {
		BString path(dir.Path());
		path << "/Qt/.config/qupzilla/profiles/default/bookmarks.json";
		BEntry dest(destination, false);
		BEntry def(path, false);
		if (dest == def) {
			if (def.Exists()) {
				BDirectory parent;
				def.GetParent(&parent);
				int replaceIndex = 0;
				while (BEntry(&parent, (BString("bookmarks-old-")
					<< replaceIndex << ".json").String()).Exists())
					replaceIndex++;
				def.Rename(BString("bookmarks-old-") << replaceIndex
					<< ".json");
			}
		}
		else
			std::cerr << "Put the generated file into " << path.String()
				<< " for use with QupZilla." << std::endl;

	}

	if (fDestination != &std::cout)
		delete fDestination;

	if (destination != NULL) {
		fDestination = new std::ofstream(destination);
		if (!fDestination->good()) {
			delete fDestination;
			fDestination = &std::cout;
		}
	} else
		fDestination = &std::cout;

	*fDestination << "{" << std::endl << " \"roots\": {" << std::endl
		<< "  \"bookmark_bar\": ";

	if (entry->IsFolder())
		static_cast<BookmarksFolder*>(entry)->SetName("Import");

	HandleItem(entry, 0, true);

	*fDestination << std::endl << " }," << std::endl << " \"version\": 1"
		<< std::endl << "}" << std::endl;
}

void QupZillaOutput::HandleItem(BookmarksEntry* entry, int indent, bool first)
{
	if (entry->IsFolder())
		OutputDirectory(*static_cast<BookmarksFolder*>(entry), indent, first);
	else if (entry->IsBookmark())
		OutputBookmark(*static_cast<Bookmark*>(entry), indent, first);
}

void QupZillaOutput::OutputDirectory(BookmarksFolder& dir, int indent,
	bool first)
{
	BString ind;
	ind.Append(' ', indent * fIndentSize + kBaseOffset);

	if (!first)
		*fDestination << ", ";

	*fDestination << std::endl
		<< ind << "{" << std::endl << ind << " \"children\": [";

	std::vector<BookmarksEntry*>::iterator it;
	for (it = dir.begin(); it != dir.end(); it++)
		HandleItem(*it, indent + 1, it == dir.begin());

	if (dir.size() > 0)
		*fDestination << std::endl << ind << " ";
	*fDestination	<< "]," << std::endl
					<< ind << " \"name\": \"" << dir.GetName() << "\","
					<< std::endl
					<< ind << " \"type\": \"folder\"" << std::endl
					<< ind << "}";
}

void QupZillaOutput::OutputBookmark(Bookmark& bookmark, int indent, bool first)
{
	BString ind;
	ind.Append(' ', indent * fIndentSize + kBaseOffset);

	if (!first)
		*fDestination << ", ";

	*fDestination << std::endl << ind << "{" << std::endl;
	if (BString(bookmark.GetKeywords()) != "")
		*fDestination << ind << " \"keyword\": \"" << bookmark.GetKeywords()
			<< "\"," << std::endl;

	*fDestination	<< ind << " \"name\": \"" << bookmark.GetTitle() << "\","
					<< std::endl
					<< ind << " \"type\": \"url\"," << std::endl
					<< ind << " \"url\": \"" << bookmark.GetURL() << "\""
					<< std::endl
					<< ind << "}";
}

void QupZillaOutput::SetIndentSize(int spaces)
{
	if (spaces >= 0)
		fIndentSize = spaces;
}

int QupZillaOutput::GetIndentSize()
{
	return fIndentSize;
}

QupZillaOutput::QupZillaOutput()
	:
	fIndentSize(2)
{
}

QupZillaOutput::~QupZillaOutput()
{
	delete fDestination;
}
<commit_msg>Fix build with current API<commit_after>/*
 * QupZillaFormat.cpp
 * Copyright (c) 2015 Markus Himmel. All rights reserved.
 * Distributed under the terms of the MIT license.
 */

#include <fstream>
#include <iostream>

#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <Json.h>
#include <Path.h>

#include "BookmarksTree.h"
#include "BookmarksFormat.h"

QupZillaInput::QupZillaInput()
{
}

QupZillaInput::~QupZillaInput()
{
}

BookmarksEntry* QupZillaInput::Input(const char* source)
{
	BFile file(source, B_READ_ONLY);
	if (file.InitCheck() != B_OK)
		return NULL;

	off_t size;
	if (file.GetSize(&size) != B_OK)
		return NULL;

	char* buffer = new (std::nothrow) char[size];
	if (buffer == NULL)
		return NULL;

	if (file.Read(buffer, size) != size) {
		delete[] buffer;
		return NULL;
	}

	BString json(buffer);
	delete[] buffer;
	BMessage decoded;

	if (BJson::Parse(json, decoded) != B_OK)
		return NULL;

	BMessage roots;
	if (decoded.FindMessage("roots", &roots) != B_OK)
		return NULL;

	BookmarksFolder* top = new BookmarksFolder(), * child = NULL;

	BMessage folder;
	if (roots.FindMessage("bookmark_menu", &folder) == B_OK) {
		child = readDirectory(folder);
		if (child != NULL)
			top->push_back(child);
	}

	if (roots.FindMessage("bookmark_menu", &folder) == B_OK) {
		child = readDirectory(folder);
		if (child != NULL)
			top->push_back(child);
	}

	if (roots.FindMessage("other", &folder) == B_OK) {
		child = readDirectory(folder);
		if (child != NULL)
			top->push_back(child);
	}

	return top;
}

BookmarksFolder* QupZillaInput::readDirectory(BMessage& info)
{
	BMessage children;
	if (info.FindMessage("children", &children) != B_OK)
		return NULL;

	BookmarksFolder* thisDir = new BookmarksFolder();

	int currentIndex = 0;
	BMessage currentChild;
	while (children.FindMessage((BString() << currentIndex).String(),
		&currentChild) == B_OK) {
		currentIndex++;
		const char* type;
		if (currentChild.FindString("type", &type) != B_OK)
			continue;

		BString typeS(type);
		if (typeS == "url") {
			Bookmark* child = readItem(currentChild);
			if (child != NULL)
				thisDir->push_back(child);
		} else if (typeS == "folder") {
			BookmarksFolder* child = readDirectory(currentChild);
			if (child != NULL)
				thisDir->push_back(child);
		} else
			continue;
	}

	const char* name;
	if (info.FindString("name", &name) == B_OK)
		thisDir->SetName(name);
	else
		thisDir->SetName("Unknown");

	return thisDir;
}

Bookmark* QupZillaInput::readItem(BMessage& info)
{
	Bookmark* result = new Bookmark();

	const char* tmp;
	if (info.FindString("name", &tmp) == B_OK)
		result->SetTitle(tmp);
	else
		result->SetTitle("Unknown");

	if (info.FindString("url", &tmp) == B_OK)
		result->SetURL(tmp);
	else
		result->SetURL("Unknown");

	if (info.FindString("keyword", &tmp) == B_OK)
		result->SetKeywords(tmp);

	return result;
}

const int kBaseOffset = 3;

void QupZillaOutput::Output(BookmarksEntry* entry, const char* destination)
{
	BPath dir;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK) {
		BString path(dir.Path());
		path << "/Qt/.config/qupzilla/profiles/default/bookmarks.json";
		BEntry dest(destination, false);
		BEntry def(path, false);
		if (dest == def) {
			if (def.Exists()) {
				BDirectory parent;
				def.GetParent(&parent);
				int replaceIndex = 0;
				while (BEntry(&parent, (BString("bookmarks-old-")
					<< replaceIndex << ".json").String()).Exists())
					replaceIndex++;
				def.Rename(BString("bookmarks-old-") << replaceIndex
					<< ".json");
			}
		}
		else
			std::cerr << "Put the generated file into " << path.String()
				<< " for use with QupZilla." << std::endl;

	}

	if (fDestination != &std::cout)
		delete fDestination;

	if (destination != NULL) {
		fDestination = new std::ofstream(destination);
		if (!fDestination->good()) {
			delete fDestination;
			fDestination = &std::cout;
		}
	} else
		fDestination = &std::cout;

	*fDestination << "{" << std::endl << " \"roots\": {" << std::endl
		<< "  \"bookmark_bar\": ";

	if (entry->IsFolder())
		static_cast<BookmarksFolder*>(entry)->SetName("Import");

	HandleItem(entry, 0, true);

	*fDestination << std::endl << " }," << std::endl << " \"version\": 1"
		<< std::endl << "}" << std::endl;
}

void QupZillaOutput::HandleItem(BookmarksEntry* entry, int indent, bool first)
{
	if (entry->IsFolder())
		OutputDirectory(*static_cast<BookmarksFolder*>(entry), indent, first);
	else if (entry->IsBookmark())
		OutputBookmark(*static_cast<Bookmark*>(entry), indent, first);
}

void QupZillaOutput::OutputDirectory(BookmarksFolder& dir, int indent,
	bool first)
{
	BString ind;
	ind.Append(' ', indent * fIndentSize + kBaseOffset);

	if (!first)
		*fDestination << ", ";

	*fDestination << std::endl
		<< ind << "{" << std::endl << ind << " \"children\": [";

	std::vector<BookmarksEntry*>::iterator it;
	for (it = dir.begin(); it != dir.end(); it++)
		HandleItem(*it, indent + 1, it == dir.begin());

	if (dir.size() > 0)
		*fDestination << std::endl << ind << " ";
	*fDestination	<< "]," << std::endl
					<< ind << " \"name\": \"" << dir.GetName() << "\","
					<< std::endl
					<< ind << " \"type\": \"folder\"" << std::endl
					<< ind << "}";
}

void QupZillaOutput::OutputBookmark(Bookmark& bookmark, int indent, bool first)
{
	BString ind;
	ind.Append(' ', indent * fIndentSize + kBaseOffset);

	if (!first)
		*fDestination << ", ";

	*fDestination << std::endl << ind << "{" << std::endl;
	if (BString(bookmark.GetKeywords()) != "")
		*fDestination << ind << " \"keyword\": \"" << bookmark.GetKeywords()
			<< "\"," << std::endl;

	*fDestination	<< ind << " \"name\": \"" << bookmark.GetTitle() << "\","
					<< std::endl
					<< ind << " \"type\": \"url\"," << std::endl
					<< ind << " \"url\": \"" << bookmark.GetURL() << "\""
					<< std::endl
					<< ind << "}";
}

void QupZillaOutput::SetIndentSize(int spaces)
{
	if (spaces >= 0)
		fIndentSize = spaces;
}

int QupZillaOutput::GetIndentSize()
{
	return fIndentSize;
}

QupZillaOutput::QupZillaOutput()
	:
	fIndentSize(2)
{
}

QupZillaOutput::~QupZillaOutput()
{
	delete fDestination;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#include "Buffer.h"

#include "RamCloudBackend.h"
#include "Postgres.h"

const char* ramcloudConnectionString() {
  char* conn = (char*) malloc(128 * sizeof(char));
  snprintf(conn, 127, "fast+udp:host=%s,port=%d",
           RAMCLOUD_HOST.c_str(), RAMCLOUD_PORT);
  printf("connecting to %s\n", conn);
  return conn;
}

//
// RamCloudFactDB
//

// Construct the requisite tables for storing facts
// in RamCloud, if they don't already exist.
RamCloudFactDB::RamCloudFactDB()
    : ramcloud(ramcloudConnectionString()),
      factTableName("Facts")
    {

  factTableId = ramcloud.createTable(factTableName);

  // Create a Postgres connection
  char factQuery[127];
  snprintf(factQuery, 127, "SELECT left_arg, rel, right_arg, weight FROM %s LIMIT 10000000;", PG_TABLE_FACT.c_str());
  PGIterator iter = PGIterator(factQuery);
  uint64_t totalRead = 0;

  while (iter.hasNext()) {
    RAMCloud::MultiWriteObject requestObjects[100];
    RAMCloud::MultiWriteObject* requests[100];
    float confidences[100];
    uint32_t numRequests = 0;
    for (uint16_t i = 0; i < 100; ++i) {
      // If no more to write, break;
      if (!iter.hasNext()) { break; }

      // Get data from Postgres
      PGRow row = iter.next();
      word fact[256];
      uint8_t factLength = 0;
      for (int k = 0; k < 3; ++k) {  // for each argument...
        if (row[k] == NULL) { continue; }
        // ...read it as a string
        uint32_t stringLength = strlen(row[k]);
        char stringWithoutBrackets[stringLength + 1];
        memcpy( stringWithoutBrackets, &row[k][1], stringLength - 2 );
        stringWithoutBrackets[stringLength] = '\0';

        // ...tokenize it
        const char* token = strtok(stringWithoutBrackets, ",");
        while (token != NULL) {
          char* end;
          fact[factLength] = strtol(token, &end, 10);
          if (end == token || *end != '\0') {
            printf("Could not convert string to integer: %s\n (end is '%c')", token);
            std::exit(1);
          }
          factLength += 1;  // append the word to the buffer
          token = strtok(NULL, ",");
        }
        // sanity check to prevent too long of a fact
        if (factLength >= 256) { break; }
      }
      confidences[i] = atof(row[3]);

      // Create request object
      requestObjects[i] =
        RAMCloud::MultiWriteObject(factTableId, fact, factLength,
          &confidences[i], sizeof(float));
      requests[i] = &requestObjects[i];
      numRequests += 1;
      totalRead += 1;
    }
    // Write request
    ramcloud.multiWrite(requests, numRequests);
    if (totalRead % 1000000 == 0) {
      printf("Read %luM facts\n", totalRead / 1000000);
    }
  }

}

const bool RamCloudFactDB::contains(const word* key, const uint8_t wordLength) {
  RAMCloud::Buffer buffer;
  ramcloud.read(factTableId, key, wordLength, &buffer);
  if (buffer.getTotalLength() > 0)
    return true;
  else
    return false;
}

// Clean up
RamCloudFactDB::~RamCloudFactDB() {
//  dropTable(factTableName);  // TODO(gabor) drop me somewhere!
}

FactDB* ReadRamCloudFactDB() {
  return new RamCloudFactDB();
}
<commit_msg>I don't like c++ strings...<commit_after>#include <stdio.h>
#include <stdlib.h>

#include "Buffer.h"

#include "RamCloudBackend.h"
#include "Postgres.h"

const char* ramcloudConnectionString() {
  char* conn = (char*) malloc(128 * sizeof(char));
  snprintf(conn, 127, "fast+udp:host=%s,port=%d",
           RAMCLOUD_HOST.c_str(), RAMCLOUD_PORT);
  printf("connecting to %s\n", conn);
  return conn;
}

//
// RamCloudFactDB
//

// Construct the requisite tables for storing facts
// in RamCloud, if they don't already exist.
RamCloudFactDB::RamCloudFactDB()
    : ramcloud(ramcloudConnectionString()),
      factTableName("Facts")
    {

  factTableId = ramcloud.createTable(factTableName);

  // Create a Postgres connection
  char factQuery[127];
  snprintf(factQuery, 127, "SELECT left_arg, rel, right_arg, weight FROM %s LIMIT 10000000;", PG_TABLE_FACT.c_str());
  PGIterator iter = PGIterator(factQuery);
  uint64_t totalRead = 0;

  while (iter.hasNext()) {
    RAMCloud::MultiWriteObject requestObjects[100];
    RAMCloud::MultiWriteObject* requests[100];
    float confidences[100];
    uint32_t numRequests = 0;
    for (uint16_t i = 0; i < 100; ++i) {
      // If no more to write, break;
      if (!iter.hasNext()) { break; }

      // Get data from Postgres
      PGRow row = iter.next();
      word fact[256];
      uint8_t factLength = 0;
      for (int k = 0; k < 3; ++k) {  // for each argument...
        if (row[k] == NULL) { continue; }
        // ...read it as a string
        uint32_t stringLength = strlen(row[k]);
        char stringWithoutBrackets[stringLength ];
        memcpy( stringWithoutBrackets, &row[k][1], stringLength - 2 );
        stringWithoutBrackets[stringLength - 1] = '\0';

        // ...tokenize it
        const char* token = strtok(stringWithoutBrackets, ",");
        while (token != NULL) {
          char* end;
          fact[factLength] = strtol(token, &end, 10);
          if (end == token || *end != '\0') {
            printf("Could not convert string to integer: %s\n (end is '%c')", token);
            std::exit(1);
          }
          factLength += 1;  // append the word to the buffer
          token = strtok(NULL, ",");
        }
        // sanity check to prevent too long of a fact
        if (factLength >= 256) { break; }
      }
      confidences[i] = atof(row[3]);

      // Create request object
      requestObjects[i] =
        RAMCloud::MultiWriteObject(factTableId, fact, factLength,
          &confidences[i], sizeof(float));
      requests[i] = &requestObjects[i];
      numRequests += 1;
      totalRead += 1;
    }
    // Write request
    ramcloud.multiWrite(requests, numRequests);
    if (totalRead % 1000000 == 0) {
      printf("Read %luM facts\n", totalRead / 1000000);
    }
  }

}

const bool RamCloudFactDB::contains(const word* key, const uint8_t wordLength) {
  RAMCloud::Buffer buffer;
  ramcloud.read(factTableId, key, wordLength, &buffer);
  if (buffer.getTotalLength() > 0)
    return true;
  else
    return false;
}

// Clean up
RamCloudFactDB::~RamCloudFactDB() {
//  dropTable(factTableName);  // TODO(gabor) drop me somewhere!
}

FactDB* ReadRamCloudFactDB() {
  return new RamCloudFactDB();
}
<|endoftext|>