<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "glwidget.h"
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QMouseEvent>
#include <QApplication>
#include <QDir>
#include <QPainter>
#include <QFileInfo>
#include <QFileInfoList>
#include <QOpenGLPaintDevice>
#include <QOpenGLFramebufferObject>

GLWidget::GLWidget(QWidget *parent)
    : QOpenGLWidget(parent),
      clearColor(Qt::black),
      program(0),
      currentTexture(0),
      currentFrame(0),
      numberOfFrames(0),
      currentFps(0),
      avgFrames(0),
      mFpsTimePerFrame(0)
{
    connect(&mTimer, &QTimer::timeout, this, &GLWidget::updateFps);
    mTimer.start(1000);
}

GLWidget::~GLWidget()
{
    makeCurrent();
    vbo.destroy();
    foreach(QOpenGLTexture *texture, textures)
    delete texture;
    delete program;
    doneCurrent();
}

QSize GLWidget::minimumSizeHint() const
{
    return QSize(50, 50);
}

void GLWidget::setClearColor(const QColor &color)
{
    clearColor = color;
    update();
}

void GLWidget::setFpsLimit(int limit)
{
    mFpsTimePerFrame = 1000.0 / (limit * 1.0);
}

void GLWidget::initializeGL()
{
    initializeOpenGLFunctions();

    makeObject();

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

#define PROGRAM_VERTEX_ATTRIBUTE 0
#define PROGRAM_TEXCOORD_ATTRIBUTE 1

    QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
    const char *vsrc =
        "attribute highp vec4 vertex;\n"
        "attribute mediump vec4 texCoord;\n"
        "varying mediump vec4 texc;\n"
        "uniform mediump mat4 matrix;\n"
        "void main(void)\n"
        "{\n"
        "    gl_Position = matrix * vertex;\n"
        "    texc = texCoord;\n"
        "    gl_Position = matrix * vertex;\n"
        "    texc = texCoord * vec4(1.0, -1.0, 1.0, 1.0);\n"

        "}\n";
    vshader->compileSourceCode(vsrc);

    QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
    const char *fsrc =
        "uniform sampler2D texture;\n"
        "varying mediump vec4 texc;\n"
        "void main(void)\n"
        "{\n"
        "    gl_FragColor = texture2D(texture, texc.st);\n"
        "    if (gl_FragColor.a < 0.5)\n"
        "        discard;\n"
        "}\n";
    fshader->compileSourceCode(fsrc);

    program = new QOpenGLShaderProgram;
    program->addShader(vshader);
    program->addShader(fshader);
    program->bindAttributeLocation("vertex", PROGRAM_VERTEX_ATTRIBUTE);
    program->bindAttributeLocation("texCoord", PROGRAM_TEXCOORD_ATTRIBUTE);
    program->link();

    program->bind();
    program->setUniformValue("texture", 0);
}

void GLWidget::paintGL()
{
    glClearColor(clearColor.redF(), clearColor.greenF(), clearColor.blueF(), clearColor.alphaF());
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    paintText();

    QMatrix4x4 m;
    m.ortho(-1.0f, +1.0f, +1.0f, -1.0f, 1.0f, -1.0f);

    program->setUniformValue("matrix", m);
    program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
    program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
    program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0,
                3, 5 * sizeof(GLfloat));
    program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT,
                3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));

    if (textures.size()) {
    textures[currentTexture]->bind();
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    currentTexture++;
    currentTexture %= textures.size();
    }

    currentFrame++;

    QTimer::singleShot(mFpsTimePerFrame, this, SLOT(update()));
}
void GLWidget::resizeGL(int width, int height)
{
    qDebug() << width << "x" << height;
    glViewport(0, 0, width, height);
}

void GLWidget::paintText()
{
    QString fpsOverlay = QString("FPS: %1").arg(currentFps);
    QString avgOverlay = QString("AVG: %1").arg(avgFrames);

    const QRect drawRect(0, 0, 150, 50);
    const QSize drawRectSize = drawRect.size();

    QImage img(drawRectSize, QImage::Format_ARGB32);
    img.fill(Qt::transparent);
    QPainter painter;

    painter.begin(&img);
    painter.setBackgroundMode(Qt::TransparentMode);

    painter.setBackground(Qt::transparent);
    QFont font = painter.font();
    font.setPointSize(24);
    font.setPointSize(16);
    painter.setFont(font);
    painter.setPen(Qt::green);
    painter.setBrush(QBrush());

    QFontMetrics fMetrics = painter.fontMetrics();
    QSize fpsMetrics = fMetrics.size( Qt::TextSingleLine, fpsOverlay );
    QRectF fpsRect( QPoint(0, 0), fpsMetrics );
    QSize avgMetrics = fMetrics.size( Qt::TextSingleLine, avgOverlay );
    QRectF avgRect( QPoint(0, fpsRect.height()), avgMetrics );
    painter.drawText(fpsRect, Qt::TextSingleLine, fpsOverlay);
    painter.drawText(avgRect, Qt::TextSingleLine, avgOverlay);

    painter.end();

    QOpenGLTexture texture(img);
    texture.bind();

    QMatrix4x4 m;
    m.ortho(-12.0f, +12.0f, +12.0f, -12.0f, 1.0f, -1.0f);

    program->setUniformValue("matrix", m);
    program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
    program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
    program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0,
                3, 5 * sizeof(GLfloat));
    program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT,
                3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

}

void GLWidget::updateFps()
{
    currentFps = currentFrame;
    currentFrame = 0;

    avgFrames = (currentFps + numberOfFrames * avgFrames) / (numberOfFrames + 1);
    numberOfFrames++;

    qDebug() << "FPS: " << currentFps << ", AVG: " << avgFrames;
}

void GLWidget::makeObject()
{
    static const int coords[4][3] = {
    { +1, -1, -1 },
    { -1, -1, -1 },
    { -1, +1, -1 },
    { +1, +1, -1 }
    };

    QString path = QApplication::applicationDirPath();

    QDir dir(path, "*.png", QDir::IgnoreCase, QDir::Files);
    QFileInfoList files = dir.entryInfoList();

    foreach(QFileInfo file, files) {
    QImage img;
    if (img.load(file.absoluteFilePath())) {
        textures.append(new QOpenGLTexture(img));
    }
    }

    QVector<GLfloat> vertData;
    for (int j = 0; j < 4; ++j) {
    // vertex position
    vertData.append(coords[j][0]);
    vertData.append(coords[j][1]);
    vertData.append(coords[j][2]);
    // texture coordinate
    vertData.append(j == 0 || j == 3);
    vertData.append(j == 0 || j == 1);
    }

    vbo.create();
    vbo.bind();
    vbo.allocate(vertData.constData(), vertData.count() * sizeof(GLfloat));
}

<commit_msg>Allowing to deactivate FPS limiter now.<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "glwidget.h"
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QMouseEvent>
#include <QApplication>
#include <QDir>
#include <QPainter>
#include <QFileInfo>
#include <QFileInfoList>
#include <QOpenGLPaintDevice>
#include <QOpenGLFramebufferObject>

GLWidget::GLWidget(QWidget *parent)
    : QOpenGLWidget(parent),
      clearColor(Qt::black),
      program(0),
      currentTexture(0),
      currentFrame(0),
      numberOfFrames(0),
      currentFps(0),
      avgFrames(0),
      mFpsTimePerFrame(0)
{
    connect(&mTimer, &QTimer::timeout, this, &GLWidget::updateFps);
    mTimer.start(1000);
}

GLWidget::~GLWidget()
{
    makeCurrent();
    vbo.destroy();
    foreach(QOpenGLTexture *texture, textures)
    delete texture;
    delete program;
    doneCurrent();
}

QSize GLWidget::minimumSizeHint() const
{
    return QSize(50, 50);
}

void GLWidget::setClearColor(const QColor &color)
{
    clearColor = color;
    update();
}

void GLWidget::setFpsLimit(int limit)
{
    if (limit > 0)
        mFpsTimePerFrame = 1000.0 / (limit * 1.0);
    else
        mFpsTimePerFrame = 0.0;
}

void GLWidget::initializeGL()
{
    initializeOpenGLFunctions();

    makeObject();

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

#define PROGRAM_VERTEX_ATTRIBUTE 0
#define PROGRAM_TEXCOORD_ATTRIBUTE 1

    QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
    const char *vsrc =
        "attribute highp vec4 vertex;\n"
        "attribute mediump vec4 texCoord;\n"
        "varying mediump vec4 texc;\n"
        "uniform mediump mat4 matrix;\n"
        "void main(void)\n"
        "{\n"
        "    gl_Position = matrix * vertex;\n"
        "    texc = texCoord;\n"
        "    gl_Position = matrix * vertex;\n"
        "    texc = texCoord * vec4(1.0, -1.0, 1.0, 1.0);\n"

        "}\n";
    vshader->compileSourceCode(vsrc);

    QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
    const char *fsrc =
        "uniform sampler2D texture;\n"
        "varying mediump vec4 texc;\n"
        "void main(void)\n"
        "{\n"
        "    gl_FragColor = texture2D(texture, texc.st);\n"
        "    if (gl_FragColor.a < 0.5)\n"
        "        discard;\n"
        "}\n";
    fshader->compileSourceCode(fsrc);

    program = new QOpenGLShaderProgram;
    program->addShader(vshader);
    program->addShader(fshader);
    program->bindAttributeLocation("vertex", PROGRAM_VERTEX_ATTRIBUTE);
    program->bindAttributeLocation("texCoord", PROGRAM_TEXCOORD_ATTRIBUTE);
    program->link();

    program->bind();
    program->setUniformValue("texture", 0);
}

