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

#include "base/logging.hh"
#include "systemc/ext/core/sc_simcontext.hh"

namespace sc_core
{

sc_dt::uint64
sc_simcontext::delta_count() const
{
    warn("%s not implemented.\n", __PRETTY_FUNCTION__);
    return 0;
}

void
sc_simcontext::reset()
{
    warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}

sc_curr_proc_handle
sc_simcontext::get_curr_proc_info()
{
    warn("%s not implemented.\n", __PRETTY_FUNCTION__);
    return nullptr;
}

sc_object *
sc_simcontext::first_object()
{
    warn("%s not implemented.\n", __PRETTY_FUNCTION__);
    return nullptr;
}

sc_object *
sc_simcontext::next_object()
{
    warn("%s not implemented.\n", __PRETTY_FUNCTION__);
    return nullptr;
}

sc_simcontext *
sc_get_curr_simcontext()
{
    warn("%s not implemented.\n", __PRETTY_FUNCTION__);
    return nullptr;
}

} // namespace sc_core
<commit_msg>systemc: Mostly implememt sc_simcontext.<commit_after>/*
 * Copyright 2018 Google, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include "base/logging.hh"
#include "systemc/core/object.hh"
#include "systemc/core/scheduler.hh"
#include "systemc/ext/core/sc_main.hh"
#include "systemc/ext/core/sc_simcontext.hh"

namespace sc_core
{

namespace
{

size_t objIndex = 0;
sc_simcontext currContext;

sc_curr_proc_info currProcInfo;

} // anonymous namespace

sc_dt::uint64 sc_simcontext::delta_count() const { return sc_delta_count(); }
void sc_simcontext::reset() { objIndex = 0; }

sc_curr_proc_handle
sc_simcontext::get_curr_proc_info()
{
    ::sc_gem5::Process *p = ::sc_gem5::scheduler.current();
    currProcInfo.process_handle = p;
    currProcInfo.kind = p ? p->procKind() : SC_NO_PROC_;
    return &currProcInfo;
}

sc_object *
sc_simcontext::first_object()
{
    objIndex = 0;
    if (!::sc_gem5::allObjects.empty())
        return ::sc_gem5::allObjects[0];
    else
        return nullptr;
}

sc_object *
sc_simcontext::next_object()
{
    objIndex++;
    if (::sc_gem5::allObjects.size() > objIndex)
        return ::sc_gem5::allObjects[objIndex];
    else
        return nullptr;
}

sc_simcontext *
sc_get_curr_simcontext()
{
    return &currContext;
}

} // namespace sc_core
<|endoftext|>


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

#include "Buffer.h"

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

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

RamCloudGraph::RamCloudGraph()
    : ramcloud(ramcloudConnectionString()),
      wordIndexerTable(ramcloud.createTable("word_indexer")),
      edgesTable(ramcloud.createTable("edges")) { }

RamCloudGraph::RamCloudGraph(const Graph& copy)
    : ramcloud(ramcloudConnectionString()),
      wordIndexerTable(ramcloud.createTable("word_indexer")),
      edgesTable(ramcloud.createTable("edges")) {

  vector<word> keys = copy.keys();
  // Copy Graph
  RAMCloud::MultiWriteObject* indexerRequests[keys.size()];
  RAMCloud::MultiWriteObject* edgesRequests[keys.size()];
  for (int i = 0; i < keys.size(); ++i) {
    word key = keys[i];
    string gloss = copy.gloss(key);
    vector<edge> edges = copy.outgoingEdges(key);
    // Indexer
    indexerRequests[i] = new RAMCloud::MultiWriteObject(
          wordIndexerTable, &key, sizeof(word),
          gloss.c_str(), gloss.size()
        );
    // Edges
    uint32_t blockSize = (sizeof(word) + sizeof(edge_type) + sizeof(float));
    uint8_t* edgesBlob = (uint8_t*) malloc( keys.size() * blockSize );
    for (int k = 0; k < edges.size(); ++k) {
      *(edgesBlob + (k * blockSize + 0)) = edges[k].sink;
      *(edgesBlob + (k * blockSize + sizeof(word))) = edges[k].type;
      *(edgesBlob + (k * blockSize + sizeof(word) + sizeof(edge_type)))
          = edges[k].cost;
    }
    indexerRequests[i] = new RAMCloud::MultiWriteObject(
          wordIndexerTable, &key, sizeof(word),
          edgesBlob, keys.size() * blockSize
        );
  }
  // Commit to RamCloud
  ramcloud.multiWrite(indexerRequests, keys.size());
  ramcloud.multiWrite(edgesRequests, keys.size());
}

RamCloudGraph::~RamCloudGraph() {
  ramcloud.dropTable("word_indexer");
  ramcloud.dropTable("edges");
}

// TODO(gabor) I haven't even made an attempt at making this yet
const vector<edge>& RamCloudGraph::outgoingEdges(word source) const {
  return vector<edge>();
}

// TODO(gabor) Finish me (commented line complains about const)
const string RamCloudGraph::gloss(word id) const {
  RAMCloud::Buffer buffer;
//  ramcloud.read(wordIndexerTable, &id, sizeof(word), &buffer);
  char gloss[buffer.getTotalLength()];
  buffer.copy(0, buffer.getTotalLength(), &gloss);
  return string(gloss);
}

// TODO(gabor) in theory this would be nice to implement, but I can't forsee
//             anyone actually using it in the near future...
const vector<word> RamCloudGraph::keys() const {
  printf("FATAL: keys() not implemented for RamCloudGraph");
  std::exit(1);
}

Graph* ReadRamCloudGraph() {
  // Read from Postgres
  Graph* inMemoryGraph = ReadGraph();
  Graph* ramcloud = new RamCloudGraph(*inMemoryGraph);
  delete inMemoryGraph;
  return ramcloud;
}

//
// 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);

  while (iter.hasNext()) {
    RAMCloud::MultiWriteObject requestObjects[100];
    RAMCloud::MultiWriteObject* requests[100];
    float confidences[100];
    uint32_t numRequests;
    for (uint8_t i = 0; i++; i < 100) {
      // 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 i = 0; i < 3; ++i) {  // for each argument...
        // ...read it as a string
        uint32_t stringLength = strlen(row[i]);
        char stringWithoutBrackets[stringLength];
        memcpy( stringWithoutBrackets, &row[i][1], stringLength - 2 );
        // ...tokenize it
        const char* token = strtok(stringWithoutBrackets, ",");
        while (token != NULL) {
          fact[factLength] = atoi(token);
          factLength += 1;  // append the word to the buffer
        }
        // 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;
    }
    // Write request
    ramcloud.multiWrite(requests, numRequests);
  }

}

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>Fix ambiguous index<commit_after>#include <stdio.h>
#include <stdlib.h>

#include "Buffer.h"

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

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

RamCloudGraph::RamCloudGraph()
    : ramcloud(ramcloudConnectionString()),
      wordIndexerTable(ramcloud.createTable("word_indexer")),
      edgesTable(ramcloud.createTable("edges")) { }

RamCloudGraph::RamCloudGraph(const Graph& copy)
    : ramcloud(ramcloudConnectionString()),
      wordIndexerTable(ramcloud.createTable("word_indexer")),
      edgesTable(ramcloud.createTable("edges")) {

  vector<word> keys = copy.keys();
  // Copy Graph
  RAMCloud::MultiWriteObject* indexerRequests[keys.size()];
  RAMCloud::MultiWriteObject* edgesRequests[keys.size()];
  for (int i = 0; i < keys.size(); ++i) {
    word key = keys[i];
    string gloss = copy.gloss(key);
    vector<edge> edges = copy.outgoingEdges(key);
    // Indexer
    indexerRequests[i] = new RAMCloud::MultiWriteObject(
          wordIndexerTable, &key, sizeof(word),
          gloss.c_str(), gloss.size()
        );
    // Edges
    uint32_t blockSize = (sizeof(word) + sizeof(edge_type) + sizeof(float));
    uint8_t* edgesBlob = (uint8_t*) malloc( keys.size() * blockSize );
    for (int k = 0; k < edges.size(); ++k) {
      *(edgesBlob + (k * blockSize + 0)) = edges[k].sink;
      *(edgesBlob + (k * blockSize + sizeof(word))) = edges[k].type;
      *(edgesBlob + (k * blockSize + sizeof(word) + sizeof(edge_type)))
          = edges[k].cost;
    }
    indexerRequests[i] = new RAMCloud::MultiWriteObject(
          wordIndexerTable, &key, sizeof(word),
          edgesBlob, keys.size() * blockSize
        );
  }
  // Commit to RamCloud
  ramcloud.multiWrite(indexerRequests, keys.size());
  ramcloud.multiWrite(edgesRequests, keys.size());
}

RamCloudGraph::~RamCloudGraph() {
  ramcloud.dropTable("word_indexer");
  ramcloud.dropTable("edges");
}

// TODO(gabor) I haven't even made an attempt at making this yet
const vector<edge>& RamCloudGraph::outgoingEdges(word source) const {
  return vector<edge>();
}

// TODO(gabor) Finish me (commented line complains about const)
const string RamCloudGraph::gloss(word id) const {
  RAMCloud::Buffer buffer;
//  ramcloud.read(wordIndexerTable, &id, sizeof(word), &buffer);
  char gloss[buffer.getTotalLength()];
  buffer.copy(0, buffer.getTotalLength(), &gloss);
  return string(gloss);
}

// TODO(gabor) in theory this would be nice to implement, but I can't forsee
//             anyone actually using it in the near future...
const vector<word> RamCloudGraph::keys() const {
  printf("FATAL: keys() not implemented for RamCloudGraph");
  std::exit(1);
}

Graph* ReadRamCloudGraph() {
  // Read from Postgres
  Graph* inMemoryGraph = ReadGraph();
  Graph* ramcloud = new RamCloudGraph(*inMemoryGraph);
  delete inMemoryGraph;
  return ramcloud;
}

//
// 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);

  while (iter.hasNext()) {
    RAMCloud::MultiWriteObject requestObjects[100];
    RAMCloud::MultiWriteObject* requests[100];
    float confidences[100];
    uint32_t numRequests;
    for (uint8_t i = 0; i++; i < 100) {
      // 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...
        // ...read it as a string
        uint32_t stringLength = strlen(row[k]);
        char stringWithoutBrackets[stringLength];
        memcpy( stringWithoutBrackets, &row[k][1], stringLength - 2 );
        // ...tokenize it
        const char* token = strtok(stringWithoutBrackets, ",");
        while (token != NULL) {
          fact[factLength] = atoi(token);
          factLength += 1;  // append the word to the buffer
        }
        // 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;
    }
    // Write request
    ramcloud.multiWrite(requests, numRequests);
  }

}

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|>


<commit_before>/*
 * Copyright (C) 2016 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3, or any
 * later version accepted by the membership of KDE e.V. (or its
 * successor approved by the membership of KDE e.V.), which shall
 * act as a proxy defined in Section 6 of version 3 of the license.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "PDFCoverImageProvider.h"

#include <QCoreApplication>
#include <QDir>
#include <QIcon>
#include <QMimeDatabase>
#include <QProcess>
#include <QStandardPaths>
#include <QUrl>
#include <QDebug>

class PDFCoverImageProvider::Private {
public:
    Private() {
        QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
        thumbDir = QDir(path);
        QString subpath("thumbcache");
        if(!thumbDir.exists(subpath)) {
            thumbDir.mkpath(subpath);
        }
        thumbDir.cd(subpath);
    }
    QDir thumbDir;
};

PDFCoverImageProvider::PDFCoverImageProvider()
    : QQuickImageProvider(QQuickImageProvider::Image)
    , d(new Private)
{
}

PDFCoverImageProvider::~PDFCoverImageProvider()
{
    delete d;
}

QImage PDFCoverImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize)
{
    Q_UNUSED(size)
    Q_UNUSED(requestedSize)
    QImage img;

    QMimeDatabase db;
    db.mimeTypeForFile(id, QMimeDatabase::MatchContent);
    const QMimeType mime = db.mimeTypeForFile(id, QMimeDatabase::MatchContent);
    if(mime.inherits("application/pdf")) {
        //-sOutputFile=FILENAME.png FILENAME
        QString outFile = QString("%1/%2.png").arg(d->thumbDir.absolutePath()).arg(QUrl(id).toString().replace("/", "-").replace(":", "-"));
        if(!QFile::exists(outFile)) {
            // then we've not already generated a thumbnail, try to make one...
            QProcess thumbnailer;
            QStringList args;
            args << "-sPageList=1" << "-dLastPage=1" << "-dSAFER" << "-dBATCH" << "-dNOPAUSE" << "-dQUIET" << "-sDEVICE=png16m" << "-dGraphicsAlphaBits=4" << "-r150";
            args << QString("-sOutputFile=%1").arg(outFile) << id;
            QString gsApp;
            #ifdef Q_OS_WIN
                gsApp = qApp->applicationDirPath();
                #ifdef Q_OS_WIN64
                    gsApp += "/gswin64c.exe";
                #else
                    gsApp += "/gswin32c.exe";
                #endif
            #else
                gsApp = "gs";
            #endif
            thumbnailer.start(gsApp, args);
            thumbnailer.waitForFinished();
        }
        bool success = false;
        // Now, does it exist this time?
        if(QFile::exists(outFile)) {
            success = img.load(outFile);
        }
        if(!success) {
            QIcon oops = QIcon::fromTheme("unknown");
            img = oops.pixmap(oops.availableSizes().last()).toImage();
            qDebug() << "Failed to load image with id" << id << "from thumbnail file" << outFile;
        }
    }

    return img;
}
<commit_msg>Don't use the msvc ghostscript exec names with mingw<commit_after>/*
 * Copyright (C) 2016 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3, or any
 * later version accepted by the membership of KDE e.V. (or its
 * successor approved by the membership of KDE e.V.), which shall
 * act as a proxy defined in Section 6 of version 3 of the license.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "PDFCoverImageProvider.h"

#include <QCoreApplication>
#include <QDir>
#include <QIcon>
#include <QMimeDatabase>
#include <QProcess>
#include <QStandardPaths>
#include <QUrl>
#include <QDebug>

class PDFCoverImageProvider::Private {
public:
    Private() {
        QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
        thumbDir = QDir(path);
        QString subpath("thumbcache");
        if(!thumbDir.exists(subpath)) {
            thumbDir.mkpath(subpath);
        }
        thumbDir.cd(subpath);
    }
    QDir thumbDir;
};

PDFCoverImageProvider::PDFCoverImageProvider()
    : QQuickImageProvider(QQuickImageProvider::Image)
    , d(new Private)
{
}

PDFCoverImageProvider::~PDFCoverImageProvider()
{
    delete d;
}

QImage PDFCoverImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize)
{
    Q_UNUSED(size)
    Q_UNUSED(requestedSize)
    QImage img;

    QMimeDatabase db;
    db.mimeTypeForFile(id, QMimeDatabase::MatchContent);
    const QMimeType mime = db.mimeTypeForFile(id, QMimeDatabase::MatchContent);
    if(mime.inherits("application/pdf")) {
        //-sOutputFile=FILENAME.png FILENAME
        QString outFile = QString("%1/%2.png").arg(d->thumbDir.absolutePath()).arg(QUrl(id).toString().replace("/", "-").replace(":", "-"));
        if(!QFile::exists(outFile)) {
            // then we've not already generated a thumbnail, try to make one...
            QProcess thumbnailer;
            QStringList args;
            args << "-sPageList=1" << "-dLastPage=1" << "-dSAFER" << "-dBATCH" << "-dNOPAUSE" << "-dQUIET" << "-sDEVICE=png16m" << "-dGraphicsAlphaBits=4" << "-r150";
            args << QString("-sOutputFile=%1").arg(outFile) << id;
            QString gsApp;
            #ifdef Q_OS_WIN
                #ifdef __MINGW32__
                    gsApp = qApp->applicationDirPath() + "/gsc.exe";
                #else
                    gsApp = qApp->applicationDirPath();
                    #ifdef Q_OS_WIN64
                        gsApp += "/gswin64c.exe";
                    #else
                        gsApp += "/gswin32c.exe";
                    #endif
                #endif
            #else
                gsApp = "gs";
            #endif
            thumbnailer.start(gsApp, args);
            thumbnailer.waitForFinished();
        }
        bool success = false;
        // Now, does it exist this time?
        if(QFile::exists(outFile)) {
            success = img.load(outFile);
        }
        if(!success) {
            QIcon oops = QIcon::fromTheme("unknown");
            img = oops.pixmap(oops.availableSizes().last()).toImage();
            qDebug() << "Failed to load image with id" << id << "from thumbnail file" << outFile;
        }
    }

    return img;
}
<|endoftext|>


<commit_before>#include "filebrowserwidget.h"

#include <QFileSystemModel>

#include <QDesktopServices>
#include <QHeaderView>
#include <QSettings>

#define SETTINGS_SORTCOLUMN "_SortColumn"
#define SETTINGS_SORTORDER  "_SortOrder"

FileBrowserWidget::FileBrowserWidget(QWidget *pParent) :
    QTreeView(pParent),
    CommonWidget(pParent)
{
    mFileSystemModel = new QFileSystemModel;

    mFileSystemModel->setRootPath("");

    // Set some properties for the file browser widget itself

    setModel(mFileSystemModel);   // Associate ourselves to mFileSystemModel
    setSortingEnabled(true);      // Allow sorting
    setUniformRowHeights(true);   // They ought to be of the same height, so set
                                  // it to true to speed things up (can't harm!)
}

FileBrowserWidget::~FileBrowserWidget()
{
    delete mFileSystemModel;
}

void FileBrowserWidget::retranslateUi()
{
    // Nothing to do for now...
}

void FileBrowserWidget::defaultSettings()
{
    // Sort by ascending drive letters / paths

    sortByColumn(0, Qt::AscendingOrder);
}

void FileBrowserWidget::loadSettings(const QSettings &pSettings,
                                     const QString &pKey)
{
    // Retrieve the sorting information

    sortByColumn(pSettings.value(pKey+SETTINGS_SORTCOLUMN, 0).toInt(),
                 Qt::SortOrder(pSettings.value(pKey+SETTINGS_SORTORDER, Qt::AscendingOrder).toInt()));
}

void FileBrowserWidget::saveSettings(QSettings &pSettings, const QString &pKey)
{
    // Keep track of the sorting information

    pSettings.setValue(pKey+SETTINGS_SORTCOLUMN, header()->sortIndicatorSection());
    pSettings.setValue(pKey+SETTINGS_SORTORDER, header()->sortIndicatorOrder());
}

QSize FileBrowserWidget::sizeHint() const
{
    // Suggest a default size for the file browser widget
    // Note: this is critical if we want a docked widget, with a file browser
    //       widget on it, to have a decent size when docked to the main window

    return defaultSize(0.15);
}

void FileBrowserWidget::paintEvent(QPaintEvent *pEvent)
{
    QTreeView::paintEvent(pEvent);

    // Draw a border in case we are docked

    drawBorderIfDocked();
}
<commit_msg>Minor cleaning up.<commit_after>#include "filebrowserwidget.h"

#include <QFileSystemModel>

#include <QDesktopServices>
#include <QHeaderView>
#include <QSettings>

#define SETTINGS_SORTCOLUMN "_SortColumn"
#define SETTINGS_SORTORDER  "_SortOrder"

FileBrowserWidget::FileBrowserWidget(QWidget *pParent) :
    QTreeView(pParent),
    CommonWidget(pParent)
{
    mFileSystemModel = new QFileSystemModel;

    // We want acces to the full file system

    mFileSystemModel->setRootPath(QDir::rootPath());

    // Set some properties for the file browser widget itself

    setModel(mFileSystemModel);   // Associate ourselves to mFileSystemModel
    setSortingEnabled(true);      // Allow sorting
    setUniformRowHeights(true);   // Everything ought to be of the same height,
                                  // so set this property to true since it can
                                  // only speed things up which can't harm!
}

FileBrowserWidget::~FileBrowserWidget()
{
    delete mFileSystemModel;
}

void FileBrowserWidget::retranslateUi()
{
    // Nothing to do for now...
}

void FileBrowserWidget::defaultSettings()
{
    // Sort by ascending drive letters / paths

    sortByColumn(0, Qt::AscendingOrder);
}

void FileBrowserWidget::loadSettings(const QSettings &pSettings,
                                     const QString &pKey)
{
    // Retrieve the sorting information

    sortByColumn(pSettings.value(pKey+SETTINGS_SORTCOLUMN, 0).toInt(),
                 Qt::SortOrder(pSettings.value(pKey+SETTINGS_SORTORDER, Qt::AscendingOrder).toInt()));
}

void FileBrowserWidget::saveSettings(QSettings &pSettings, const QString &pKey)
{
    // Keep track of the sorting information

    pSettings.setValue(pKey+SETTINGS_SORTCOLUMN, header()->sortIndicatorSection());
    pSettings.setValue(pKey+SETTINGS_SORTORDER, header()->sortIndicatorOrder());
}

QSize FileBrowserWidget::sizeHint() const
{
    // Suggest a default size for the file browser widget
    // Note: this is critical if we want a docked widget, with a file browser
    //       widget on it, to have a decent size when docked to the main window

    return defaultSize(0.15);
}

void FileBrowserWidget::paintEvent(QPaintEvent *pEvent)
{
    QTreeView::paintEvent(pEvent);

    // Draw a border in case we are docked

    drawBorderIfDocked();
}
<|endoftext|>


<commit_before>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include "test.hpp"

#include <tao/pegtl/contrib/tracer.hpp>

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      using GRAMMAR = sor< failure, one< 'a' > >;

      template< typename Rule >
      struct tracer_action
         : nothing< Rule >
      {
      };

      unsigned a0 = 0;
      unsigned a = 0;

      template<>
      struct tracer_action< one< 'a' > >
      {
         template< typename... Ts >
         static void apply0( Ts&&... /*unused*/ )
         {
            ++a0;
         }
      };

      template<>
      struct tracer_action< GRAMMAR >
      {
         template< typename... Ts >
         static void apply( Ts&&... /*unused*/ )
         {
            ++a;
         }
      };

      void unit_test()
      {
         {
            memory_input in( "ab", "trace test please ignore" );
            const auto result = parse< GRAMMAR, nothing, tracer >( in );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 0 );
            TAO_PEGTL_TEST_ASSERT( a == 0 );
         }
         {
            memory_input in( "ab", "trace test please ignore" );
            const auto result = parse< GRAMMAR, tracer_action, tracer >( in );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 1 );
            TAO_PEGTL_TEST_ASSERT( a == 1 );
         }
         {
            trace_state ts;
            memory_input in( "ab", "trace test please ignore" );
            const auto result = parse< GRAMMAR, nothing, tracer >( in, ts );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 1 );
            TAO_PEGTL_TEST_ASSERT( a == 1 );
         }
         {
            trace_state ts;
            memory_input in( "ab", "trace test please ignore" );
            const auto result = parse< GRAMMAR, tracer_action, tracer >( in, ts );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 2 );
            TAO_PEGTL_TEST_ASSERT( a == 2 );
         }
      }

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#include "main.hpp"
<commit_msg>Fix coverage<commit_after>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include "test.hpp"

#include <tao/pegtl/contrib/tracer.hpp>

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      using GRAMMAR = sor< failure, one< 'a' > >;
      using GRAMMAR2 = seq< one< 'a' >, any, any, any, any, one< 'b' >, eof >;

      template< typename Rule >
      struct tracer_action
         : nothing< Rule >
      {
      };

      unsigned a0 = 0;
      unsigned a = 0;

      template<>
      struct tracer_action< one< 'a' > >
      {
         template< typename... Ts >
         static void apply0( Ts&&... /*unused*/ )
         {
            ++a0;
         }
      };

      template<>
      struct tracer_action< GRAMMAR >
      {
         template< typename... Ts >
         static void apply( Ts&&... /*unused*/ )
         {
            ++a;
         }
      };

      void unit_test()
      {
         {
            memory_input in( "ab", "trace test please ignore" );
            const auto result = parse< GRAMMAR, nothing, tracer >( in );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 0 );
            TAO_PEGTL_TEST_ASSERT( a == 0 );
         }
         {
            memory_input in( "ab", "trace test please ignore" );
            const auto result = parse< GRAMMAR, tracer_action, tracer >( in );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 1 );
            TAO_PEGTL_TEST_ASSERT( a == 1 );
         }
         {
            trace_state ts;
            memory_input in( "ab", "trace test please ignore" );
            const auto result = parse< GRAMMAR, nothing, tracer >( in, ts );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 1 );
            TAO_PEGTL_TEST_ASSERT( a == 1 );
         }
         {
            trace_state ts;
            memory_input in( "ab", "trace test please ignore" );
            const auto result = parse< GRAMMAR, tracer_action, tracer >( in, ts );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 2 );
            TAO_PEGTL_TEST_ASSERT( a == 2 );
         }
         {
            trace_state ts;
            memory_input in( "a\r\n\t\0b", 6, "trace test please ignore" );
            const auto result = parse< GRAMMAR2, nothing, tracer >( in, ts );
            TAO_PEGTL_TEST_ASSERT( result );
            TAO_PEGTL_TEST_ASSERT( a0 == 2 );
            TAO_PEGTL_TEST_ASSERT( a == 2 );
         }
         {
            trace_state ts;
            memory_input in( "a\r\n\t\0b", 6, "trace test please ignore" );
            const auto result = parse< GRAMMAR2, tracer_action, tracer >( in, ts );
            TAO_PEGTL_TEST_ASSERT( result );
         }
      }

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#include "main.hpp"
<|endoftext|>