void GLWidget::paintGL()
{
    glClearColor(clearColor.redF(), clearColor.greenF(), clearColor.blueF(), clearColor.alphaF());
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    paintText();

    QMatrix4x4 m;
    m.ortho(-1.0f, +1.0f, +1.0f, -1.0f, 1.0f, -1.0f);

    program->setUniformValue("matrix", m);
    program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
    program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
    program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0,
                3, 5 * sizeof(GLfloat));
    program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT,
                3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));

    if (textures.size()) {
    textures[currentTexture]->bind();
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    currentTexture++;
    currentTexture %= textures.size();
    }

    currentFrame++;

    QTimer::singleShot(mFpsTimePerFrame, this, SLOT(update()));
}
void GLWidget::resizeGL(int width, int height)
{
    qDebug() << width << "x" << height;
    glViewport(0, 0, width, height);
}

void GLWidget::paintText()
{
    QString fpsOverlay = QString("FPS: %1").arg(currentFps);
    QString avgOverlay = QString("AVG: %1").arg(avgFrames);

    const QRect drawRect(0, 0, 150, 50);
    const QSize drawRectSize = drawRect.size();

    QImage img(drawRectSize, QImage::Format_ARGB32);
    img.fill(Qt::transparent);
    QPainter painter;

    painter.begin(&img);
    painter.setBackgroundMode(Qt::TransparentMode);

    painter.setBackground(Qt::transparent);
    QFont font = painter.font();
    font.setPointSize(24);
    font.setPointSize(16);
    painter.setFont(font);
    painter.setPen(Qt::green);
    painter.setBrush(QBrush());

    QFontMetrics fMetrics = painter.fontMetrics();
    QSize fpsMetrics = fMetrics.size( Qt::TextSingleLine, fpsOverlay );
    QRectF fpsRect( QPoint(0, 0), fpsMetrics );
    QSize avgMetrics = fMetrics.size( Qt::TextSingleLine, avgOverlay );
    QRectF avgRect( QPoint(0, fpsRect.height()), avgMetrics );
    painter.drawText(fpsRect, Qt::TextSingleLine, fpsOverlay);
    painter.drawText(avgRect, Qt::TextSingleLine, avgOverlay);

    painter.end();

    QOpenGLTexture texture(img);
    texture.bind();

    QMatrix4x4 m;
    m.ortho(-12.0f, +12.0f, +12.0f, -12.0f, 1.0f, -1.0f);

    program->setUniformValue("matrix", m);
    program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
    program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
    program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0,
                3, 5 * sizeof(GLfloat));
    program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT,
                3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

}

void GLWidget::updateFps()
{
    currentFps = currentFrame;
    currentFrame = 0;

    avgFrames = (currentFps + numberOfFrames * avgFrames) / (numberOfFrames + 1);
    numberOfFrames++;

    qDebug() << "FPS: " << currentFps << ", AVG: " << avgFrames;
}

void GLWidget::makeObject()
{
    static const int coords[4][3] = {
    { +1, -1, -1 },
    { -1, -1, -1 },
    { -1, +1, -1 },
    { +1, +1, -1 }
    };

    QString path = QApplication::applicationDirPath();

    QDir dir(path, "*.png", QDir::IgnoreCase, QDir::Files);
    QFileInfoList files = dir.entryInfoList();

    foreach(QFileInfo file, files) {
    QImage img;
    if (img.load(file.absoluteFilePath())) {
        textures.append(new QOpenGLTexture(img));
    }
    }

    QVector<GLfloat> vertData;
    for (int j = 0; j < 4; ++j) {
    // vertex position
    vertData.append(coords[j][0]);
    vertData.append(coords[j][1]);
    vertData.append(coords[j][2]);
    // texture coordinate
    vertData.append(j == 0 || j == 3);
    vertData.append(j == 0 || j == 1);
    }

    vbo.create();
    vbo.bind();
    vbo.allocate(vertData.constData(), vertData.count() * sizeof(GLfloat));
}

<|endoftext|>


<commit_before>// @(#)root/tree:$Name:  $:$Id: TBranchRef.cxx,v 1.1 2004/08/20 14:54:53 brun Exp $
// Author: Rene Brun   19/08/2004

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// A Branch for the case of an array of clone objects                   //                                                                      //
// See TTree.                                                           //                                                                     //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TBranchRef.h"
#include "TTree.h"
#include "TBasket.h"
#include "TFile.h"

ClassImp(TBranchRef)

//______________________________________________________________________________
TBranchRef::TBranchRef(): TBranch()
{

   fRefTable   = 0;
}

//______________________________________________________________________________
TBranchRef::TBranchRef(TTree *tree)
    :TBranch()
{
   // main constructor called by TTree::BranchRef

   if (!tree) return;
   TDirectory *dir = tree->GetDirectory();
   if (!dir) return;
   TFile *file = dir->GetFile();
   if (!file) return;
   SetName("TRefTable");
   SetTitle("List of branch numbers with referenced objects");
   fRefTable = new TRefTable(100);
   file->SetRefTable(fRefTable);

   fCompress       = 1;
   fBasketSize     = 32000;
   fAddress        = 0;
   fBasketBytes    = new Int_t[fMaxBaskets];
   fBasketEntry    = new Long64_t[fMaxBaskets];
   fBasketSeek     = new Long64_t[fMaxBaskets];

   for (Int_t i=0;i<fMaxBaskets;i++) {
      fBasketBytes[i] = 0;
      fBasketEntry[i] = 0;
      fBasketSeek[i]  = 0;
   }

   fTree       = tree;
   fDirectory  = fTree->GetDirectory();
   fFileName   = "";

  //  Create the first basket
   TBasket *basket = new TBasket("TRefTable",fTree->GetName(),this);
   fBaskets.Add(basket);
}

//______________________________________________________________________________
TBranchRef::~TBranchRef()
{
   delete fRefTable;
   GetFile()->SetRefTable(0);
}

//______________________________________________________________________________
void TBranchRef::Clear(Option_t *option)
{
  // clear entries in the TRefTable

   fRefTable->Clear(option);
}

//______________________________________________________________________________
Int_t TBranchRef::Fill()
{
  // fill the branch basket with the referenced objects parent numbers

   Int_t nbytes = TBranch::Fill();
   return nbytes;
}

//______________________________________________________________________________
void TBranchRef::FillLeaves(TBuffer &b)
{
   // This function called by TBranch::Fill overloads TBranch::FillLeaves

    fRefTable->FillBuffer(b);
}

//______________________________________________________________________________
void TBranchRef::Print(Option_t *option) const
{
  // Print the TRefTable branch

   TBranch::Print(option);
}

//______________________________________________________________________________
void TBranchRef::ReadLeaves(TBuffer &b)
{
   // This function called by TBranch::GetEntry overloads TBranch::ReadLeaves

  fRefTable->ReadBuffer(b);
}

//______________________________________________________________________________
void TBranchRef::Reset(Option_t *option)
{
  //    Existing buffers are deleted
  //    Entries, max and min are reset
  //    TRefTable is cleared

   TBranch::Reset(option);
   fRefTable->Clear();
}

//______________________________________________________________________________
void TBranchRef::SetParent(const TObject *object)
{
   // this function is called by TBranchElement::Fill when filling
   // branches that may contain referenced objects

   fRefTable->SetParent(object);
}
<commit_msg>add protection in dtor against GetFile() returning 0.<commit_after>// @(#)root/tree:$Name:  $:$Id: TBranchRef.cxx,v 1.2 2004/08/20 21:24:49 brun Exp $
// Author: Rene Brun   19/08/2004

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// A Branch for the case of an array of clone objects                   //                                                                      //
// See TTree.                                                           //                                                                     //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TBranchRef.h"
#include "TTree.h"
#include "TBasket.h"
#include "TFile.h"

ClassImp(TBranchRef)

//______________________________________________________________________________
TBranchRef::TBranchRef(): TBranch()
{

   fRefTable   = 0;
}

//______________________________________________________________________________
TBranchRef::TBranchRef(TTree *tree)
    :TBranch()
{
   // main constructor called by TTree::BranchRef

   if (!tree) return;
   TDirectory *dir = tree->GetDirectory();
   if (!dir) return;
   TFile *file = dir->GetFile();
   if (!file) return;
   SetName("TRefTable");
   SetTitle("List of branch numbers with referenced objects");
   fRefTable = new TRefTable(100);
   file->SetRefTable(fRefTable);

   fCompress       = 1;
   fBasketSize     = 32000;
   fAddress        = 0;
   fBasketBytes    = new Int_t[fMaxBaskets];
   fBasketEntry    = new Long64_t[fMaxBaskets];
   fBasketSeek     = new Long64_t[fMaxBaskets];

   for (Int_t i=0;i<fMaxBaskets;i++) {
      fBasketBytes[i] = 0;
      fBasketEntry[i] = 0;
      fBasketSeek[i]  = 0;
   }

   fTree       = tree;
   fDirectory  = fTree->GetDirectory();
   fFileName   = "";

  //  Create the first basket
   TBasket *basket = new TBasket("TRefTable",fTree->GetName(),this);
   fBaskets.Add(basket);
}

//______________________________________________________________________________
TBranchRef::~TBranchRef()
{
   delete fRefTable;
   TFile *f = GetFile();
   if (f) f->SetRefTable(0);
}

//______________________________________________________________________________
void TBranchRef::Clear(Option_t *option)
{
  // clear entries in the TRefTable

   fRefTable->Clear(option);
}

//______________________________________________________________________________
Int_t TBranchRef::Fill()
{
  // fill the branch basket with the referenced objects parent numbers

   Int_t nbytes = TBranch::Fill();
   return nbytes;
}

//______________________________________________________________________________
void TBranchRef::FillLeaves(TBuffer &b)
{
   // This function called by TBranch::Fill overloads TBranch::FillLeaves

    fRefTable->FillBuffer(b);
}

//______________________________________________________________________________
void TBranchRef::Print(Option_t *option) const
{
  // Print the TRefTable branch

   TBranch::Print(option);
}

//______________________________________________________________________________
void TBranchRef::ReadLeaves(TBuffer &b)
{
   // This function called by TBranch::GetEntry overloads TBranch::ReadLeaves

  fRefTable->ReadBuffer(b);
}

//______________________________________________________________________________
void TBranchRef::Reset(Option_t *option)
{
  //    Existing buffers are deleted
  //    Entries, max and min are reset
  //    TRefTable is cleared

   TBranch::Reset(option);
   fRefTable->Clear();
}

//______________________________________________________________________________
void TBranchRef::SetParent(const TObject *object)
{
   // this function is called by TBranchElement::Fill when filling
   // branches that may contain referenced objects

   fRefTable->SetParent(object);
}
<|endoftext|>


<commit_before>#include "LRToComplex.h"
#include "check_params.h"
#include "lr_config.h"

namespace edb
{

std::string LRToComplex::Command() const
{
	return "lr2complex";
}

std::string LRToComplex::Description() const
{
	return "create complex file from lr file";
}

std::string LRToComplex::Usage() const
{
	// lr2complex e:/test2/test_lr.json
	std::string usage = Command() + " [filepath]";
	return usage;
}

void LRToComplex::Run(int argc, char *argv[])
{
	if (!check_number(this, argc, 3)) return;
	if (!check_file(argv[2])) return;

	Run(argv[2]);
}

void LRToComplex::Run(const std::string& filepath)
{
	Json::Value lr_val;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filepath.c_str());
	std::locale::global(std::locale("C"));
	reader.parse(fin, lr_val);
	fin.close();

	Json::Value complex_val;
// 	for (int i = 0; i < 3; ++i) {
// 		LoadSpriteValue(lr_val["layer"][i]["sprite"], complex_val["sprite"]);
// 	}
	int layer_idx = 0;
	LoadSpriteValue(lr_val["layer"][layer_idx]["sprite"], complex_val["sprite"]);
	std::string name = d2d::FilenameTools::getFilename(filepath);
	name = "scene_" + name.substr(0, name.find_last_of('_'));
	complex_val["name"] = name;
	complex_val["use_render_cache"] = false;
	complex_val["xmax"] = 0;
	complex_val["xmin"] = 0;
	complex_val["ymax"] = 0;
	complex_val["ymin"] = 0;

	std::string outfile = filepath.substr(0, filepath.find_last_of("_"));
	wxString tag = d2d::FileNameParser::getFileTag(d2d::FileNameParser::e_complex);
	outfile = d2d::FilenameTools::getFilenameAddTag(outfile, tag, "json");

	Json::StyledStreamWriter writer;
	std::locale::global(std::locale(""));
	std::ofstream fout(outfile.c_str());
	std::locale::global(std::locale("C"));
	writer.write(fout, complex_val);
	fout.close();
}

void LRToComplex::LoadSpriteValue(const Json::Value& src_val, Json::Value& dst_val)
{
	int idx = 0;
	Json::Value spr_val = src_val[idx++];
	while (!spr_val.isNull()) {
		// test character
		std::string tag = spr_val["tag"].asString();
		if (!tag.empty()) {
			spr_val = src_val[idx++];
			continue;
		}

		std::string filepath = spr_val["filepath"].asString();
		Json::Value spr_val_fix = spr_val;

		std::string suffix = "_shape.json";
		int pos = filepath.find(suffix);
		if (pos!= std::string::npos) {
			std::string fix_filepath = filepath.substr(0, pos) + ".png";
			if (d2d::FilenameTools::isExist(fix_filepath)) {
				spr_val_fix["filepath"] = fix_filepath;
			}
		}

		dst_val[dst_val.size()] = spr_val_fix;

		spr_val = src_val[idx++];
	}
}

}<commit_msg>[FIXED] lr打包加上装饰层<commit_after>#include "LRToComplex.h"
#include "check_params.h"
#include "lr_config.h"

namespace edb
{

std::string LRToComplex::Command() const
{
	return "lr2complex";
}

std::string LRToComplex::Description() const
{
	return "create complex file from lr file";
}

std::string LRToComplex::Usage() const
{
	// lr2complex e:/test2/test_lr.json
	std::string usage = Command() + " [filepath]";
	return usage;
}

void LRToComplex::Run(int argc, char *argv[])
{
	if (!check_number(this, argc, 3)) return;
	if (!check_file(argv[2])) return;

	Run(argv[2]);
}

void LRToComplex::Run(const std::string& filepath)
{
	Json::Value lr_val;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filepath.c_str());
	std::locale::global(std::locale("C"));
	reader.parse(fin, lr_val);
	fin.close();

	Json::Value complex_val;
// 	for (int i = 0; i < 3; ++i) {
// 		LoadSpriteValue(lr_val["layer"][i]["sprite"], complex_val["sprite"]);
// 	}
	int layer_idx = 0;
	LoadSpriteValue(lr_val["layer"][layer_idx]["sprite"], complex_val["sprite"]);
	layer_idx = 1;
	LoadSpriteValue(lr_val["layer"][layer_idx]["sprite"], complex_val["sprite"]);
	std::string name = d2d::FilenameTools::getFilename(filepath);
	name = "scene_" + name.substr(0, name.find_last_of('_'));
	complex_val["name"] = name;
	complex_val["use_render_cache"] = false;
	complex_val["xmax"] = 0;
	complex_val["xmin"] = 0;
	complex_val["ymax"] = 0;
	complex_val["ymin"] = 0;

	std::string outfile = filepath.substr(0, filepath.find_last_of("_"));
	wxString tag = d2d::FileNameParser::getFileTag(d2d::FileNameParser::e_complex);
	outfile = d2d::FilenameTools::getFilenameAddTag(outfile, tag, "json");

	Json::StyledStreamWriter writer;
	std::locale::global(std::locale(""));
	std::ofstream fout(outfile.c_str());
	std::locale::global(std::locale("C"));
	writer.write(fout, complex_val);
	fout.close();
}

void LRToComplex::LoadSpriteValue(const Json::Value& src_val, Json::Value& dst_val)
{
	int idx = 0;
	Json::Value spr_val = src_val[idx++];
	while (!spr_val.isNull()) {
		// test character
		std::string tag = spr_val["tag"].asString();
		if (!tag.empty()) {
			spr_val = src_val[idx++];
			continue;
		}

		std::string filepath = spr_val["filepath"].asString();

		Json::Value spr_val_fix = spr_val;

		std::string suffix = "_shape.json";
		int pos = filepath.find(suffix);
		if (pos!= std::string::npos) {
			std::string fix_filepath = filepath.substr(0, pos) + ".png";
			if (d2d::FilenameTools::isExist(fix_filepath)) {
				spr_val_fix["filepath"] = fix_filepath;
			}
		}

		dst_val[dst_val.size()] = spr_val_fix;

		spr_val = src_val[idx++];
	}
}

}<|endoftext|>


<commit_before>// Copyright 2022 The Chromium Authors.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <iostream>
#include <string>
#include <vector>

#include "content_analysis/sdk/analysis_client.h"

using content_analysis::sdk::Client;
using content_analysis::sdk::ContentAnalysisRequest;
using content_analysis::sdk::ContentAnalysisResponse;
using content_analysis::sdk::ContentAnalysisAcknowledgement;

// Paramters used to build the request.
content_analysis::sdk::AnalysisConnector connector =
    content_analysis::sdk::FILE_ATTACHED;
std::string request_token = "req-12345";
std::string tag = "dlp";
std::string digest = "sha256-123456";
std::string url = "https://upload.example.com";
std::vector<std::string> datas;

// Command line parameters.
constexpr const char* kArgConnector = "--connector=";
constexpr const char* kArgRequestToken = "--request-token=";
constexpr const char* kArgTag = "--tag=";
constexpr const char* kArgDigest = "--digest=";
constexpr const char* kArgUrl = "--url=";
constexpr const char* kArgHelp = "--help";

bool ParseCommandLine(int argc, char* argv[]) {
  for (int i = 1; i < argc; ++i) {
    const std::string arg = argv[i];
    if (arg.find(kArgConnector) == 0) {
      std::string connector_str = arg.substr(strlen(kArgConnector));
      if (connector_str == "download") {
        connector = content_analysis::sdk::FILE_DOWNLOADED;
      } else if (connector_str == "attach") {
        connector = content_analysis::sdk::FILE_ATTACHED;
      } else if (connector_str == "bulk-data-entry") {
        connector = content_analysis::sdk::BULK_DATA_ENTRY;
      } else if (connector_str == "print") {
        connector = content_analysis::sdk::PRINT;
      } else if (connector_str == "file-transfer") {
        connector = content_analysis::sdk::FILE_TRANSFER;
      } else {
        std::cout << "[Demo] Incorrect command line arg: " << arg << std::endl;
        return false;
      }
    } else if (arg.find(kArgRequestToken) == 0) {
      request_token = arg.substr(strlen(kArgRequestToken));
    } else if (arg.find(kArgTag) == 0) {
      tag = arg.substr(strlen(kArgTag));
    } else if (arg.find(kArgDigest) == 0) {
      digest = arg.substr(strlen(kArgDigest));
    } else if (arg.find(kArgUrl) == 0) {
      url = arg.substr(strlen(kArgUrl));
    } else if (arg.find(kArgHelp) == 0) {
      return false;
    } else {
      datas.push_back(arg);
    }
  }

  return true;
}