<commit_before>//
// Created by ariel on 11/6/16.
//
#include "Tower/TowerMan.h"
#include <iostream>

using std::vector;
using std::cout;
using std::endl;

namespace Towers {
    TowerMan::TowerMan(sf::RenderWindow &window, MonsterMan &monsterMan)
            : _towers(), _window(window),
              _monsterMan(&monsterMan) {
        _fireInterval = sf::seconds(0.7f);
        _fireAnimationInterval = sf::seconds(0.05f);

        Tower::_normalTexture.loadFromFile("Resources/Textures/Tower-lvl1.png");
        Tower::_firingTexture.loadFromFile("Resources/Textures/Tower-lvl1-fire.png");
        Tower::_fireSoundBuffer.loadFromFile("Resources/Sounds/TowerFireSound-1.wav");
    }

    void TowerMan::update() {
        //TODO: Loop through button events, perform actions on towers based on button clicks
        sf::Time currentElapsed = _fireClock.getElapsedTime();

        for (auto &t : _towers) {
            if (t.getHealth() <= 0 && !t.shouldDestroy())
                t.destroy();

            if ((currentElapsed - t.getLastFireTime()) >= _fireInterval && _hasMonsterInRange(t))
                t.startFire(currentElapsed);
            else if ((currentElapsed - t.getLastFireTime()) >= _fireAnimationInterval && t.isFiring())
                t.stopFire(currentElapsed);

			t.setTarget(_monsterMan->getMonstersInRange(t.getSprite().getPosition(), 10000));

            t.update();
        }
    }

    void TowerMan::render() {
        //TODO: Perform pre-tower-render events (buttons, etc)
        for (auto &t : _towers) {
            _window.draw(t.getSprite());
        }

    }

    Tower& TowerMan::getTowerAt(TilePoint location) {
        for (auto &t : _towers) {
            //if (location == t.getPos())
                return t;
        }
    }

    bool TowerMan::_hasMonsterInRange(Tower &tower) {
        //TODO: write _hasMonsterInRange
        return true;
    }

    void TowerMan::onButtonClick(ButtonClickEvent event) {
        //TODO: Implement onButtonClick
    }

    void TowerMan::createTower(TowerType type, float x, float y) {
        Tower t(type, x, y);
        _towers.push_back(t);
    }
}
<commit_msg>Added json import<commit_after>//
// Created by ariel on 11/6/16.
//
#include "Tower/TowerMan.h"
#include <lib/json.hpp>

using std::vector;
using std::cout;
using std::endl;

namespace Towers {
    TowerMan::TowerMan(sf::RenderWindow &window, MonsterMan &monsterMan)
            : _towers(), _window(window),
              _monsterMan(&monsterMan) {
        _fireInterval = sf::seconds(0.7f);
        _fireAnimationInterval = sf::seconds(0.05f);

        Tower::_normalTexture.loadFromFile("Resources/Textures/Tower-lvl1.png");
        Tower::_firingTexture.loadFromFile("Resources/Textures/Tower-lvl1-fire.png");
        Tower::_fireSoundBuffer.loadFromFile("Resources/Sounds/TowerFireSound-1.wav");
    }

    void TowerMan::update() {
        //TODO: Loop through button events, perform actions on towers based on button clicks
        sf::Time currentElapsed = _fireClock.getElapsedTime();

        for (auto &t : _towers) {
            if (t.getHealth() <= 0 && !t.shouldDestroy())
                t.destroy();

            if ((currentElapsed - t.getLastFireTime()) >= _fireInterval && _hasMonsterInRange(t))
                t.startFire(currentElapsed);
            else if ((currentElapsed - t.getLastFireTime()) >= _fireAnimationInterval && t.isFiring())
                t.stopFire(currentElapsed);

			t.setTarget(_monsterMan->getMonstersInRange(t.getSprite().getPosition(), 10000));

            t.update();
        }
    }

    void TowerMan::render() {
        //TODO: Perform pre-tower-render events (buttons, etc)
        for (auto &t : _towers) {
            _window.draw(t.getSprite());
        }

    }

    Tower& TowerMan::getTowerAt(TilePoint location) {
        for (auto &t : _towers) {
            //if (location == t.getPos())
                return t;
        }
    }

    bool TowerMan::_hasMonsterInRange(Tower &tower) {
        //TODO: write _hasMonsterInRange
        return true;
    }

    void TowerMan::onButtonClick(ButtonClickEvent event) {
        //TODO: Implement onButtonClick
    }

    void TowerMan::createTower(TowerType type, float x, float y) {
        Tower t(type, x, y);
        _towers.push_back(t);
    }
}
<|endoftext|>


<commit_before>// TransformTools.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "TransformTools.h"
#include "MarkedList.h"
#include "HLine.h"
#include "HILine.h"
#include "HeeksConfig.h"

//static double from[3];
static double centre[3];

//static
void TransformTools::RemoveUncopyable()
{
	std::list<HeeksObj*> uncopyable_objects;
	for(std::list<HeeksObj*>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
	{
		HeeksObj* object = *It;
		if(!object->CanBeCopied())uncopyable_objects.push_back(object);
	}
	if(uncopyable_objects.size() > 0)wxGetApp().m_marked_list->Remove(uncopyable_objects, true);
}

//static
void TransformTools::Translate(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to move"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	HeeksConfig config;
	int ncopies;
	config.Read(_T("TranslateNumCopies"), &ncopies, 1);
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	double from[3], to[3];
	config.Read(_T("TranslateFromX"), &from[0], 0.0);
	config.Read(_T("TranslateFromY"), &from[1], 0.0);
	config.Read(_T("TranslateFromZ"), &from[2], 0.0);
	config.Read(_T("TranslateToX"), &to[0], 0.0);
	config.Read(_T("TranslateToY"), &to[1], 0.0);
	config.Read(_T("TranslateToZ"), &to[2], 0.0);

	if(!wxGetApp().InputFromAndTo(from, to, copy ? &ncopies : NULL))return;

	if(copy)
	{
		if(ncopies < 1)return;
		config.Write(_T("TranslateNumCopies"), ncopies);
	}
	config.Write(_T("TranslateFromX"), from[0]);
	config.Write(_T("TranslateFromY"), from[1]);
	config.Write(_T("TranslateFromZ"), from[2]);
	config.Write(_T("TranslateToX"), to[0]);
	config.Write(_T("TranslateToY"), to[1]);
	config.Write(_T("TranslateToZ"), to[2]);

	wxGetApp().StartHistory();

	// transform the objects
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetTranslationPart(make_vector(make_point(from), make_point(to)) * (i + 1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				object->m_owner->Add(new_object, NULL);
				wxGetApp().TransformUndoably(new_object, m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetTranslationPart(make_vector(make_point(from), make_point(to)));
		double m[16];
		extract(mat, m);
		wxGetApp().TransformUndoably(selected_items, m);
	}

	wxGetApp().EndHistory();
}

//static
void TransformTools::Rotate(bool copy)
{
	//rotation axis - Z axis by default
	gp_Dir axis_Dir = gp_Dir(0,0,1);
	gp_Pnt line_Pos = gp_Pnt(0,0,0);

	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to rotate"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	HeeksConfig config;
	int ncopies;
	config.Read(_T("RotateNumCopies"), &ncopies, 1);
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	double angle;
	config.Read(_T("RotateAngle"), &angle, 90.0);

	// enter angle, plane and position
	double axis[3];
	double pos[3];
	config.Read(_T("RotateAxisX"), &axis[0], 0.0);
	config.Read(_T("RotateAxisY"), &axis[1], 0.0);
	config.Read(_T("RotateAxisZ"), &axis[2], 1.0);
	config.Read(_T("RotatePosX"), &pos[0], 0.0);
	config.Read(_T("RotatePosY"), &pos[1], 0.0);
	config.Read(_T("RotatePosZ"), &pos[2], 0.0);

	double axial_shift;
	config.Read(_T("RotateAxialShift"), &axial_shift, 0.0);

	if(!wxGetApp().InputAngleWithPlane(angle, axis, pos, copy ? &ncopies : NULL, &axial_shift))return;
	if(copy)
	{
		if(ncopies < 1)return;
		config.Write(_T("RotateNumCopies"), ncopies);
	}
	config.Write(_T("RotateAngle"), angle);
	config.Write(_T("RotateAxialShift"), axial_shift);
	config.Write(_T("RotateAxisX"), axis[0]);
	config.Write(_T("RotateAxisY"), axis[1]);
	config.Write(_T("RotateAxisZ"), axis[2]);
	config.Write(_T("RotatePosX"), pos[0]);
	config.Write(_T("RotatePosY"), pos[1]);
	config.Write(_T("RotatePosZ"), pos[2]);
	axis_Dir = gp_Dir(axis[0], axis[1], axis[2]);
	line_Pos = gp_Pnt(pos[0], pos[1], pos[2]);

	// transform the objects
	wxGetApp().StartHistory();
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetRotation(gp_Ax1(line_Pos, axis_Dir), angle * M_PI/180 * (i+1));
			gp_Trsf tmat;
			tmat.SetTranslation(gp_Vec(axis_Dir.XYZ() * (axial_shift * ((double)(i+1)) / ncopies)));
			mat = tmat * mat;
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				wxGetApp().TransformUndoably(new_object, m);             // Rotate the duplicate object.
				wxGetApp().AddUndoably(new_object, object->m_owner, NULL);// And add it to this object's owner
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetRotation(gp_Ax1(line_Pos, axis_Dir), angle * M_PI/180);
		gp_Trsf tmat;
		tmat.SetTranslation(gp_Vec(axis_Dir.XYZ() * axial_shift));
		mat = tmat * mat;
		double m[16];
		extract(mat, m);
		wxGetApp().Transform(selected_items, m);
	}
	wxGetApp().EndHistory();
}

//static
void TransformTools::Mirror(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to mirror"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick a line to mirror about
	bool line_found = false;
	gp_Lin line;
	int save_filter = wxGetApp().m_marked_list->m_filter;
	wxGetApp().PickObjects(_("Pick line to mirror about"), MARKING_FILTER_LINE | MARKING_FILTER_ILINE, true);
	wxGetApp().m_marked_list->m_filter = save_filter;
	for(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == LineType)
		{
			line = ((HLine*)object)->GetLine();
			line_found = true;
		}
		else if(object->GetType() == ILineType)
		{
			line = ((HILine*)object)->GetLine();
			line_found = true;
		}
	}
	if(!line_found)return;

	// transform the objects
	wxGetApp().StartHistory();
	gp_Trsf mat;
	mat.SetMirror(gp_Ax1(line.Location(), line.Direction()));
	double m[16];
	extract(mat, m);

	if(copy)
	{
		for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
		{
			HeeksObj* object = *It;
			HeeksObj* new_object = object->MakeACopy();
			wxGetApp().AddUndoably(new_object, object->m_owner, NULL);
			wxGetApp().TransformUndoably(new_object, m);
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		wxGetApp().TransformUndoably(selected_items, m);
	}
	wxGetApp().EndHistory();
}

void TransformTools::Scale(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to scale"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	int ncopies;
	HeeksConfig config;
	config.Read(_T("ScaleNumCopies"), &ncopies, 1);
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		if(!wxGetApp().InputInt(_("Enter number of copies"), _("number of copies"), ncopies))return;
		if(ncopies < 1)return;
		config.Write(_T("ScaleNumCopies"), ncopies);
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick "centre" position
	if(!wxGetApp().PickPosition(_("Click centre position to scale about"), centre))return;

	// enter scale factor
	double scale;
	config.Read(_T("ScaleFactor"), &scale, 2.0);
	if(!wxGetApp().InputDouble(_("Enter scale factor"), _("scale factor"), scale))return;
	config.Write(_T("ScaleFactor"), scale);

	// transform the objects
	wxGetApp().StartHistory();
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetScale(make_point(centre), scale * (i+1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				wxGetApp().AddUndoably(new_object, object->m_owner, NULL);
				wxGetApp().TransformUndoably(new_object, m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetScale(make_point(centre), scale);
		double m[16];
		extract(mat, m);
		wxGetApp().TransformUndoably(selected_items, m);
	}
	wxGetApp().EndHistory();
}
<commit_msg>3d rotate was not undoable!<commit_after>// TransformTools.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "TransformTools.h"
#include "MarkedList.h"
#include "HLine.h"
#include "HILine.h"
#include "HeeksConfig.h"

//static double from[3];
static double centre[3];

//static
void TransformTools::RemoveUncopyable()
{
	std::list<HeeksObj*> uncopyable_objects;
	for(std::list<HeeksObj*>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
	{
		HeeksObj* object = *It;
		if(!object->CanBeCopied())uncopyable_objects.push_back(object);
	}
	if(uncopyable_objects.size() > 0)wxGetApp().m_marked_list->Remove(uncopyable_objects, true);
}

//static
void TransformTools::Translate(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to move"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	HeeksConfig config;
	int ncopies;
	config.Read(_T("TranslateNumCopies"), &ncopies, 1);
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	double from[3], to[3];
	config.Read(_T("TranslateFromX"), &from[0], 0.0);
	config.Read(_T("TranslateFromY"), &from[1], 0.0);
	config.Read(_T("TranslateFromZ"), &from[2], 0.0);
	config.Read(_T("TranslateToX"), &to[0], 0.0);
	config.Read(_T("TranslateToY"), &to[1], 0.0);
	config.Read(_T("TranslateToZ"), &to[2], 0.0);

	if(!wxGetApp().InputFromAndTo(from, to, copy ? &ncopies : NULL))return;

	if(copy)
	{
		if(ncopies < 1)return;
		config.Write(_T("TranslateNumCopies"), ncopies);
	}
	config.Write(_T("TranslateFromX"), from[0]);
	config.Write(_T("TranslateFromY"), from[1]);
	config.Write(_T("TranslateFromZ"), from[2]);
	config.Write(_T("TranslateToX"), to[0]);
	config.Write(_T("TranslateToY"), to[1]);
	config.Write(_T("TranslateToZ"), to[2]);

	wxGetApp().StartHistory();

	// transform the objects
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetTranslationPart(make_vector(make_point(from), make_point(to)) * (i + 1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				object->m_owner->Add(new_object, NULL);
				wxGetApp().TransformUndoably(new_object, m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetTranslationPart(make_vector(make_point(from), make_point(to)));
		double m[16];
		extract(mat, m);
		wxGetApp().TransformUndoably(selected_items, m);
	}

	wxGetApp().EndHistory();
}

//static
void TransformTools::Rotate(bool copy)
{
	//rotation axis - Z axis by default
	gp_Dir axis_Dir = gp_Dir(0,0,1);
	gp_Pnt line_Pos = gp_Pnt(0,0,0);

	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to rotate"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	HeeksConfig config;
	int ncopies;
	config.Read(_T("RotateNumCopies"), &ncopies, 1);
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	double angle;
	config.Read(_T("RotateAngle"), &angle, 90.0);

	// enter angle, plane and position
	double axis[3];
	double pos[3];
	config.Read(_T("RotateAxisX"), &axis[0], 0.0);
	config.Read(_T("RotateAxisY"), &axis[1], 0.0);
	config.Read(_T("RotateAxisZ"), &axis[2], 1.0);
	config.Read(_T("RotatePosX"), &pos[0], 0.0);
	config.Read(_T("RotatePosY"), &pos[1], 0.0);
	config.Read(_T("RotatePosZ"), &pos[2], 0.0);

	double axial_shift;
	config.Read(_T("RotateAxialShift"), &axial_shift, 0.0);

	if(!wxGetApp().InputAngleWithPlane(angle, axis, pos, copy ? &ncopies : NULL, &axial_shift))return;
	if(copy)
	{
		if(ncopies < 1)return;
		config.Write(_T("RotateNumCopies"), ncopies);
	}
	config.Write(_T("RotateAngle"), angle);
	config.Write(_T("RotateAxialShift"), axial_shift);
	config.Write(_T("RotateAxisX"), axis[0]);
	config.Write(_T("RotateAxisY"), axis[1]);
	config.Write(_T("RotateAxisZ"), axis[2]);
	config.Write(_T("RotatePosX"), pos[0]);
	config.Write(_T("RotatePosY"), pos[1]);
	config.Write(_T("RotatePosZ"), pos[2]);
	axis_Dir = gp_Dir(axis[0], axis[1], axis[2]);
	line_Pos = gp_Pnt(pos[0], pos[1], pos[2]);

	// transform the objects
	wxGetApp().StartHistory();
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetRotation(gp_Ax1(line_Pos, axis_Dir), angle * M_PI/180 * (i+1));
			gp_Trsf tmat;
			tmat.SetTranslation(gp_Vec(axis_Dir.XYZ() * (axial_shift * ((double)(i+1)) / ncopies)));
			mat = tmat * mat;
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				wxGetApp().TransformUndoably(new_object, m);             // Rotate the duplicate object.
				wxGetApp().AddUndoably(new_object, object->m_owner, NULL);// And add it to this object's owner
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetRotation(gp_Ax1(line_Pos, axis_Dir), angle * M_PI/180);
		gp_Trsf tmat;
		tmat.SetTranslation(gp_Vec(axis_Dir.XYZ() * axial_shift));
		mat = tmat * mat;
		double m[16];
		extract(mat, m);
		wxGetApp().TransformUndoably(selected_items, m);
	}
	wxGetApp().EndHistory();
}

//static
void TransformTools::Mirror(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to mirror"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick a line to mirror about
	bool line_found = false;
	gp_Lin line;
	int save_filter = wxGetApp().m_marked_list->m_filter;
	wxGetApp().PickObjects(_("Pick line to mirror about"), MARKING_FILTER_LINE | MARKING_FILTER_ILINE, true);
	wxGetApp().m_marked_list->m_filter = save_filter;
	for(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == LineType)
		{
			line = ((HLine*)object)->GetLine();
			line_found = true;
		}
		else if(object->GetType() == ILineType)
		{
			line = ((HILine*)object)->GetLine();
			line_found = true;
		}
	}
	if(!line_found)return;

	// transform the objects
	wxGetApp().StartHistory();
	gp_Trsf mat;
	mat.SetMirror(gp_Ax1(line.Location(), line.Direction()));
	double m[16];
	extract(mat, m);

	if(copy)
	{
		for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
		{
			HeeksObj* object = *It;
			HeeksObj* new_object = object->MakeACopy();
			wxGetApp().AddUndoably(new_object, object->m_owner, NULL);
			wxGetApp().TransformUndoably(new_object, m);
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		wxGetApp().TransformUndoably(selected_items, m);
	}
	wxGetApp().EndHistory();
}

void TransformTools::Scale(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to scale"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	int ncopies;
	HeeksConfig config;
	config.Read(_T("ScaleNumCopies"), &ncopies, 1);
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		if(!wxGetApp().InputInt(_("Enter number of copies"), _("number of copies"), ncopies))return;
		if(ncopies < 1)return;
		config.Write(_T("ScaleNumCopies"), ncopies);
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick "centre" position
	if(!wxGetApp().PickPosition(_("Click centre position to scale about"), centre))return;

	// enter scale factor
	double scale;
	config.Read(_T("ScaleFactor"), &scale, 2.0);
	if(!wxGetApp().InputDouble(_("Enter scale factor"), _("scale factor"), scale))return;
	config.Write(_T("ScaleFactor"), scale);

	// transform the objects
	wxGetApp().StartHistory();
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetScale(make_point(centre), scale * (i+1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				wxGetApp().AddUndoably(new_object, object->m_owner, NULL);
				wxGetApp().TransformUndoably(new_object, m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetScale(make_point(centre), scale);
		double m[16];
		extract(mat, m);
		wxGetApp().TransformUndoably(selected_items, m);
	}
	wxGetApp().EndHistory();
}
<|endoftext|>


<commit_before>// JsonTMXImporter.hpp
// Panic! Medieval
//
// Dan Alexander 08/29/14
// Copyright(c) 2014
//
/* JsonTMXImporter
 *
 * This class handles importing levels from
 * TMX json files.
 */

#ifndef JSONTMXIMPORTER_HPP
#define JSONTMXIMPORTER_HPP

#include "LevelImporter.hpp" // parent class
#include <string>
#include <map>
#include <vector>
#include "TMXMiddleware.hpp"
#include "tiledjsonconsts.hpp"

namespace TILEDJSON_NAMESPACE
{

class JsonTMXImporter : public LevelImporter
{
private:
	std::string getFileContents(const char *filename);

	TMXMapDetails		mMapDetails;

	bool				mMapDetailsLoaded;

public:
	JsonTMXImporter();
	~JsonTMXImporter();

	bool load(const char *filename);

	bool loadTMXJson(const char *filename);

	int getMapWidth();
	int getMapHeight();
	int getMapUnitWidth() { return mMapDetails.TileWidth; }
	int getMapUnitHeight() { return mMapDetails.TileHeight; }

	std::map<std::string, std::string> getMapProperties();

	std::vector<MapLayer*> getLayers();

	TilePropertyGidMap getTileProperties();

	std::vector<MapTileSet> getTileSets();

};

}

#endif // JSONTMXIMPORTER_HPP
<commit_msg>removed unused method declaration<commit_after>// JsonTMXImporter.hpp
// Panic! Medieval
//
// Dan Alexander 08/29/14
// Copyright(c) 2014
//
/* JsonTMXImporter
 *
 * This class handles importing levels from
 * TMX json files.
 */

#ifndef JSONTMXIMPORTER_HPP
#define JSONTMXIMPORTER_HPP

#include "LevelImporter.hpp" // parent class
#include <string>
#include <map>
#include <vector>
#include "TMXMiddleware.hpp"
#include "tiledjsonconsts.hpp"

namespace TILEDJSON_NAMESPACE
{

class JsonTMXImporter : public LevelImporter
{
private:

	TMXMapDetails		mMapDetails;

	bool				mMapDetailsLoaded;

public:
	JsonTMXImporter();
	~JsonTMXImporter();

	bool load(const char *filename);

	bool loadTMXJson(const char *filename);

	int getMapWidth();
	int getMapHeight();
	int getMapUnitWidth() { return mMapDetails.TileWidth; }
	int getMapUnitHeight() { return mMapDetails.TileHeight; }

	std::map<std::string, std::string> getMapProperties();

	std::vector<MapLayer*> getLayers();

	TilePropertyGidMap getTileProperties();

	std::vector<MapTileSet> getTileSets();

};

}

#endif // JSONTMXIMPORTER_HPP
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.11  2003/10/17 21:14:30  peiyongz
 * using XTemplateSerializer
 *
 * Revision 1.10  2003/10/14 15:20:42  peiyongz
 * Implementation of Serialization/Deserialization
 *
 * Revision 1.9  2003/09/22 19:49:02  neilg
 * implement change to Grammar::putElem(XMLElementDecl, bool).  If Grammars are used only to hold declared objects, there will be no need for the fElemNonDeclPool tables; make Grammar implementations lazily create them only if the application requires them (which good cpplications should not.)
 *
 * Revision 1.8  2003/08/14 03:00:46  knoaman
 * Code refactoring to improve performance of validation.
 *
 * Revision 1.7  2003/07/31 17:09:59  peiyongz
 * Grammar embed grammar description
 *
 * Revision 1.6  2003/05/18 14:02:06  knoaman
 * Memory manager implementation: pass per instance manager.
 *
 * Revision 1.5  2003/05/15 18:54:50  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2002/12/04 02:47:25  knoaman
 * scanner re-organization.
 *
 * Revision 1.3  2002/11/04 14:50:40  tng
 * C++ Namespace Support.
 *
 * Revision 1.2  2002/07/11 18:19:28  knoaman
 * Grammar caching/preparsing - initial implementation.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:43  peiyongz
 * sane_include
 *
 * Revision 1.4  2001/09/14 14:50:22  tng
 * Schema: Fix some wildcard bugs, and some retrieving qualified/unqualified element decl problems.
 *
 * Revision 1.3  2001/05/11 13:27:08  tng
 * Copyright update.
 *
 * Revision 1.2  2001/04/19 18:17:20  tng
 * Schema: SchemaValidator update, and use QName in Content Model
 *
 * Revision 1.1  2001/03/21 21:56:20  tng
 * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/validators/DTD/DTDGrammar.hpp>
#include <xercesc/validators/DTD/XMLDTDDescriptionImpl.hpp>

#include <xercesc/internal/XTemplateSerializer.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  DTDGrammar: Static member data
// ---------------------------------------------------------------------------
NameIdPool<DTDEntityDecl>* DTDGrammar::fDefaultEntities = 0;

//---------------------------------------------------------------------------
//  DTDGrammar: Constructors and Destructor
// ---------------------------------------------------------------------------
DTDGrammar::DTDGrammar(MemoryManager* const manager) :
    fMemoryManager(manager)
    , fElemDeclPool(0)
    , fElemNonDeclPool(0)
    , fEntityDeclPool(0)
    , fNotationDeclPool(0)
    , fValidated(false)
    , fGramDesc(0)
{
    //
    //  Init all the pool members.
    //
    //  <TBD> Investigate what the optimum values would be for the various
    //  pools.
    //
    fElemDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(109, 128, fMemoryManager);
    // should not need this in the common situation where grammars
    // are built once and then read - NG
    //fElemNonDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(29, 128, fMemoryManager);
    fEntityDeclPool = new (fMemoryManager) NameIdPool<DTDEntityDecl>(109, 128, fMemoryManager);
    fNotationDeclPool = new (fMemoryManager) NameIdPool<XMLNotationDecl>(109, 128, fMemoryManager);

    //REVISIT: use grammarPool to create
    fGramDesc = new (fMemoryManager) XMLDTDDescriptionImpl(XMLUni::fgDTDEntityString, fMemoryManager);

    // Create default entities
    resetEntityDeclPool();
}

DTDGrammar::~DTDGrammar()
{
    delete fElemDeclPool;
    if(fElemNonDeclPool)
    {
        delete fElemNonDeclPool;
    }
    delete fEntityDeclPool;
    delete fNotationDeclPool;
    delete fGramDesc;
}

// -----------------------------------------------------------------------
//  Notification that lazy data has been deleted
// -----------------------------------------------------------------------
void DTDGrammar::reinitDfltEntities() {
	delete fDefaultEntities;
	fDefaultEntities = 0;
}

// -----------------------------------------------------------------------
//  Virtual methods
// -----------------------------------------------------------------------
XMLElementDecl* DTDGrammar::findOrAddElemDecl (const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    prefixName
        , const XMLCh* const    qName
        , unsigned int          scope
        ,       bool&           wasAdded )
{
    // See it it exists
    DTDElementDecl* retVal = (DTDElementDecl*) getElemDecl(uriId, baseName, qName, scope);

    // if not, then add this in
    if (!retVal)
    {
        retVal = new (fMemoryManager) DTDElementDecl
        (
            qName
            , uriId
            , DTDElementDecl::Any
            , fMemoryManager
        );
        if(!fElemNonDeclPool)
            fElemNonDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(29, 128, fMemoryManager);
        const unsigned int elemId = fElemNonDeclPool->put(retVal);
        retVal->setId(elemId);
        wasAdded = true;
    }
     else
    {
        wasAdded = false;
    }
    return retVal;
}

XMLElementDecl* DTDGrammar::putElemDecl (const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    prefixName
        , const XMLCh* const    qName
        , unsigned int          scope
        , const bool            notDeclared)
{
    DTDElementDecl* retVal = new (fMemoryManager) DTDElementDecl
    (
        qName
        , uriId
        , DTDElementDecl::Any
        , fMemoryManager
    );
    if(notDeclared)
    {
        if(!fElemNonDeclPool)
            fElemNonDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(29, 128, fMemoryManager);
        retVal->setId(fElemNonDeclPool->put(retVal));
    } else
    {
        retVal->setId(fElemDeclPool->put(retVal));
    }
    return retVal;
}

void DTDGrammar::reset()
{
    //
    //  We need to reset all of the pools.
    //
    fElemDeclPool->removeAll();
    // now that we have this, no point in deleting it...
    if(fElemNonDeclPool)
        fElemNonDeclPool->removeAll();
    fNotationDeclPool->removeAll();
    fEntityDeclPool->removeAll();
    fValidated = false;
}

void DTDGrammar::resetEntityDeclPool() {

    static XMLRegisterCleanup builtInRegistryCleanup;

    // Initialize default entities if not initialized
    if (fDefaultEntities == 0) {

        NameIdPool<DTDEntityDecl>* t = new NameIdPool<DTDEntityDecl>(11, 12);

        if (XMLPlatformUtils::compareAndSwap((void **)&fDefaultEntities, t, 0) != 0)
        {
            delete t;
        }
        else
        {
            builtInRegistryCleanup.registerCleanup(reinitDfltEntities);

            //
            // Add the default entity entries for the character refs that must
            // always be present. We indicate that they are from the internal
            // subset. They aren't really, but they have to look that way so
            // that they are still valid for use within a standalone document.
            //
            // We also mark them as special char entities, which allows them
            // to be used in places whether other non-numeric general entities
            // cannot.
            //
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgAmp, chAmpersand, true, true));
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgLT, chOpenAngle, true, true));
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgGT, chCloseAngle, true, true));
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgQuot, chDoubleQuote, true, true));
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgApos, chSingleQuote, true, true));
        }
    }
}