void PrintHelp() {
  std::cout
    << std::endl << std::endl
    << "Usage: client [OPTIONS] [@]content_or_file ..." << std::endl
    << "A simple client to send content analysis requests to a running agent." << std::endl
    << "Without @ the content to analyze is the argument itself." << std::endl
    << "Otherwise the content is read from a file called 'content_or_file'." << std::endl
    << "Multiple [@]content_or_file arguments may be specified, each generates one request." << std::endl
    << std::endl << "Options:"  << std::endl
    << kArgConnector << "<connector> : one of 'download', 'attach' (default), 'bulk-data-entry', 'print', or 'file-transfer'" << std::endl
    << kArgRequestToken << "<unique-token> : defaults to 'req-12345'" << std::endl
    << kArgTag << "<tag> : defaults to 'dlp'" << std::endl
    << kArgUrl << "<url> : defaults to 'https://upload.example.com'" << std::endl
    << kArgDigest << "<digest> : defaults to 'sha256-123456'" << std::endl
    << kArgHelp << " : prints this help message" << std::endl;
}

ContentAnalysisRequest BuildRequest(const std::string& data) {
  std::string filepath;
  std::string filename;
  if (data[0] == '@') {
    filepath = data.substr(1);
    filename = filepath.substr(filepath.find_last_of("/\\") + 1);
  }

  ContentAnalysisRequest request;

  request.set_analysis_connector(connector);
  request.set_request_token(request_token);
  *request.add_tags() = tag;

  auto request_data = request.mutable_request_data();
  request_data->set_url(url);
  request_data->set_digest(digest);
  if (!filename.empty()) {
    request_data->set_filename(filename);
  }

  if (!data.empty()) {
    request.set_text_content(data);
  } else if (!filepath.empty()) {
    request.set_file_path(filepath);
  } else {
    std::cout << "[Demo] Specify text content or a file path." << std::endl;
    PrintHelp();
    return ContentAnalysisRequest();
  }

  return request;
}

void DumpResponse(int position, const ContentAnalysisResponse& response) {
  for (auto result : response.results()) {
    auto tag = result.has_tag() ? result.tag() : "<no-tag>";

    auto status = result.has_status()
      ? result.status()
      : ContentAnalysisResponse::Result::STATUS_UNKNOWN;
    std::string status_str;
    switch (status) {
    case ContentAnalysisResponse::Result::STATUS_UNKNOWN:
      status_str = "Unknown";
      break;
    case ContentAnalysisResponse::Result::SUCCESS:
      status_str = "Success";
      break;
    case ContentAnalysisResponse::Result::FAILURE:
      status_str = "Failure";
      break;
    default:
      status_str = "<Uknown>";
      break;
    }

    auto action =
      ContentAnalysisResponse::Result::TriggeredRule::ACTION_UNSPECIFIED;
    for (auto rule : result.triggered_rules()) {
      if (rule.has_action() && rule.action() > action)
        action = rule.action();
    }
    std::string action_str;
    switch (action) {
    case ContentAnalysisResponse::Result::TriggeredRule::ACTION_UNSPECIFIED:
      action_str = "allowed";
      break;
    case ContentAnalysisResponse::Result::TriggeredRule::REPORT_ONLY:
      action_str = "reported only";
      break;
    case ContentAnalysisResponse::Result::TriggeredRule::WARN:
      action_str = "warned";
      break;
    case ContentAnalysisResponse::Result::TriggeredRule::BLOCK:
      action_str = "blocked";
      break;
    }

    std::cout << "[Demo] Request " << position << " is " << action_str
      << " after " << tag
      << " analysis, status=" << status_str << std::endl;
  }
}

ContentAnalysisAcknowledgement BuildAcknowledgement(
    const std::string& request_token) {
  ContentAnalysisAcknowledgement ack;
  ack.set_request_token(request_token);
  ack.set_status(ContentAnalysisAcknowledgement::SUCCESS);
  return ack;
}

int HandleRequest(Client* client,
                  int position,
                  const ContentAnalysisRequest& request) {
  ContentAnalysisResponse response;
  int err = client->Send(request, &response);
  if (err != 0) {
    std::cout << "[Demo] Error sending request " << position << std::endl;
    return 1;
  } else if (response.results_size() == 0) {
    std::cout << "[Demo] Response " << position << " is missing a result"
              << std::endl;
    return 1;
  } else {
    DumpResponse(position, response);

    int err = client->Acknowledge(
        BuildAcknowledgement(request.request_token()));
    if (err != 0) {
      std::cout << "[Demo] Error sending ack " << position << std::endl;
    }

    return 1;
  }

  return 0;
}

int main(int argc, char* argv[]) {
  if (!ParseCommandLine(argc, argv)) {
    PrintHelp();
    return 1;
  }

  // Each client uses a unique name to identify itself with Google Chrome.
  auto client = Client::Create({"content_analysis_sdk"});
  if (!client) {
    std::cout << "[Demo] Error starting client" << std::endl;
    return 1;
  };

  for (int i = 0; i < datas.size(); ++i) {
    HandleRequest(client.get(), i + 1, BuildRequest(datas[i]));
  }

  return 0;
};
<commit_msg>Fix filepath condition in demo client (#52)<commit_after>// Copyright 2022 The Chromium Authors.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <iostream>
#include <string>
#include <vector>

#include "content_analysis/sdk/analysis_client.h"

using content_analysis::sdk::Client;
using content_analysis::sdk::ContentAnalysisRequest;
using content_analysis::sdk::ContentAnalysisResponse;
using content_analysis::sdk::ContentAnalysisAcknowledgement;

// Paramters used to build the request.
content_analysis::sdk::AnalysisConnector connector =
    content_analysis::sdk::FILE_ATTACHED;
std::string request_token = "req-12345";
std::string tag = "dlp";
std::string digest = "sha256-123456";
std::string url = "https://upload.example.com";
std::vector<std::string> datas;

// Command line parameters.
constexpr const char* kArgConnector = "--connector=";
constexpr const char* kArgRequestToken = "--request-token=";
constexpr const char* kArgTag = "--tag=";
constexpr const char* kArgDigest = "--digest=";
constexpr const char* kArgUrl = "--url=";
constexpr const char* kArgHelp = "--help";

bool ParseCommandLine(int argc, char* argv[]) {
  for (int i = 1; i < argc; ++i) {
    const std::string arg = argv[i];
    if (arg.find(kArgConnector) == 0) {
      std::string connector_str = arg.substr(strlen(kArgConnector));
      if (connector_str == "download") {
        connector = content_analysis::sdk::FILE_DOWNLOADED;
      } else if (connector_str == "attach") {
        connector = content_analysis::sdk::FILE_ATTACHED;
      } else if (connector_str == "bulk-data-entry") {
        connector = content_analysis::sdk::BULK_DATA_ENTRY;
      } else if (connector_str == "print") {
        connector = content_analysis::sdk::PRINT;
      } else if (connector_str == "file-transfer") {
        connector = content_analysis::sdk::FILE_TRANSFER;
      } else {
        std::cout << "[Demo] Incorrect command line arg: " << arg << std::endl;
        return false;
      }
    } else if (arg.find(kArgRequestToken) == 0) {
      request_token = arg.substr(strlen(kArgRequestToken));
    } else if (arg.find(kArgTag) == 0) {
      tag = arg.substr(strlen(kArgTag));
    } else if (arg.find(kArgDigest) == 0) {
      digest = arg.substr(strlen(kArgDigest));
    } else if (arg.find(kArgUrl) == 0) {
      url = arg.substr(strlen(kArgUrl));
    } else if (arg.find(kArgHelp) == 0) {
      return false;
    } else {
      datas.push_back(arg);
    }
  }

  return true;
}

void PrintHelp() {
  std::cout
    << std::endl << std::endl
    << "Usage: client [OPTIONS] [@]content_or_file ..." << std::endl
    << "A simple client to send content analysis requests to a running agent." << std::endl
    << "Without @ the content to analyze is the argument itself." << std::endl
    << "Otherwise the content is read from a file called 'content_or_file'." << std::endl
    << "Multiple [@]content_or_file arguments may be specified, each generates one request." << std::endl
    << std::endl << "Options:"  << std::endl
    << kArgConnector << "<connector> : one of 'download', 'attach' (default), 'bulk-data-entry', 'print', or 'file-transfer'" << std::endl
    << kArgRequestToken << "<unique-token> : defaults to 'req-12345'" << std::endl
    << kArgTag << "<tag> : defaults to 'dlp'" << std::endl
    << kArgUrl << "<url> : defaults to 'https://upload.example.com'" << std::endl
    << kArgDigest << "<digest> : defaults to 'sha256-123456'" << std::endl
    << kArgHelp << " : prints this help message" << std::endl;
}

ContentAnalysisRequest BuildRequest(const std::string& data) {
  std::string filepath;
  std::string filename;
  if (data[0] == '@') {
    filepath = data.substr(1);
    filename = filepath.substr(filepath.find_last_of("/\\") + 1);
  }

  ContentAnalysisRequest request;

  request.set_analysis_connector(connector);
  request.set_request_token(request_token);
  *request.add_tags() = tag;

  auto request_data = request.mutable_request_data();
  request_data->set_url(url);
  request_data->set_digest(digest);
  if (!filename.empty()) {
    request_data->set_filename(filename);
  }

  if (!filepath.empty()) {
    request.set_file_path(filepath);
  } else if (!data.empty()) {
    request.set_text_content(data);
  } else {
    std::cout << "[Demo] Specify text content or a file path." << std::endl;
    PrintHelp();
    return ContentAnalysisRequest();
  }

  return request;
}

void DumpResponse(int position, const ContentAnalysisResponse& response) {
  for (auto result : response.results()) {
    auto tag = result.has_tag() ? result.tag() : "<no-tag>";

    auto status = result.has_status()
      ? result.status()
      : ContentAnalysisResponse::Result::STATUS_UNKNOWN;
    std::string status_str;
    switch (status) {
    case ContentAnalysisResponse::Result::STATUS_UNKNOWN:
      status_str = "Unknown";
      break;
    case ContentAnalysisResponse::Result::SUCCESS:
      status_str = "Success";
      break;
    case ContentAnalysisResponse::Result::FAILURE:
      status_str = "Failure";
      break;
    default:
      status_str = "<Uknown>";
      break;
    }

    auto action =
      ContentAnalysisResponse::Result::TriggeredRule::ACTION_UNSPECIFIED;
    for (auto rule : result.triggered_rules()) {
      if (rule.has_action() && rule.action() > action)
        action = rule.action();
    }
    std::string action_str;
    switch (action) {
    case ContentAnalysisResponse::Result::TriggeredRule::ACTION_UNSPECIFIED:
      action_str = "allowed";
      break;
    case ContentAnalysisResponse::Result::TriggeredRule::REPORT_ONLY:
      action_str = "reported only";
      break;
    case ContentAnalysisResponse::Result::TriggeredRule::WARN:
      action_str = "warned";
      break;
    case ContentAnalysisResponse::Result::TriggeredRule::BLOCK:
      action_str = "blocked";
      break;
    }

    std::cout << "[Demo] Request " << position << " is " << action_str
      << " after " << tag
      << " analysis, status=" << status_str << std::endl;
  }
}

ContentAnalysisAcknowledgement BuildAcknowledgement(
    const std::string& request_token) {
  ContentAnalysisAcknowledgement ack;
  ack.set_request_token(request_token);
  ack.set_status(ContentAnalysisAcknowledgement::SUCCESS);
  return ack;
}

int HandleRequest(Client* client,
                  int position,
                  const ContentAnalysisRequest& request) {
  ContentAnalysisResponse response;
  int err = client->Send(request, &response);
  if (err != 0) {
    std::cout << "[Demo] Error sending request " << position << std::endl;
    return 1;
  } else if (response.results_size() == 0) {
    std::cout << "[Demo] Response " << position << " is missing a result"
              << std::endl;
    return 1;
  } else {
    DumpResponse(position, response);

    int err = client->Acknowledge(
        BuildAcknowledgement(request.request_token()));
    if (err != 0) {
      std::cout << "[Demo] Error sending ack " << position << std::endl;
    }

    return 1;
  }

  return 0;
}

int main(int argc, char* argv[]) {
  if (!ParseCommandLine(argc, argv)) {
    PrintHelp();
    return 1;
  }

  // Each client uses a unique name to identify itself with Google Chrome.
  auto client = Client::Create({"content_analysis_sdk"});
  if (!client) {
    std::cout << "[Demo] Error starting client" << std::endl;
    return 1;
  };

  for (int i = 0; i < datas.size(); ++i) {
    HandleRequest(client.get(), i + 1, BuildRequest(datas[i]));
  }

  return 0;
};
<|endoftext|>


<commit_before>#include <cubez/cubez.h>
#include <cubez/timer.h>

#include "ball.h"
#include "physics.h"
#include "player.h"
#include "log.h"
#include "mesh.h"
#include "mesh_builder.h"
#include "input.h"
#include "render.h"
#include "shader.h"
#include "planet.h"
#include "gui.h"

#include <algorithm>
#include <thread>
#include <unordered_map>

const char simple_vs[] = R"(
#version 200

in vec3 inPos;
in vec3 inCol;

out vec3 vCol;

void main() {
  vCol = inCol;
  gl_Position = vec4(inPos, 1.0);
}
)";