void DTDGrammar::setGrammarDescription( XMLGrammarDescription* gramDesc)
{
    if ((!gramDesc) ||
        (gramDesc->getGrammarType() != Grammar::DTDGrammarType))
        return;

    if (fGramDesc)
        delete fGramDesc;

    //adopt the grammar Description
    fGramDesc = (XMLDTDDescription*) gramDesc;
}

XMLGrammarDescription*  DTDGrammar::getGrammarDescription() const
{
    return fGramDesc;
}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(DTDGrammar)

void DTDGrammar::serialize(XSerializeEngine& serEng)
{

    Grammar::serialize(serEng);

    //don't serialize fDefaultEntities

    if (serEng.isStoring())
    {
        /***
         *
         * Serialize NameIdPool<DTDElementDecl>*       fElemDeclPool;
         * Serialize NameIdPool<DTDElementDecl>*       fElemNonDeclPool;
         * Serialize NameIdPool<DTDEntityDecl>*        fEntityDeclPool;
         * Serialize NameIdPool<XMLNotationDecl>*      fNotationDeclPool;
         ***/
        XTemplateSerializer::storeObject(fElemDeclPool, serEng);
        XTemplateSerializer::storeObject(fElemNonDeclPool, serEng); //TODO: to be removed
        XTemplateSerializer::storeObject(fEntityDeclPool, serEng);
        XTemplateSerializer::storeObject(fNotationDeclPool, serEng);

        serEng<<fRootElemId;
        serEng<<fValidated;
        serEng<<fGramDesc;

    }
    else
    {

       /***
         *
         * Deserialize NameIdPool<DTDElementDecl>*       fElemDeclPool;
         * Deserialize NameIdPool<DTDElementDecl>*       fElemNonDeclPool;
         * Deserialize NameIdPool<DTDEntityDecl>*        fEntityDeclPool;
         * Deerialize NameIdPool<XMLNotationDecl>*       fNotationDeclPool;
         ***/
        XTemplateSerializer::loadObject(&fElemDeclPool, 109, 128, serEng);
        XTemplateSerializer::loadObject(&fElemNonDeclPool, 109, 128, serEng); //TODO: to be removed
        XTemplateSerializer::loadObject(&fEntityDeclPool, 109, 128, serEng);
        XTemplateSerializer::loadObject(&fNotationDeclPool, 109, 128, serEng);

        serEng>>fRootElemId;
        serEng>>fValidated;

        XMLDTDDescriptionImpl* gramDesc;
        serEng>>gramDesc;
        fGramDesc = gramDesc;

    }

}