const char simple_fs[] = R"(
#version 130

in vec3 vCol;
out vec4 frag_color;

void main() {
  frag_color = vec4(vCol, 1.0);
}
)";

void check_for_gl_errors() {
  GLenum error = glGetError();
  if (error) {
    const GLubyte* error_str = gluErrorString(error);
    std::cout << "Error(" << error << "): " << error_str << std::endl;
  }
}

void initialize_universe(qbUniverse* uni) {
  qb_init(uni);

  {
    logging::initialize();
  }

  {
    physics::Settings settings;
    physics::initialize(settings);
  }

  {
    render::Settings s;
    s.title = "Cubez example";
    s.width = 1200;
    s.height = 800;
    s.znear = 0.1f;
    s.zfar = 10000.0f;
    s.fov = 70.0f;
    render::initialize(s);

    render::qb_camera_setyaw(90.0f);
    render::qb_camera_setpitch(0.0f);
    render::qb_camera_setposition({400.0f, -250.0f, 250.0f});

    check_for_gl_errors();
  }

  {
    input::initialize();
  }
  {
    /*

    // Operations done in the global scene (QB_GLOBAL_SCENE) will persist until
    // the game ends. By default, all API calls are executed on the global
    // scene.
    qb_scene_activate(QB_GLOBAL_SCENE);
    qb_texture_load(...);
    qb_model_load(...);

    // Create two scenes: one for the main menu, and then another scene that
    // holds all the game objects.
    qbScene main_menu;
    qbScene game_prefetch;
    qb_scene_create(&main_menu);
    qb_scene_create(&game_prefetch);

    // Sets the scene to be active. While the scene is active, all API calls
    // will only affect the active scene. The game loop will only run over
    // the active scene.
    qb_scene_activate(main_menu);
    qb_component_create(...);
    qb_entity_create(...);
    qb_material_create(...);
    qb_event_send(...);

    // "set"ing a scene will not run the game loop over it. All API calls
    // performed will only be executed on the "set" scene. The game loop will
    // NOT run over the "set" scene.
    qb_with_scene(game_prefetch, [](){
      qb_scene_push(game_prefetch);
      qb_entity_create(...);
      qb_model_load(...);
      qb_scene_pop();
    });

    ...

    // Once the user clicks on the "Start Game" button, activate the game scene
    // and purge the old scene.
    qb_button_press("MainMenu/StartGame", []() {
      qb_scene_activate(game_prefetch);
      qb_scene_destroy(main_menu);
    });

    */
  }

#if 1
  qbShader mesh_shader;
  qbTexture ball_texture;
  MeshBuilder block_mesh;
  qbMaterial ball_material;
  qbMaterial red_material;
  {
    // Load resources.
    std::cout << "Loading resources.\n";
    qb_shader_load(&mesh_shader, "mesh_shader", "resources/mesh.vs", "resources/mesh.fs");
    qb_texture_load(&ball_texture, "ball_texture", "resources/soccer_ball.bmp");
    block_mesh = MeshBuilder::FromFile("resources/block.obj");

    qbMaterialAttr attr;
    qb_materialattr_create(&attr);
    qb_materialattr_setcolor(attr, glm::vec4{ 1.0, 0.0, 1.0, 1.0 });
    qb_materialattr_addtexture(attr, ball_texture, {0, 0}, {0, 0});
    qb_materialattr_setshader(attr, mesh_shader);
    qb_material_create(&ball_material, attr);
    qb_materialattr_destroy(&attr);
  }
  {
    qbMaterialAttr attr;
    qb_materialattr_create(&attr);
    qb_materialattr_setcolor(attr, glm::vec4{ 1.0, 0.0, 0.0, 1.0 });
    qb_materialattr_setshader(attr, mesh_shader);
    qb_material_create(&red_material, attr);
    qb_materialattr_destroy(&attr);
  }

  {
    ball::Settings settings;
    settings.mesh = block_mesh.BuildRenderable(qbRenderMode::QB_TRIANGLES);
    settings.collision_mesh = new Mesh(block_mesh.BuildMesh());
    settings.material = ball_material;
    settings.material_exploded = red_material;

    ball::initialize(settings);
    check_for_gl_errors();
  }
#if 0
  {
    qbEntityAttr attr;
    qb_entityattr_create(&attr);

    physics::Transform t{{400.0f, 300.0f, -32.0f}, {}, true};
    qb_entityattr_addcomponent(attr, physics::component(), &t);

    qbMesh mesh;
    qb_mesh_load(&mesh, "floor_mesh", "C:\\Users\\Sam\\Source\\Repos\\cubez\\windows\\cubez\\x64\\Release\\floor.obj");
    render::create(mesh, ball_material);

    qbEntity unused;
    qb_entity_create(&unused, attr);

    qb_entityattr_destroy(&attr);
  }
#endif
  {
    player::Settings settings;
    settings.start_pos = {0, 0, 0};

    player::initialize(settings);
    check_for_gl_errors();
  }
  auto new_game = [mesh_shader](const framework::JSObject&, const framework::JSArgs&) {
    planet::Settings settings;
    settings.shader = mesh_shader;
    settings.resource_folder = "resources/";
    planet::Initialize(settings);

    return framework::JSValue();
  };

  {
    glm::vec2 menu_size(200, 500);
    glm::vec2 menu_pos(
      (render::window_width() / 2) - (menu_size.x / 2),
      (render::window_height() / 2) - (menu_size.y / 2)
     );

    gui::JSCallbackMap callbacks;
    callbacks["NewGame"] = new_game;

    gui::FromHtml(R"(

 New Game

 Load Game

 Exit

    )", menu_pos, menu_size, callbacks);
  }

#endif
}

int main(int, char* []) {
  // Create and initialize the game engine.
  qbUniverse uni;
  initialize_universe(&uni);

  qb_start();
  int frame = 0;
  WindowTimer fps_timer(50);
  WindowTimer update_timer(50);
  WindowTimer render_timer(50);

  double t = 0.0;
  const double dt = 0.01;
  double current_time = Timer::now() * 0.000000001;
  double start_time = Timer::now();
  double accumulator = 0.0;

  qb_loop();
  while (1) {
    fps_timer.start();

    double new_time = Timer::now() * 0.000000001;
    double frame_time = new_time - current_time;
    frame_time = std::min(0.25, frame_time);
    current_time = new_time;

    accumulator += frame_time;

    input::handle_input([](SDL_Event*) {
      render::shutdown();
      SDL_Quit();
      qb_stop();
      exit(0);
    });
    while (accumulator >= dt) {
      update_timer.start();
      qb_loop();
      update_timer.stop();
      update_timer.step();

      accumulator -= dt;
      t += dt;
    }

    render_timer.start();

    render::RenderEvent e;
    e.frame = frame;
    e.ftimestamp_us = Timer::now() - start_time;
    e.alpha = accumulator / dt;
    render::present(&e);

    render_timer.stop();
    render_timer.step();

    ++frame;
    fps_timer.stop();
    fps_timer.step();

    double time = Timer::now();

    static int prev_trigger = 0;
    static int trigger = 0;
    int period = 1;

    prev_trigger = trigger;
    trigger = int64_t(time - start_time) / 1000000000;
    if (rand() % 1000000000 == 0) {
      ball::create({(float)(rand() % 500) - 250.0f,
                    (float)(rand() % 500) - 250.0f,
                    (float)(rand() % 500) - 250.0f}, {}, true, true);
    }

    if (trigger % period == 0 && prev_trigger != trigger) {
      if ((int)(1e9 / update_timer.get_avg_elapsed_ns()) < 60) {
        std::cout << "BAD FPS\n";
      }
    //if (true && period && prev_trigger == prev_trigger && trigger == trigger) {
      std::cout << "Ball count " << qb_component_getcount(ball::Component()) << std::endl;
      double total = (1/60.0) * 1e9;
      //logging::out(
      std::cout <<
          "Frame " + std::to_string(frame) + "\n" +
          + "Utili: "  + std::to_string(100.0 * render_timer.get_avg_elapsed_ns() / total)
          + " : " + std::to_string(100.0 * update_timer.get_avg_elapsed_ns() / total) + "\n"
          + "Render FPS: " + std::to_string((int)(1e9 / render_timer.get_avg_elapsed_ns())) + "\n"
          + "Update FPS: " + std::to_string((int)(1e9 / update_timer.get_avg_elapsed_ns())) + "\n"
          + "Total FPS: " + std::to_string(1e9 / fps_timer.get_elapsed_ns()) + "\n"
          + "Accum: " + std::to_string(accumulator) + "\n"
          + "Alpha: " + std::to_string(accumulator / dt) + "\n";
    }
  }
}
<commit_msg>Test GUI<commit_after>#include <cubez/cubez.h>
#include <cubez/timer.h>

#include "ball.h"
#include "physics.h"
#include "player.h"
#include "log.h"
#include "mesh.h"
#include "mesh_builder.h"
#include "input.h"
#include "render.h"
#include "shader.h"
#include "planet.h"
#include "gui.h"

#include <algorithm>
#include <thread>
#include <unordered_map>

const char simple_vs[] = R"(
#version 200

in vec3 inPos;
in vec3 inCol;

out vec3 vCol;

void main() {
  vCol = inCol;
  gl_Position = vec4(inPos, 1.0);
}
)";

const char simple_fs[] = R"(
#version 130

in vec3 vCol;
out vec4 frag_color;

void main() {
  frag_color = vec4(vCol, 1.0);
}
)";

void check_for_gl_errors() {
  GLenum error = glGetError();
  if (error) {
    const GLubyte* error_str = gluErrorString(error);
    std::cout << "Error(" << error << "): " << error_str << std::endl;
  }
}

void initialize_universe(qbUniverse* uni) {
  qb_init(uni);

  {
    logging::initialize();
  }

  {
    physics::Settings settings;
    physics::initialize(settings);
  }

  {
    render::Settings s;
    s.title = "Cubez example";
    s.width = 1200;
    s.height = 800;
    s.znear = 0.1f;
    s.zfar = 10000.0f;
    s.fov = 70.0f;
    render::initialize(s);

    render::qb_camera_setyaw(90.0f);
    render::qb_camera_setpitch(0.0f);
    render::qb_camera_setposition({400.0f, -250.0f, 250.0f});

    check_for_gl_errors();
  }

  {
    input::initialize();
  }
  {
    /*

    // Operations done in the global scene (QB_GLOBAL_SCENE) will persist until
    // the game ends. By default, all API calls are executed on the global
    // scene.
    qb_scene_activate(QB_GLOBAL_SCENE);
    qb_texture_load(...);
    qb_model_load(...);

    // Create two scenes: one for the main menu, and then another scene that
    // holds all the game objects.
    qbScene main_menu;
    qbScene game_prefetch;
    qb_scene_create(&main_menu);
    qb_scene_create(&game_prefetch);

    // Sets the scene to be active. While the scene is active, all API calls
    // will only affect the active scene. The game loop will only run over
    // the active scene.
    qb_scene_activate(main_menu);
    qb_component_create(...);
    qb_entity_create(...);
    qb_material_create(...);
    qb_event_send(...);

    // "set"ing a scene will not run the game loop over it. All API calls
    // performed will only be executed on the "set" scene. The game loop will
    // NOT run over the "set" scene.
    qb_with_scene(game_prefetch, [](){
      qb_scene_push(game_prefetch);
      qb_entity_create(...);
      qb_model_load(...);
      qb_scene_pop();
    });

    ...

    // Once the user clicks on the "Start Game" button, activate the game scene
    // and purge the old scene.
    qb_button_press("MainMenu/StartGame", []() {
      qb_scene_activate(game_prefetch);
      qb_scene_destroy(main_menu);
    });

    */
  }

#if 1
  qbShader mesh_shader;
  qbTexture ball_texture;
  MeshBuilder block_mesh;
  qbMaterial ball_material;
  qbMaterial red_material;
  {
    // Load resources.
    std::cout << "Loading resources.\n";
    qb_shader_load(&mesh_shader, "mesh_shader", "resources/mesh.vs", "resources/mesh.fs");
    qb_texture_load(&ball_texture, "ball_texture", "resources/soccer_ball.bmp");
    block_mesh = MeshBuilder::FromFile("resources/block.obj");

    qbMaterialAttr attr;
    qb_materialattr_create(&attr);
    qb_materialattr_setcolor(attr, glm::vec4{ 1.0, 0.0, 1.0, 1.0 });
    qb_materialattr_addtexture(attr, ball_texture, {0, 0}, {0, 0});
    qb_materialattr_setshader(attr, mesh_shader);
    qb_material_create(&ball_material, attr);
    qb_materialattr_destroy(&attr);
  }
  {
    qbMaterialAttr attr;
    qb_materialattr_create(&attr);
    qb_materialattr_setcolor(attr, glm::vec4{ 1.0, 0.0, 0.0, 1.0 });
    qb_materialattr_setshader(attr, mesh_shader);
    qb_material_create(&red_material, attr);
    qb_materialattr_destroy(&attr);
  }

  {
    ball::Settings settings;
    settings.mesh = block_mesh.BuildRenderable(qbRenderMode::QB_TRIANGLES);
    settings.collision_mesh = new Mesh(block_mesh.BuildMesh());
    settings.material = ball_material;
    settings.material_exploded = red_material;

    ball::initialize(settings);
    check_for_gl_errors();
  }
#if 0
  {
    qbEntityAttr attr;
    qb_entityattr_create(&attr);

    physics::Transform t{{400.0f, 300.0f, -32.0f}, {}, true};
    qb_entityattr_addcomponent(attr, physics::component(), &t);

    qbMesh mesh;
    qb_mesh_load(&mesh, "floor_mesh", "C:\\Users\\Sam\\Source\\Repos\\cubez\\windows\\cubez\\x64\\Release\\floor.obj");
    render::create(mesh, ball_material);

    qbEntity unused;
    qb_entity_create(&unused, attr);

    qb_entityattr_destroy(&attr);
  }
#endif
  {
    player::Settings settings;
    settings.start_pos = {0, 0, 0};

    player::initialize(settings);
    check_for_gl_errors();
  }

  /*

  qbScene main_menu_scene;

  qb_scene_create(&main_menu_scene);
  qb_scene_push(main_menu_scene);

  qb_scene_pop();

  */

  auto new_game = [mesh_shader](const framework::JSObject&, const framework::JSArgs&) {
    planet::Settings settings;
    settings.shader = mesh_shader;
    settings.resource_folder = "resources/";
    planet::Initialize(settings);

    return framework::JSValue();
  };
  {
    planet::Settings settings;
    settings.shader = mesh_shader;
    settings.resource_folder = "resources/";
    planet::Initialize(settings);
  }
  {
    glm::vec2 menu_size(render::window_width(), render::window_height());
    glm::vec2 menu_pos(0, 0);

    gui::JSCallbackMap callbacks;
    callbacks["NewGame"] = new_game;

    //gui::FromFile("file:///game.html", menu_pos, menu_size, callbacks);
  }

#endif
}