XERCES_CPP_NAMESPACE_END
<commit_msg>initialize data member<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.12  2003/11/06 15:03:45  peiyongz
 * initialize data member
 *
 * Revision 1.11  2003/10/17 21:14:30  peiyongz
 * using XTemplateSerializer
 *
 * Revision 1.10  2003/10/14 15:20:42  peiyongz
 * Implementation of Serialization/Deserialization
 *
 * Revision 1.9  2003/09/22 19:49:02  neilg
 * implement change to Grammar::putElem(XMLElementDecl, bool).  If Grammars are used only to hold declared objects, there will be no need for the fElemNonDeclPool tables; make Grammar implementations lazily create them only if the application requires them (which good cpplications should not.)
 *
 * Revision 1.8  2003/08/14 03:00:46  knoaman
 * Code refactoring to improve performance of validation.
 *
 * Revision 1.7  2003/07/31 17:09:59  peiyongz
 * Grammar embed grammar description
 *
 * Revision 1.6  2003/05/18 14:02:06  knoaman
 * Memory manager implementation: pass per instance manager.
 *
 * Revision 1.5  2003/05/15 18:54:50  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2002/12/04 02:47:25  knoaman
 * scanner re-organization.
 *
 * Revision 1.3  2002/11/04 14:50:40  tng
 * C++ Namespace Support.
 *
 * Revision 1.2  2002/07/11 18:19:28  knoaman
 * Grammar caching/preparsing - initial implementation.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:43  peiyongz
 * sane_include
 *
 * Revision 1.4  2001/09/14 14:50:22  tng
 * Schema: Fix some wildcard bugs, and some retrieving qualified/unqualified element decl problems.
 *
 * Revision 1.3  2001/05/11 13:27:08  tng
 * Copyright update.
 *
 * Revision 1.2  2001/04/19 18:17:20  tng
 * Schema: SchemaValidator update, and use QName in Content Model
 *
 * Revision 1.1  2001/03/21 21:56:20  tng
 * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/validators/DTD/DTDGrammar.hpp>
#include <xercesc/validators/DTD/XMLDTDDescriptionImpl.hpp>

#include <xercesc/internal/XTemplateSerializer.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  DTDGrammar: Static member data
// ---------------------------------------------------------------------------
NameIdPool<DTDEntityDecl>* DTDGrammar::fDefaultEntities = 0;

//---------------------------------------------------------------------------
//  DTDGrammar: Constructors and Destructor
// ---------------------------------------------------------------------------
DTDGrammar::DTDGrammar(MemoryManager* const manager) :
    fMemoryManager(manager)
    , fElemDeclPool(0)
    , fElemNonDeclPool(0)
    , fEntityDeclPool(0)
    , fNotationDeclPool(0)
    , fRootElemId(0)
    , fValidated(false)
    , fGramDesc(0)
{
    //
    //  Init all the pool members.
    //
    //  <TBD> Investigate what the optimum values would be for the various
    //  pools.
    //
    fElemDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(109, 128, fMemoryManager);
    // should not need this in the common situation where grammars
    // are built once and then read - NG
    //fElemNonDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(29, 128, fMemoryManager);
    fEntityDeclPool = new (fMemoryManager) NameIdPool<DTDEntityDecl>(109, 128, fMemoryManager);
    fNotationDeclPool = new (fMemoryManager) NameIdPool<XMLNotationDecl>(109, 128, fMemoryManager);

    //REVISIT: use grammarPool to create
    fGramDesc = new (fMemoryManager) XMLDTDDescriptionImpl(XMLUni::fgDTDEntityString, fMemoryManager);

    // Create default entities
    resetEntityDeclPool();
}