int main(int, char* []) {
  // Create and initialize the game engine.
  qbUniverse uni;
  initialize_universe(&uni);

  qb_start();
  int frame = 0;
  WindowTimer fps_timer(50);
  WindowTimer update_timer(50);
  WindowTimer render_timer(50);

  double t = 0.0;
  const double dt = 0.01;
  double current_time = Timer::now() * 0.000000001;
  double start_time = Timer::now();
  double accumulator = 0.0;
  gui::qbRenderTarget target;
  gui::qb_rendertarget_create(&target, { 250, 0 }, { 500, 500 });

  qb_loop();
  while (1) {
    fps_timer.start();

    double new_time = Timer::now() * 0.000000001;
    double frame_time = new_time - current_time;
    frame_time = std::min(0.25, frame_time);
    current_time = new_time;

    accumulator += frame_time;

    input::handle_input([](SDL_Event*) {
      render::shutdown();
      SDL_Quit();
      qb_stop();
      exit(0);
    });
    while (accumulator >= dt) {
      update_timer.start();
      qb_loop();
      update_timer.stop();
      update_timer.step();

      accumulator -= dt;
      t += dt;
    }

    render_timer.start();

    render::RenderEvent e;
    e.frame = frame;
    e.ftimestamp_us = Timer::now() - start_time;
    e.alpha = accumulator / dt;
    render::present(&e);

    render_timer.stop();
    render_timer.step();

    ++frame;
    fps_timer.stop();
    fps_timer.step();

    double time = Timer::now();

    static int prev_trigger = 0;
    static int trigger = 0;
    int period = 1;

    prev_trigger = trigger;
    trigger = int64_t(time - start_time) / 1000000000;
    if (rand() % 1000000000 == 0) {
      ball::create({(float)(rand() % 500) - 250.0f,
                    (float)(rand() % 500) - 250.0f,
                    (float)(rand() % 500) - 250.0f}, {}, true, true);
    }

    if (trigger % period == 0 && prev_trigger != trigger) {
      if ((int)(1e9 / update_timer.get_avg_elapsed_ns()) < 60) {
        std::cout << "BAD FPS\n";
      }
    //if (true && period && prev_trigger == prev_trigger && trigger == trigger) {
      std::cout << "Ball count " << qb_component_getcount(ball::Component()) << std::endl;
      double total = (1/60.0) * 1e9;
      //logging::out(
      std::cout <<
          "Frame " + std::to_string(frame) + "\n" +
          + "Utili: "  + std::to_string(100.0 * render_timer.get_avg_elapsed_ns() / total)
          + " : " + std::to_string(100.0 * update_timer.get_avg_elapsed_ns() / total) + "\n"
          + "Render FPS: " + std::to_string((int)(1e9 / render_timer.get_avg_elapsed_ns())) + "\n"
          + "Update FPS: " + std::to_string((int)(1e9 / update_timer.get_avg_elapsed_ns())) + "\n"
          + "Total FPS: " + std::to_string(1e9 / fps_timer.get_elapsed_ns()) + "\n"
          + "Accum: " + std::to_string(accumulator) + "\n"
          + "Alpha: " + std::to_string(accumulator / dt) + "\n";
    }
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: basicio.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-16 15:53:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COMPHELPER_BASIC_IO_HXX_
#define _COMPHELPER_BASIC_IO_HXX_

#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_
#include <com/sun/star/io/XPersistObject.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif

#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif

//.........................................................................
namespace comphelper
{
//.........................................................................

namespace stario    = ::com::sun::star::io;
namespace staruno   = ::com::sun::star::uno;
namespace starawt   = ::com::sun::star::awt;

// sal_Bool
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Bool& _rVal);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Bool _bVal);

// ::rtl::OUString
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, ::rtl::OUString& _rStr);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, const ::rtl::OUString& _rStr);

// sal_Int16
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Int16& _rValue);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Int16 _nValue);

// sal_uInt16
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_uInt16& _rValue);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_uInt16 _nValue);

// sal_uInt32
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_uInt32& _rValue);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_uInt32 _nValue);

// sal_Int16
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Int32& _rValue);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Int32 _nValue);

// FontDescriptor
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& InStream, starawt::FontDescriptor& rVal);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& OutStream, const starawt::FontDescriptor& rVal);

// sequences
template <class ELEMENT>
const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, staruno::Sequence<ELEMENT>& _rSeq)
{
    sal_Int32 nLen = _rxInStream->readLong();
    _rSeq.realloc(nLen);
    if (nLen)
    {
        ELEMENT* pElement = _rSeq.getArray();
        for (sal_Int32 i=0; i<nLen; ++i, ++pElement)
            _rxInStream >> *pElement;
    }
    return _rxInStream;
}

template <class ELEMENT>
const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, const staruno::Sequence<ELEMENT>& _rSeq)
{
    sal_Int32 nLen = _rSeq.getLength();
    _rxOutStream->writeLong(nLen);
    if (nLen)
    {
        const ELEMENT* pElement = _rSeq.getConstArray();
        for (sal_Int32 i = 0; i < nLen; ++i, ++pElement)
            _rxOutStream << *pElement;
    }
    return _rxOutStream;
}

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif // _COMPHELPER_BASIC_IO_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.54); FILE MERGED 2005/09/05 15:23:38 rt 1.2.54.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basicio.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 02:27:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COMPHELPER_BASIC_IO_HXX_
#define _COMPHELPER_BASIC_IO_HXX_

#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_
#include <com/sun/star/io/XPersistObject.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif

#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif

//.........................................................................
namespace comphelper
{
//.........................................................................

namespace stario    = ::com::sun::star::io;
namespace staruno   = ::com::sun::star::uno;
namespace starawt   = ::com::sun::star::awt;

// sal_Bool
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Bool& _rVal);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Bool _bVal);

// ::rtl::OUString
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, ::rtl::OUString& _rStr);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, const ::rtl::OUString& _rStr);

// sal_Int16
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Int16& _rValue);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Int16 _nValue);

// sal_uInt16
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_uInt16& _rValue);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_uInt16 _nValue);

// sal_uInt32
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_uInt32& _rValue);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_uInt32 _nValue);

// sal_Int16
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Int32& _rValue);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Int32 _nValue);

// FontDescriptor
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& InStream, starawt::FontDescriptor& rVal);
COMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& OutStream, const starawt::FontDescriptor& rVal);

// sequences
template <class ELEMENT>
const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, staruno::Sequence<ELEMENT>& _rSeq)
{
    sal_Int32 nLen = _rxInStream->readLong();
    _rSeq.realloc(nLen);
    if (nLen)
    {
        ELEMENT* pElement = _rSeq.getArray();
        for (sal_Int32 i=0; i<nLen; ++i, ++pElement)
            _rxInStream >> *pElement;
    }
    return _rxInStream;
}

template <class ELEMENT>
const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, const staruno::Sequence<ELEMENT>& _rSeq)
{
    sal_Int32 nLen = _rSeq.getLength();
    _rxOutStream->writeLong(nLen);
    if (nLen)
    {
        const ELEMENT* pElement = _rSeq.getConstArray();
        for (sal_Int32 i = 0; i < nLen; ++i, ++pElement)
            _rxOutStream << *pElement;
    }
    return _rxOutStream;
}

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif // _COMPHELPER_BASIC_IO_HXX_

<|endoftext|>


<commit_before>#include "NeuralNetwork.hpp"

using namespace std;

NeuralNetwork::NeuralNetwork(const int ni, const int nh, const int no, const bool regression)
	: ni(ni+1), nh(nh+1), no(no), regression(regression), ai(ni, 1.0), ah(nh, 1.0), ao(no, 1.0)
{
	wi = NeuralNetwork::makeMatrix(ni, nh);
	wo = NeuralNetwork::makeMatrix(nh, no);

	uniform_real_distribution<float> dist(-1, 1);

	for (int i = 0; i < ni; i++) {
		for (int j = 0; j < nh; j++) {
			wi[i][j] = dist(rng);
		}
	}

	for (int i = 0; i < nh; i++) {
		for (int j = 0; j < no; j++) {
			wo[i][j] = dist(rng);
		}
	}

	ci = makeMatrix(ni, nh);
	co = makeMatrix(nh, no);

	cout << "Number of inputs: " << ni << endl;
	cout << "Number of hidden neuron layers: " << nh << endl;
	cout << "Number of outputs: " << no << endl;

	cout << "Size of input weights: " << wi.size() << endl;
	cout << "Size of output weights:" << wo.size() << endl;
}

vector<vector<float>> NeuralNetwork::makeMatrix(const int width, const int height, const float fill) {
	vector<vector<float>> matrix;
	for (int i = 0; i < width; i++) {
		matrix.push_back(vector<float>(height, fill));
	}

	return matrix;
}

float NeuralNetwork::sigmoid(const float x) {
    return tanh(x);
}

float NeuralNetwork::dsigmoid(const float y) {
    return 1.0 - y*y;
}

vector<float> NeuralNetwork::update(const vector<float>& inputs) {
        if (inputs.size() != ni-1) {
			throw string("wrong number of inputs");
		}

        for (unsigned int i = 0; i < ni-1; i++) {
            ai[i] = inputs[i];
		}

        for (unsigned int j = 0; j < nh-1; j++) {
            float total = 0.0;
            for (int i = 0; i < ni; i++) {
                total += ai[i] * wi[i][j];
			}

            ah[j] = sigmoid(total);
		}

        for (unsigned int k = 0; k < no; k++) {
            float total = 0.0;
            for (unsigned int j = 0; j < nh; j++) {
                total += ah[j] * wo[j][k];
			}

            ao[k] = total;
            if (!regression) {
                ao[k] = sigmoid(total);
			}
		}

        return ao;
}