DTDGrammar::~DTDGrammar()
{
    delete fElemDeclPool;
    if(fElemNonDeclPool)
    {
        delete fElemNonDeclPool;
    }
    delete fEntityDeclPool;
    delete fNotationDeclPool;
    delete fGramDesc;
}

// -----------------------------------------------------------------------
//  Notification that lazy data has been deleted
// -----------------------------------------------------------------------
void DTDGrammar::reinitDfltEntities() {
	delete fDefaultEntities;
	fDefaultEntities = 0;
}

// -----------------------------------------------------------------------
//  Virtual methods
// -----------------------------------------------------------------------
XMLElementDecl* DTDGrammar::findOrAddElemDecl (const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    prefixName
        , const XMLCh* const    qName
        , unsigned int          scope
        ,       bool&           wasAdded )
{
    // See it it exists
    DTDElementDecl* retVal = (DTDElementDecl*) getElemDecl(uriId, baseName, qName, scope);

    // if not, then add this in
    if (!retVal)
    {
        retVal = new (fMemoryManager) DTDElementDecl
        (
            qName
            , uriId
            , DTDElementDecl::Any
            , fMemoryManager
        );
        if(!fElemNonDeclPool)
            fElemNonDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(29, 128, fMemoryManager);
        const unsigned int elemId = fElemNonDeclPool->put(retVal);
        retVal->setId(elemId);
        wasAdded = true;
    }
     else
    {
        wasAdded = false;
    }
    return retVal;
}

XMLElementDecl* DTDGrammar::putElemDecl (const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    prefixName
        , const XMLCh* const    qName
        , unsigned int          scope
        , const bool            notDeclared)
{
    DTDElementDecl* retVal = new (fMemoryManager) DTDElementDecl
    (
        qName
        , uriId
        , DTDElementDecl::Any
        , fMemoryManager
    );
    if(notDeclared)
    {
        if(!fElemNonDeclPool)
            fElemNonDeclPool = new (fMemoryManager) NameIdPool<DTDElementDecl>(29, 128, fMemoryManager);
        retVal->setId(fElemNonDeclPool->put(retVal));
    } else
    {
        retVal->setId(fElemDeclPool->put(retVal));
    }
    return retVal;
}

void DTDGrammar::reset()
{
    //
    //  We need to reset all of the pools.
    //
    fElemDeclPool->removeAll();
    // now that we have this, no point in deleting it...
    if(fElemNonDeclPool)
        fElemNonDeclPool->removeAll();
    fNotationDeclPool->removeAll();
    fEntityDeclPool->removeAll();
    fValidated = false;
}

void DTDGrammar::resetEntityDeclPool() {

    static XMLRegisterCleanup builtInRegistryCleanup;

    // Initialize default entities if not initialized
    if (fDefaultEntities == 0) {

        NameIdPool<DTDEntityDecl>* t = new NameIdPool<DTDEntityDecl>(11, 12);

        if (XMLPlatformUtils::compareAndSwap((void **)&fDefaultEntities, t, 0) != 0)
        {
            delete t;
        }
        else
        {
            builtInRegistryCleanup.registerCleanup(reinitDfltEntities);

            //
            // Add the default entity entries for the character refs that must
            // always be present. We indicate that they are from the internal
            // subset. They aren't really, but they have to look that way so
            // that they are still valid for use within a standalone document.
            //
            // We also mark them as special char entities, which allows them
            // to be used in places whether other non-numeric general entities
            // cannot.
            //
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgAmp, chAmpersand, true, true));
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgLT, chOpenAngle, true, true));
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgGT, chCloseAngle, true, true));
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgQuot, chDoubleQuote, true, true));
            fDefaultEntities->put(new DTDEntityDecl(XMLUni::fgApos, chSingleQuote, true, true));
        }
    }
}

void DTDGrammar::setGrammarDescription( XMLGrammarDescription* gramDesc)
{
    if ((!gramDesc) ||
        (gramDesc->getGrammarType() != Grammar::DTDGrammarType))
        return;

    if (fGramDesc)
        delete fGramDesc;

    //adopt the grammar Description
    fGramDesc = (XMLDTDDescription*) gramDesc;
}

XMLGrammarDescription*  DTDGrammar::getGrammarDescription() const
{
    return fGramDesc;
}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(DTDGrammar)

void DTDGrammar::serialize(XSerializeEngine& serEng)
{

    Grammar::serialize(serEng);

    //don't serialize fDefaultEntities

    if (serEng.isStoring())
    {
        /***
         *
         * Serialize NameIdPool<DTDElementDecl>*       fElemDeclPool;
         * Serialize NameIdPool<DTDElementDecl>*       fElemNonDeclPool;
         * Serialize NameIdPool<DTDEntityDecl>*        fEntityDeclPool;
         * Serialize NameIdPool<XMLNotationDecl>*      fNotationDeclPool;
         ***/
        XTemplateSerializer::storeObject(fElemDeclPool, serEng);
        XTemplateSerializer::storeObject(fElemNonDeclPool, serEng); //TODO: to be removed
        XTemplateSerializer::storeObject(fEntityDeclPool, serEng);
        XTemplateSerializer::storeObject(fNotationDeclPool, serEng);

        serEng<<fRootElemId;
        serEng<<fValidated;
        serEng<<fGramDesc;

    }
    else
    {

       /***
         *
         * Deserialize NameIdPool<DTDElementDecl>*       fElemDeclPool;
         * Deserialize NameIdPool<DTDElementDecl>*       fElemNonDeclPool;
         * Deserialize NameIdPool<DTDEntityDecl>*        fEntityDeclPool;
         * Deerialize NameIdPool<XMLNotationDecl>*       fNotationDeclPool;
         ***/
        XTemplateSerializer::loadObject(&fElemDeclPool, 109, 128, serEng);
        XTemplateSerializer::loadObject(&fElemNonDeclPool, 109, 128, serEng); //TODO: to be removed
        XTemplateSerializer::loadObject(&fEntityDeclPool, 109, 128, serEng);
        XTemplateSerializer::loadObject(&fNotationDeclPool, 109, 128, serEng);

        serEng>>fRootElemId;
        serEng>>fValidated;

        XMLDTDDescriptionImpl* gramDesc;
        serEng>>gramDesc;
        fGramDesc = gramDesc;

    }

}

XERCES_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>Matrix3i m = Matrix3i::Random();
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Here is m.minor(1,1):" << endl << m.minor(1,1) << endl;
<commit_msg>Remove doc/snippets/MatrixBase_minor.cpp because minor() was removed.<commit_after><|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include <pcap_cpp/pcap.hpp>
namespace pcap_tests {

TEST(pcap_tests, get_default) {
  auto device = libpcap::find_default_device_name();
  std::cout << "Default device found: " << device << "\n";
  EXPECT_FALSE(device.empty());
}

TEST(pcap_tests, find_all_devices_test) {
  auto devices = libpcap::find_all_devices();
  std::cout << "All devices:\n";
  for (const auto &device : devices) {
    std::cout << device << "\n";
  }
  EXPECT_FALSE(devices.empty());
}

} //namespace test_vector
<commit_msg>builing up tests<commit_after>#include "gtest/gtest.h"
#include <pcap_cpp/pcap.hpp>
namespace {
  pcap_t *get_default_device() {
    auto device_name = libpcap::find_default_device_name();
    return libpcap::create(device_name);
  }
}

namespace pcap_tests {

TEST(pcap_tests, get_default) {
  auto device_name = libpcap::find_default_device_name();
  std::cout << "Default device found: " << device_name << "\n";
  EXPECT_FALSE(device_name.empty());
}

TEST(pcap_tests, find_all_devices_test) {
  auto devices = libpcap::find_all_devices();
  std::cout << "All devices:\n";
  for (const auto &device : devices) {
    std::cout << device << "\n";
  }
  EXPECT_FALSE(devices.empty());
}

TEST(pcap_tests, create_default_devie_and_activate_test) {
  auto device = get_default_device();
  EXPECT_TRUE(device);
  libpcap::activate(device);
}

TEST(pcap_tests, default_device_ip_and_netmask_test) {
  auto device_name = libpcap::find_default_device_name();
  auto ip_netmask = libpcap::get_device_ip_and_netmask(device_name);
  std::cout << "device ip: " << libpcap::qtos(std::get<0>(ip_netmask)) << "\n";
  std::cout << "device netmask: " << libpcap::qtos(std::get<1>(ip_netmask)) << "\n";
  EXPECT_FALSE(ip_netmask == std::make_tuple(0, 0));
}

TEST(pcap_tests, default_device_time_stamp_types_test) {
  auto device = get_default_device();
  auto time_stamps = libpcap::get_time_stamp_types(device);
  std::cout << "Time stamp types for default device:\n";
  for (const auto &time_stamp : time_stamps) {
    std::cout << time_stamp << "\n";
  }
  EXPECT_TRUE(true);
}

} //namespace test_vector
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osg/AnimationPath>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>

using namespace osg;

void AnimationPath::insert(double time,const ControlPoint& controlPoint)
{
    _timeControlPointMap[time] = controlPoint;
}

bool AnimationPath::getInterpolatedControlPoint(double time,ControlPoint& controlPoint) const
{
    if (_timeControlPointMap.empty()) return false;

    switch(_loopMode)
    {
        case(SWING):
        {
            double modulated_time = (time - getFirstTime())/(getPeriod()*2.0);
            double fraction_part = modulated_time - floor(modulated_time);
            if (fraction_part>0.5) fraction_part = 1.0-fraction_part;

            time = getFirstTime()+(fraction_part*2.0) * getPeriod();
            break;
        }
        case(LOOP):
        {
            double modulated_time = (time - getFirstTime())/getPeriod();
            double fraction_part = modulated_time - floor(modulated_time);
            time = getFirstTime()+fraction_part * getPeriod();
            break;
        }
        case(NO_LOOPING):
            // no need to modulate the time.
            break;
    }

    TimeControlPointMap::const_iterator second = _timeControlPointMap.lower_bound(time);
    if (second==_timeControlPointMap.begin())
    {
        controlPoint = second->second;
    }
    else if (second!=_timeControlPointMap.end())
    {
        TimeControlPointMap::const_iterator first = second;
        --first;

        // we have both a lower bound and the next item.

        // deta_time = second.time - first.time
        double delta_time = second->first - first->first;

        if (delta_time==0.0)
            controlPoint = first->second;
        else
        {
            controlPoint.interpolate((time - first->first)/delta_time,
                            first->second,
                            second->second);
        }
    }
    else // (second==_timeControlPointMap.end())
    {
        controlPoint = _timeControlPointMap.rbegin()->second;
    }
    return true;
}