float NeuralNetwork::backPropagate(const vector<float>& targets, const float lr, const float mf) {
	if (targets.size() != no) {
		throw string("wrong number of target values");
	}

	vector<float> output_deltas(no, 1.0);
	for (unsigned int k = 0; k < no; k++) {
		output_deltas[k] = targets[k] - ao[k];
		if (!regression) {
			output_deltas[k] = dsigmoid(ao[k])*output_deltas[k];
		}
	}

	vector<float> hidden_deltas(nh, 0.0);
	for (unsigned int j = 0; j < nh; j++) {
		float error = 0.0;
		for (unsigned int k = 0; k < no; k++) {
			error += output_deltas[k]*wo[j][k];
		}

		hidden_deltas[j] = dsigmoid(ah[j])*error;
	}

	for (unsigned int j = 0; j < nh; j++) {
		for (unsigned int k = 0; k < no; k++) {
			float change = output_deltas[k]*ah[j];
			wo[j][k] = wo[j][k] + lr*change + mf*co[j][k];
			co[j][k] = change;
		}
	}

	for (unsigned int i = 0; i < ni; i++) {
		for (unsigned int j = 0; j < nh; j++) {
			float change = hidden_deltas[j]*ai[i];
			wi[i][j] = wi[i][j] + lr*change + mf*ci[i][j];
			ci[i][j] = change;
		}
	}

	float error = 0.0;
	for (unsigned int k = 0; k < targets.size(); k++) {
		error += 0.5*((targets[k]-ao[k])*(targets[k]-ao[k]));
	}

	return error;
}

vector<vector<float>> NeuralNetwork::test(const vector<vector<vector<float>>>& patterns, const bool verbose) {
	vector<vector<float>> tmp;
	for (const auto& p : patterns) {
		if (verbose) {
			// cout << p[0] << " -> " << update(p[0]);
		}

		tmp.push_back(update(p[0]));
	}

	return tmp;
}

void NeuralNetwork::train(const vector<vector<vector<float>>>& patterns, const int iterations, const float lr, const float mf, const bool verbose) {
	for (int i = 0; i < iterations; i++) {
		float error = 0;

		for (const auto& p : patterns) {
			update(p[0]);
			float tmp = backPropagate(p[1], lr, mf);
			error += tmp;
		}

		if (i % 100 == 0) {
			cout << "error rate = " << error << endl;
		}
	}
}

<commit_msg>Fixed bug causing a segfault<commit_after>#include "NeuralNetwork.hpp"

using namespace std;

NeuralNetwork::NeuralNetwork(const int nbi, const int nbh, const int nbo, const bool regression)
	: ni(nbi+1), nh(nbh+1), no(nbo), regression(regression), ai(ni, 1.0), ah(nh, 1.0), ao(no, 1.0)
{
	wi = NeuralNetwork::makeMatrix(ni, nh);
	wo = NeuralNetwork::makeMatrix(nh, no);

	uniform_real_distribution<float> dist(-1, 1);

	for (int i = 0; i < ni; i++) {
		for (int j = 0; j < nh; j++) {
			wi[i][j] = dist(rng);
		}
	}

	for (int j = 0; j < nh; j++) {
		for (int k = 0; k < no; k++) {
			wo[j][k] = dist(rng);
		}
	}

	ci = makeMatrix(ni, nh);
	co = makeMatrix(nh, no);

	cout << "Number of inputs: " << ni << endl;
	cout << "Number of hidden neuron layers: " << nh << endl;
	cout << "Number of outputs: " << no << endl;

	cout << "Size of input weights: " << wi.size() << endl;
	cout << "Size of output weights:" << wo.size() << endl;
}

vector<vector<float>> NeuralNetwork::makeMatrix(const int width, const int height, const float fill) {
	vector<vector<float>> matrix;
	for (int i = 0; i < width; i++) {
		matrix.push_back(vector<float>(height, fill));
	}

	return matrix;
}

float NeuralNetwork::sigmoid(const float x) {
    return tanh(x);
}

float NeuralNetwork::dsigmoid(const float y) {
    return 1.0 - y*y;
}

vector<float> NeuralNetwork::update(const vector<float>& inputs) {
        if (inputs.size() != ni-1) {
			throw string("wrong number of inputs");
		}

        for (unsigned int i = 0; i < ni-1; i++) {
            ai[i] = inputs[i];
		}

        for (unsigned int j = 0; j < nh-1; j++) {
            float total = 0.0;
            for (int i = 0; i < ni; i++) {
                total += ai[i] * wi[i][j];
			}

            ah[j] = sigmoid(total);
		}

        for (unsigned int k = 0; k < no; k++) {
            float total = 0.0;
            for (unsigned int j = 0; j < nh; j++) {
                total += ah[j] * wo[j][k];
			}

            ao[k] = total;
            if (!regression) {
                ao[k] = sigmoid(total);
			}
		}

        return ao;
}

float NeuralNetwork::backPropagate(const vector<float>& targets, const float lr, const float mf) {
	if (targets.size() != no) {
		throw string("wrong number of target values");
	}

	vector<float> output_deltas(no, 1.0);
	for (unsigned int k = 0; k < no; k++) {
		output_deltas[k] = targets[k] - ao[k];
		if (!regression) {
			output_deltas[k] = dsigmoid(ao[k])*output_deltas[k];
		}
	}

	vector<float> hidden_deltas(nh, 0.0);
	for (unsigned int j = 0; j < nh; j++) {
		float error = 0.0;
		for (unsigned int k = 0; k < no; k++) {
			error += output_deltas[k]*wo[j][k];
		}

		hidden_deltas[j] = dsigmoid(ah[j])*error;
	}

	for (unsigned int j = 0; j < nh; j++) {
		for (unsigned int k = 0; k < no; k++) {
			float change = output_deltas[k]*ah[j];
			wo[j][k] = wo[j][k] + lr*change + mf*co[j][k];
			co[j][k] = change;
		}
	}

	for (unsigned int i = 0; i < ni; i++) {
		for (unsigned int j = 0; j < nh; j++) {
			float change = hidden_deltas[j]*ai[i];
			wi[i][j] = wi[i][j] + lr*change + mf*ci[i][j];
			ci[i][j] = change;
		}
	}

	float error = 0.0;
	for (unsigned int k = 0; k < targets.size(); k++) {
		error += 0.5*((targets[k]-ao[k])*(targets[k]-ao[k]));
	}

	return error;
}

vector<vector<float>> NeuralNetwork::test(const vector<vector<vector<float>>>& patterns, const bool verbose) {
	vector<vector<float>> tmp;
	for (const auto& p : patterns) {
		if (verbose) {
			// cout << p[0] << " -> " << update(p[0]);
		}

		tmp.push_back(update(p[0]));
	}

	return tmp;
}

void NeuralNetwork::train(const vector<vector<vector<float>>>& patterns, const int iterations, const float lr, const float mf, const bool verbose) {
	for (int i = 0; i < iterations; i++) {
		float error = 0;

		for (const auto& p : patterns) {
			update(p[0]);
			float tmp = backPropagate(p[1], lr, mf);
			error += tmp;
		}

		if (i % 100 == 0) {
			cout << "error rate = " << error << endl;
		}
	}
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Lech Kulina
 *
 * This file is part of the Realms Of Steel.
 * For conditions of distribution and use, see copyright details in the LICENSE file.
 */
#include <iostream>
#include <Application/Logger.h>

ros::LoggerPtr ros::Logger::logger;

ros::LoggerPtr ros::Logger::Create(const PropertyTree& config) {
    if (logger) {
        return logger;
    }

    logger.reset(new Logger());
    if (!logger->Init(config)) {
        logger.reset();
    }

    return logger;
}

bool ros::Logger::Init(const PropertyTree& config) {
    if (!LogsSink::Init(config)) {
        return false;
    }

    for (PropertyConstIter iter = config.begin(); iter != config.end(); ++iter) {
        if (iter->first == "Sink") {
            LogsSinkPtr sink = LogsSink::Create(iter->second);
            if (sink) {
                sinks.push_back(sink);
            }
        }
    }

    return true;
}

bool ros::Logger::SendMessage(const LogMessage& message) {
    if (!IsMessageAccepted(message)) {
        return false;
    }

    for (LogsSinksIter iter = sinks.begin(); iter != sinks.end(); ++iter) {
        LogsSinkPtr sink = *iter;
        if (sink->IsMessageAccepted(message) && !sink->SendMessage(message)) {
            return false;
        }
    }

    return true;
}

void ros::Logger::FlushMessages() {
    for (LogsSinksIter iter = sinks.begin(); iter != sinks.end(); ++iter) {
        (*iter)->FlushMessages();
    }
}
<commit_msg>Fail logger initialization when there are not sinks available<commit_after>/*
 * Copyright (c) 2016 Lech Kulina
 *
 * This file is part of the Realms Of Steel.
 * For conditions of distribution and use, see copyright details in the LICENSE file.
 */
#include <iostream>
#include <Application/Logger.h>

ros::LoggerPtr ros::Logger::logger;

ros::LoggerPtr ros::Logger::Create(const PropertyTree& config) {
    if (logger) {
        return logger;
    }

    logger.reset(new Logger());
    if (!logger->Init(config)) {
        logger.reset();
    }

    return logger;
}

bool ros::Logger::Init(const PropertyTree& config) {
    if (!LogsSink::Init(config)) {
        return false;
    }

    for (PropertyConstIter iter = config.begin(); iter != config.end(); ++iter) {
        if (iter->first == "Sink") {
            LogsSinkPtr sink = LogsSink::Create(iter->second);
            if (sink) {
                sinks.push_back(sink);
            }
        }
    }

    if (sinks.empty()) {
        std::cerr << "Failed to initialize logger: There are no sinks" << std::endl;
        return false;
    }

    return true;
}

bool ros::Logger::SendMessage(const LogMessage& message) {
    if (!IsMessageAccepted(message)) {
        return false;
    }

    for (LogsSinksIter iter = sinks.begin(); iter != sinks.end(); ++iter) {
        LogsSinkPtr sink = *iter;
        if (sink->IsMessageAccepted(message) && !sink->SendMessage(message)) {
            return false;
        }
    }

    return true;
}

void ros::Logger::FlushMessages() {
    for (LogsSinksIter iter = sinks.begin(); iter != sinks.end(); ++iter) {
        (*iter)->FlushMessages();
    }
}
<|endoftext|>