void AnimationPath::read(std::istream& in)
{
    while (!in.eof())
    {
        double time;
        osg::Vec3 position;
        osg::Quat rotation;
        in >> time >> position.x() >> position.y() >> position.z() >> rotation.x() >> rotation.y() >> rotation.z() >> rotation.w();
        if(!in.eof())
            insert(time,osg::AnimationPath::ControlPoint(position,rotation));
    }
}

void AnimationPath::write(std::ostream& fout) const
{
    const TimeControlPointMap& tcpm = getTimeControlPointMap();
    for(TimeControlPointMap::const_iterator tcpmitr=tcpm.begin();
        tcpmitr!=tcpm.end();
        ++tcpmitr)
    {
        const ControlPoint& cp = tcpmitr->second;
        fout<<tcpmitr->first<<" "<<cp._position<<" "<<cp._rotation<<std::endl;
    }
}

class AnimationPathCallbackVisitor : public NodeVisitor
{
    public:

        AnimationPathCallbackVisitor(const AnimationPath::ControlPoint& cp, const osg::Vec3d& pivotPoint, bool useInverseMatrix):
            _cp(cp),
            _pivotPoint(pivotPoint),
            _useInverseMatrix(useInverseMatrix) {}

        virtual void apply(MatrixTransform& mt)
        {
            Matrix matrix;
            if (_useInverseMatrix)
                _cp.getInverse(matrix);
            else
                _cp.getMatrix(matrix);

            mt.setMatrix(osg::Matrix::translate(-_pivotPoint)*matrix);
        }

        virtual void apply(PositionAttitudeTransform& pat)
        {
            if (_useInverseMatrix)
            {
                Matrix matrix;
                _cp.getInverse(matrix);
                pat.setPosition(matrix.getTrans());
                pat.setAttitude(_cp._rotation.inverse());
                pat.setScale(osg::Vec3(1.0f/_cp._scale.x(),1.0f/_cp._scale.y(),1.0f/_cp._scale.z()));
                pat.setPivotPoint(_pivotPoint);

            }
            else
            {
                pat.setPosition(_cp._position);
                pat.setAttitude(_cp._rotation);
                pat.setScale(_cp._scale);
                pat.setPivotPoint(_pivotPoint);
            }
        }

        AnimationPath::ControlPoint _cp;
        osg::Vec3d _pivotPoint;
        bool _useInverseMatrix;
};

void AnimationPathCallback::operator()(Node* node, NodeVisitor* nv)
{
    if (_animationPath.valid() &&
        nv->getVisitorType()==NodeVisitor::UPDATE_VISITOR &&
        nv->getFrameStamp())
    {
        double time = nv->getFrameStamp()->getReferenceTime();
        _latestTime = time;

        if (!_pause)
        {
            // Only update _firstTime the first time, when its value is still DBL_MAX
            if (_firstTime==DBL_MAX) _firstTime = time;
            update(*node);
        }
    }

    // must call any nested node callbacks and continue subgraph traversal.
    NodeCallback::traverse(node,nv);
}

double AnimationPathCallback::getAnimationTime() const
{
    return ((_latestTime-_firstTime)-_timeOffset)*_timeMultiplier;
}

void AnimationPathCallback::update(osg::Node& node)
{
    AnimationPath::ControlPoint cp;
    if (_animationPath->getInterpolatedControlPoint(getAnimationTime(),cp))
    {
        AnimationPathCallbackVisitor apcv(cp,_pivotPoint,_useInverseMatrix);
        node.accept(apcv);
    }
}

void AnimationPathCallback::reset()
{
    _firstTime = _latestTime;
    _pauseTime = _latestTime;
}

void AnimationPathCallback::setPause(bool pause)
{
    if (_pause==pause)
    {
        return;
    }

    _pause = pause;
    if (_pause)
    {
        _pauseTime = _latestTime;
    }
    else
    {
        _firstTime += (_latestTime-_pauseTime);
    }
}
<commit_msg>Improved the precision of animation paths.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osg/AnimationPath>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>

using namespace osg;

void AnimationPath::insert(double time,const ControlPoint& controlPoint)
{
    _timeControlPointMap[time] = controlPoint;
}

bool AnimationPath::getInterpolatedControlPoint(double time,ControlPoint& controlPoint) const
{
    if (_timeControlPointMap.empty()) return false;

    switch(_loopMode)
    {
        case(SWING):
        {
            double modulated_time = (time - getFirstTime())/(getPeriod()*2.0);
            double fraction_part = modulated_time - floor(modulated_time);
            if (fraction_part>0.5) fraction_part = 1.0-fraction_part;

            time = getFirstTime()+(fraction_part*2.0) * getPeriod();
            break;
        }
        case(LOOP):
        {
            double modulated_time = (time - getFirstTime())/getPeriod();
            double fraction_part = modulated_time - floor(modulated_time);
            time = getFirstTime()+fraction_part * getPeriod();
            break;
        }
        case(NO_LOOPING):
            // no need to modulate the time.
            break;
    }

    TimeControlPointMap::const_iterator second = _timeControlPointMap.lower_bound(time);
    if (second==_timeControlPointMap.begin())
    {
        controlPoint = second->second;
    }
    else if (second!=_timeControlPointMap.end())
    {
        TimeControlPointMap::const_iterator first = second;
        --first;

        // we have both a lower bound and the next item.

        // deta_time = second.time - first.time
        double delta_time = second->first - first->first;

        if (delta_time==0.0)
            controlPoint = first->second;
        else
        {
            controlPoint.interpolate((time - first->first)/delta_time,
                            first->second,
                            second->second);
        }
    }
    else // (second==_timeControlPointMap.end())
    {
        controlPoint = _timeControlPointMap.rbegin()->second;
    }
    return true;
}

void AnimationPath::read(std::istream& in)
{
    while (!in.eof())
    {
        double time;
        osg::Vec3d position;
        osg::Quat rotation;
        in >> time >> position.x() >> position.y() >> position.z() >> rotation.x() >> rotation.y() >> rotation.z() >> rotation.w();
        if(!in.eof())
            insert(time,osg::AnimationPath::ControlPoint(position,rotation));
    }
}

void AnimationPath::write(std::ostream& fout) const
{
    int prec = fout.precision();
    fout.precision(15);

    const TimeControlPointMap& tcpm = getTimeControlPointMap();
    for(TimeControlPointMap::const_iterator tcpmitr=tcpm.begin();
        tcpmitr!=tcpm.end();
        ++tcpmitr)
    {
        const ControlPoint& cp = tcpmitr->second;
        fout<<tcpmitr->first<<" "<<cp._position<<" "<<cp._rotation<<std::endl;
    }

    fout.precision(prec);
}

class AnimationPathCallbackVisitor : public NodeVisitor
{
    public:

        AnimationPathCallbackVisitor(const AnimationPath::ControlPoint& cp, const osg::Vec3d& pivotPoint, bool useInverseMatrix):
            _cp(cp),
            _pivotPoint(pivotPoint),
            _useInverseMatrix(useInverseMatrix) {}

        virtual void apply(MatrixTransform& mt)
        {
            Matrix matrix;
            if (_useInverseMatrix)
                _cp.getInverse(matrix);
            else
                _cp.getMatrix(matrix);

            mt.setMatrix(osg::Matrix::translate(-_pivotPoint)*matrix);
        }

        virtual void apply(PositionAttitudeTransform& pat)
        {
            if (_useInverseMatrix)
            {
                Matrix matrix;
                _cp.getInverse(matrix);
                pat.setPosition(matrix.getTrans());
                pat.setAttitude(_cp._rotation.inverse());
                pat.setScale(osg::Vec3(1.0f/_cp._scale.x(),1.0f/_cp._scale.y(),1.0f/_cp._scale.z()));
                pat.setPivotPoint(_pivotPoint);

            }
            else
            {
                pat.setPosition(_cp._position);
                pat.setAttitude(_cp._rotation);
                pat.setScale(_cp._scale);
                pat.setPivotPoint(_pivotPoint);
            }
        }

        AnimationPath::ControlPoint _cp;
        osg::Vec3d _pivotPoint;
        bool _useInverseMatrix;
};

void AnimationPathCallback::operator()(Node* node, NodeVisitor* nv)
{
    if (_animationPath.valid() &&
        nv->getVisitorType()==NodeVisitor::UPDATE_VISITOR &&
        nv->getFrameStamp())
    {
        double time = nv->getFrameStamp()->getReferenceTime();
        _latestTime = time;

        if (!_pause)
        {
            // Only update _firstTime the first time, when its value is still DBL_MAX
            if (_firstTime==DBL_MAX) _firstTime = time;
            update(*node);
        }
    }

    // must call any nested node callbacks and continue subgraph traversal.
    NodeCallback::traverse(node,nv);
}

double AnimationPathCallback::getAnimationTime() const
{
    return ((_latestTime-_firstTime)-_timeOffset)*_timeMultiplier;
}

void AnimationPathCallback::update(osg::Node& node)
{
    AnimationPath::ControlPoint cp;
    if (_animationPath->getInterpolatedControlPoint(getAnimationTime(),cp))
    {
        AnimationPathCallbackVisitor apcv(cp,_pivotPoint,_useInverseMatrix);
        node.accept(apcv);
    }
}

void AnimationPathCallback::reset()
{
    _firstTime = _latestTime;
    _pauseTime = _latestTime;
}

void AnimationPathCallback::setPause(bool pause)
{
    if (_pause==pause)
    {
        return;
    }

    _pause = pause;
    if (_pause)
    {
        _pauseTime = _latestTime;
    }
    else
    {
        _firstTime += (_latestTime-_pauseTime);
    }
}
<|endoftext|>