<commit_before>#pragma once

#include "geometry/shapes/ray.hh"
#include "intersection.hh"

#include "eigen.hh"

#include <limits>

namespace geometry {
namespace spatial {

// Axis aligned bounding box, with some nice geometric helpers.
template <int DIM = 3, typename Scalar = double>
class BoundingBox {
 public:
  using Vec = Eigen::Matrix<Scalar, DIM, 1>;

  // Expand to contain a point
  void expand(const Vec &point) {
    lower_ = lower_.cwiseMin(point);
    upper_ = upper_.cwiseMax(point);
  }

  // Expand to contain another axis-aligned bounding box
  void expand(const BoundingBox<DIM> &box) {
    expand(box.lower());
    expand(box.upper());
  }

  bool contains(const Vec &point) const {
    return (point.array() < upper_.array()).all() &&
           (point.array() > lower_.array()).all();
  }

  Vec center() const {
    return (upper_ + lower_) * 0.5;
  }

  double surface_area() const {
    static_assert(DIM == 3, "Dimension must be 3 because how do I higher dimensions?");
    const Vec delta = upper_ - lower_;
    double sa = 0.0;
    for (int i = 0; i < DIM; ++i) {
      sa += 2.0 * delta(i) * delta((i + 1) % DIM);
    }
    return sa;
  }

  // Compute an intersection using the slab method
  Intersection intersect(const Ray &ray) const {
    static_assert(DIM == 3, "Dimension must be 3 because rays are of dim 3 so");

    double max_t_near = std::numeric_limits<double>::lowest();
    double min_t_far = std::numeric_limits<double>::max();

    for (int i = 0; i < DIM; ++i) {
      // Note: We're really just trying to avoid denormals, in principle the operations
      // that follow are permissible for arbitrary nonzero floats
      constexpr double EPS = 1e-10;
      if (std::abs(ray.direction(i)) < EPS) {
        if (ray.origin(i) < lower_(i) || ray.origin(i) > upper_(i)) {
          return {-1.0, false};
        }
      }

      const double inv_direction_i = 1.0 / ray.direction(i);
      const double t1 = (lower_(i) - ray.origin(i)) * inv_direction_i;
      const double t2 = (upper_(i) - ray.origin(i)) * inv_direction_i;

      const double t_near = std::min(t1, t2);
      const double t_far = std::max(t1, t2);

      max_t_near = std::max(max_t_near, t_near);
      min_t_far = std::min(min_t_far, t_far);
    }

    Intersection intersection;
    if (contains(ray.origin)) {
      intersection.intersected = true;
      intersection.distance = min_t_far;
    } else {
      intersection.intersected = (max_t_near < min_t_far) && max_t_near >= 0.0;
      intersection.distance = max_t_near;
    }
    return intersection;
  }

  Eigen::Vector3d nearest_point(const Eigen::Vector3d &point) const {
    static_assert(DIM == 3, "Dimension must be 3 (I think...)");
    using Vec3 = Eigen::Vector3d;
    const Vec3 pc = point - center();
    const Vec3 b = upper() - center();
    const Vec3 abs_pt = (pc.cwiseAbs() - b).cwiseMax(Vec3::Zero());
    return point - (abs_pt.array() * pc.cwiseSign().array()).matrix();
  }

  double ud_box(const Eigen::Vector3d &point) const {
    static_assert(DIM == 3, "Dimension must be 3 (I think...)");
    using Vec3 = Eigen::Vector3d;
    const Vec3 pc = point - center();
    const Vec3 b = upper() - center();
    return (pc.cwiseAbs() - b).cwiseMax(Vec3::Zero()).norm();
  }

  const Vec &lower() const {
    return lower_;
  }

  const Vec &upper() const {
    return upper_;
  }

 private:
  Vec lower_ = Vec::Ones() * std::numeric_limits<double>::max();
  Vec upper_ = Vec::Ones() * std::numeric_limits<double>::lowest();
};
}  // namespace spatial
}  // namespace geometry
<commit_msg>Fix reference to intersection header in bounding box<commit_after>#pragma once

#include "geometry/shapes/ray.hh"
#include "geometry/spatial/intersection.hh"

#include "eigen.hh"

#include <limits>

namespace geometry {
namespace spatial {

// Axis aligned bounding box, with some nice geometric helpers.
template <int DIM = 3, typename Scalar = double>
class BoundingBox {
 public:
  using Vec = Eigen::Matrix<Scalar, DIM, 1>;

  // Expand to contain a point
  void expand(const Vec &point) {
    lower_ = lower_.cwiseMin(point);
    upper_ = upper_.cwiseMax(point);
  }

  // Expand to contain another axis-aligned bounding box
  void expand(const BoundingBox<DIM> &box) {
    expand(box.lower());
    expand(box.upper());
  }

  bool contains(const Vec &point) const {
    return (point.array() < upper_.array()).all() &&
           (point.array() > lower_.array()).all();
  }

  Vec center() const {
    return (upper_ + lower_) * 0.5;
  }

  double surface_area() const {
    static_assert(DIM == 3, "Dimension must be 3 because how do I higher dimensions?");
    const Vec delta = upper_ - lower_;
    double sa = 0.0;
    for (int i = 0; i < DIM; ++i) {
      sa += 2.0 * delta(i) * delta((i + 1) % DIM);
    }
    return sa;
  }

  // Compute an intersection using the slab method
  Intersection intersect(const Ray &ray) const {
    static_assert(DIM == 3, "Dimension must be 3 because rays are of dim 3 so");

    double max_t_near = std::numeric_limits<double>::lowest();
    double min_t_far = std::numeric_limits<double>::max();

    for (int i = 0; i < DIM; ++i) {
      // Note: We're really just trying to avoid denormals, in principle the operations
      // that follow are permissible for arbitrary nonzero floats
      constexpr double EPS = 1e-10;
      if (std::abs(ray.direction(i)) < EPS) {
        if (ray.origin(i) < lower_(i) || ray.origin(i) > upper_(i)) {
          return {-1.0, false};
        }
      }

      const double inv_direction_i = 1.0 / ray.direction(i);
      const double t1 = (lower_(i) - ray.origin(i)) * inv_direction_i;
      const double t2 = (upper_(i) - ray.origin(i)) * inv_direction_i;

      const double t_near = std::min(t1, t2);
      const double t_far = std::max(t1, t2);

      max_t_near = std::max(max_t_near, t_near);
      min_t_far = std::min(min_t_far, t_far);
    }

    Intersection intersection;
    if (contains(ray.origin)) {
      intersection.intersected = true;
      intersection.distance = min_t_far;
    } else {
      intersection.intersected = (max_t_near < min_t_far) && max_t_near >= 0.0;
      intersection.distance = max_t_near;
    }
    return intersection;
  }

  Eigen::Vector3d nearest_point(const Eigen::Vector3d &point) const {
    static_assert(DIM == 3, "Dimension must be 3 (I think...)");
    using Vec3 = Eigen::Vector3d;
    const Vec3 pc = point - center();
    const Vec3 b = upper() - center();
    const Vec3 abs_pt = (pc.cwiseAbs() - b).cwiseMax(Vec3::Zero());
    return point - (abs_pt.array() * pc.cwiseSign().array()).matrix();
  }

  double ud_box(const Eigen::Vector3d &point) const {
    static_assert(DIM == 3, "Dimension must be 3 (I think...)");
    using Vec3 = Eigen::Vector3d;
    const Vec3 pc = point - center();
    const Vec3 b = upper() - center();
    return (pc.cwiseAbs() - b).cwiseMax(Vec3::Zero()).norm();
  }

  const Vec &lower() const {
    return lower_;
  }

  const Vec &upper() const {
    return upper_;
  }

 private:
  Vec lower_ = Vec::Ones() * std::numeric_limits<double>::max();
  Vec upper_ = Vec::Ones() * std::numeric_limits<double>::lowest();
};
}  // namespace spatial
}  // namespace geometry
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "cnttransformname.h"

#include <QDebug>

QList<CContactItemField *> CntTransformName::transformDetailL(const QContactDetail &detail)
{
    if(detail.definitionName() != QContactName::DefinitionName)
       User::Leave(KErrArgument);

    QList<CContactItemField *> fieldList;

    //cast to name
    const QContactName &name(static_cast<const QContactName&>(detail));

    //create new fields without contexts
    transformToTextFieldL(name, fieldList, name.prefix(), KUidContactFieldPrefixName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.firstName(), KUidContactFieldGivenName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.middleName(), KUidContactFieldAdditionalName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.lastName(), KUidContactFieldFamilyName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.suffix(), KUidContactFieldSuffixName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.customLabel(), KUidContactFieldTemplateLabel, KUidContactFieldVCardMapUnusedN, false);

    return fieldList;
}

QContactDetail *CntTransformName::transformItemField(const CContactItemField& field, const QContact &contact)
{
    QContactName *name = new QContactName(contact.detail<QContactName>());

    CContactTextField* storage = field.TextStorage();
    QString nameValue = QString::fromUtf16(storage->Text().Ptr(), storage->Text().Length());

    for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) {
        //Prefix
        if (field.ContentType().FieldType(i) == KUidContactFieldPrefixName) {
            name->setPrefix(nameValue);
        }
        //First name
        else if (field.ContentType().FieldType(i) == KUidContactFieldGivenName) {
            name->setFirstName(nameValue);
        }
        //Middle name
        else if (field.ContentType().FieldType(i) == KUidContactFieldAdditionalName) {
            name->setMiddleName(nameValue);
        }
        //Last name
        else if (field.ContentType().FieldType(i) == KUidContactFieldFamilyName) {
            name->setLastName(nameValue);
        }
        //Suffix
        else if (field.ContentType().FieldType(i) == KUidContactFieldSuffixName) {
            name->setSuffix(nameValue);
        }
        // custom label
        else if (field.ContentType().FieldType(i) == KUidContactFieldTemplateLabel) {
            name->setCustomLabel(nameValue);
        }
    }

    return name;
}

bool CntTransformName::supportsField(TUint32 fieldType) const
{
    bool ret = false;
    if (fieldType == KUidContactFieldPrefixName.iUid
        || fieldType == KUidContactFieldGivenName.iUid
        || fieldType == KUidContactFieldAdditionalName.iUid
        || fieldType == KUidContactFieldFamilyName.iUid
        || fieldType == KUidContactFieldSuffixName.iUid
        || fieldType == KUidContactFieldTemplateLabel.iUid ) {
        ret = true;
    }
    return ret;
}

bool CntTransformName::supportsDetail(QString detailName) const
{
    bool ret = false;
    if (detailName == QContactName::DefinitionName) {
        ret = true;
    }
    return ret;
}

QList<TUid> CntTransformName::supportedSortingFieldTypes(QString detailFieldName) const
{
    QList<TUid> uids;

    if (detailFieldName == QContactName::FieldPrefix)
        return uids << KUidContactFieldPrefixName;

    if (detailFieldName == QContactName::FieldFirst)
        return uids << KUidContactFieldGivenName;

    if (detailFieldName == QContactName::FieldMiddle)
        return uids << KUidContactFieldAdditionalName;

    if (detailFieldName == QContactName::FieldLast)
        return uids << KUidContactFieldFamilyName;

    if (detailFieldName == QContactName::FieldSuffix)
        return uids << KUidContactFieldSuffixName;

    if (detailFieldName == QContactName::FieldCustomLabel)
        return uids << KUidContactFieldTemplateLabel;

    return uids;
}

/*!
 * Checks whether the subtype is supported
 *
 * \a subType The subtype to be checked
 * \return True if this subtype is supported
 */
bool CntTransformName::supportsSubType(const QString& subType) const
{
    Q_UNUSED(subType);
    return false;
}

/*!
 * Returns the filed id corresponding to a field
 *
 * \a fieldName The name of the supported field
 * \return fieldId for the fieldName, 0  if not supported
 */
quint32 CntTransformName::getIdForField(const QString& fieldName) const
{
    if (QContactName::FieldPrefix == fieldName)
        return KUidContactFieldPrefixName.iUid;
    else if (QContactName::FieldFirst == fieldName)
        return KUidContactFieldGivenName.iUid;
    else if (QContactName::FieldMiddle == fieldName)
        return KUidContactFieldAdditionalName.iUid;
    else if (QContactName::FieldLast == fieldName)
        return KUidContactFieldFamilyName.iUid;
    else if (QContactName::FieldSuffix == fieldName)
        return KUidContactFieldSuffixName.iUid;
    else if (QContactName::FieldCustomLabel == fieldName)
        return KUidContactFieldTemplateLabel.iUid;
    else
        return 0;
}

/*!
 * Modifies the detail definitions. The default detail definitions are
 * queried from QContactManagerEngine::schemaDefinitions and then modified
 * with this function in the transform leaf classes.
 *
 * \a definitions The detail definitions to modify.
 * \a contactType The contact type the definitions apply for.
 */
void CntTransformName::detailDefinitions(QMap<QString, QContactDetailDefinition> &definitions, const QString& contactType) const
{
    if(definitions.contains(QContactName::DefinitionName)) {
        QContactDetailDefinition d = definitions.value(QContactName::DefinitionName);
        QMap<QString, QContactDetailFieldDefinition> fields = d.fields();

        // groups support only custom label
        if(contactType == QContactType::TypeGroup) {
            fields.remove(QContactName::FieldPrefix);
            fields.remove(QContactName::FieldFirst);
            fields.remove(QContactName::FieldMiddle);
            fields.remove(QContactName::FieldLast);
            fields.remove(QContactName::FieldSuffix);
        } else {
            // Note: Custom labels cannot be enabled for a contact in pre-10.1
            // platforms because setting custom label for a contact causes
            // issues for S60 Phonebook editor. If custom label support is
            // needed in 10.1 or later, it needs to be variated away from
            // pre-10.1 platforms.
            fields.remove(QContactName::FieldCustomLabel);
        }

        // Context not supported in symbian back-end, remove
        fields.remove(QContactName::FieldContext);

        d.setFields(fields);
        d.setUnique(true);

        // Replace original definitions
        definitions.insert(d.name(), d);
    }
}
<commit_msg>Fixing contact saving with custom label in symbian backend<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "cnttransformname.h"

#include <QDebug>

QList<CContactItemField *> CntTransformName::transformDetailL(const QContactDetail &detail)
{
    if(detail.definitionName() != QContactName::DefinitionName)
       User::Leave(KErrArgument);

    QList<CContactItemField *> fieldList;

    //cast to name
    const QContactName &name(static_cast<const QContactName&>(detail));

    //create new fields without contexts
    transformToTextFieldL(name, fieldList, name.prefix(), KUidContactFieldPrefixName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.firstName(), KUidContactFieldGivenName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.middleName(), KUidContactFieldAdditionalName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.lastName(), KUidContactFieldFamilyName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.suffix(), KUidContactFieldSuffixName, KUidContactFieldVCardMapUnusedN, false);
    transformToTextFieldL(name, fieldList, name.customLabel(), KUidContactFieldTemplateLabel, KUidContactFieldVCardMapUnusedN, false);

    return fieldList;
}

QContactDetail *CntTransformName::transformItemField(const CContactItemField& field, const QContact &contact)
{
    QContactName *name = new QContactName(contact.detail<QContactName>());

    CContactTextField* storage = field.TextStorage();
    QString nameValue = QString::fromUtf16(storage->Text().Ptr(), storage->Text().Length());

    for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) {
        //Prefix
        if (field.ContentType().FieldType(i) == KUidContactFieldPrefixName) {
            name->setPrefix(nameValue);
        }
        //First name
        else if (field.ContentType().FieldType(i) == KUidContactFieldGivenName) {
            name->setFirstName(nameValue);
        }
        //Middle name
        else if (field.ContentType().FieldType(i) == KUidContactFieldAdditionalName) {
            name->setMiddleName(nameValue);
        }
        //Last name
        else if (field.ContentType().FieldType(i) == KUidContactFieldFamilyName) {
            name->setLastName(nameValue);
        }
        //Suffix
        else if (field.ContentType().FieldType(i) == KUidContactFieldSuffixName) {
            name->setSuffix(nameValue);
        }
        // custom label
        else if (field.ContentType().FieldType(i) == KUidContactFieldTemplateLabel) {
            name->setCustomLabel(nameValue);
        }
    }

    return name;
}

bool CntTransformName::supportsField(TUint32 fieldType) const
{
    bool ret = false;
    if (fieldType == KUidContactFieldPrefixName.iUid
        || fieldType == KUidContactFieldGivenName.iUid
        || fieldType == KUidContactFieldAdditionalName.iUid
        || fieldType == KUidContactFieldFamilyName.iUid
        || fieldType == KUidContactFieldSuffixName.iUid
        || fieldType == KUidContactFieldTemplateLabel.iUid ) {
        ret = true;
    }
    return ret;
}

bool CntTransformName::supportsDetail(QString detailName) const
{
    bool ret = false;
    if (detailName == QContactName::DefinitionName) {
        ret = true;
    }
    return ret;
}

QList<TUid> CntTransformName::supportedSortingFieldTypes(QString detailFieldName) const
{
    QList<TUid> uids;

    if (detailFieldName == QContactName::FieldPrefix)
        return uids << KUidContactFieldPrefixName;

    if (detailFieldName == QContactName::FieldFirst)
        return uids << KUidContactFieldGivenName;

    if (detailFieldName == QContactName::FieldMiddle)
        return uids << KUidContactFieldAdditionalName;

    if (detailFieldName == QContactName::FieldLast)
        return uids << KUidContactFieldFamilyName;

    if (detailFieldName == QContactName::FieldSuffix)
        return uids << KUidContactFieldSuffixName;

    if (detailFieldName == QContactName::FieldCustomLabel)
        return uids << KUidContactFieldTemplateLabel;

    return uids;
}

/*!
 * Checks whether the subtype is supported
 *
 * \a subType The subtype to be checked
 * \return True if this subtype is supported
 */
bool CntTransformName::supportsSubType(const QString& subType) const
{
    Q_UNUSED(subType);
    return false;
}

/*!
 * Returns the filed id corresponding to a field
 *
 * \a fieldName The name of the supported field
 * \return fieldId for the fieldName, 0  if not supported
 */
quint32 CntTransformName::getIdForField(const QString& fieldName) const
{
    if (QContactName::FieldPrefix == fieldName)
        return KUidContactFieldPrefixName.iUid;
    else if (QContactName::FieldFirst == fieldName)
        return KUidContactFieldGivenName.iUid;
    else if (QContactName::FieldMiddle == fieldName)
        return KUidContactFieldAdditionalName.iUid;
    else if (QContactName::FieldLast == fieldName)
        return KUidContactFieldFamilyName.iUid;
    else if (QContactName::FieldSuffix == fieldName)
        return KUidContactFieldSuffixName.iUid;
    else if (QContactName::FieldCustomLabel == fieldName)
        return KUidContactFieldTemplateLabel.iUid;
    else
        return 0;
}

/*!
 * Modifies the detail definitions. The default detail definitions are
 * queried from QContactManagerEngine::schemaDefinitions and then modified
 * with this function in the transform leaf classes.
 *
 * \a definitions The detail definitions to modify.
 * \a contactType The contact type the definitions apply for.
 */
void CntTransformName::detailDefinitions(QMap<QString, QContactDetailDefinition> &definitions, const QString& contactType) const
{
    if(definitions.contains(QContactName::DefinitionName)) {
        QContactDetailDefinition d = definitions.value(QContactName::DefinitionName);
        QMap<QString, QContactDetailFieldDefinition> fields = d.fields();

        // groups support only custom label
        if(contactType == QContactType::TypeGroup) {
            fields.remove(QContactName::FieldPrefix);
            fields.remove(QContactName::FieldFirst);
            fields.remove(QContactName::FieldMiddle);
            fields.remove(QContactName::FieldLast);
            fields.remove(QContactName::FieldSuffix);
        } else {
            // Note: Custom labels cannot be enabled for a contact in pre-10.1
            // platforms because setting custom label for a contact causes
            // issues for S60 Phonebook editor. If custom label support is
            // needed in 10.1 or later, it needs to be variated away from
            // pre-10.1 platforms.
#ifndef SYMBIAN_BACKEND_USE_SQLITE
            fields.remove(QContactName::FieldCustomLabel);
#endif
        }

        // Context not supported in symbian back-end, remove
        fields.remove(QContactName::FieldContext);

        d.setFields(fields);
        d.setUnique(true);

        // Replace original definitions
        definitions.insert(d.name(), d);
    }
}
<|endoftext|>


<commit_before>#include "Host.h"
#include <math.h> // ceil

static const int INITIAL_WINDOW_SIZE = 0; // TODO: change this number
static const int DATA_PKT_SIZE = 1; // TODO: change this number

Host::Host(CongestionAlg congestion_algorithm , Link& host_link, float rt) : my_link(host_link)
{
    window_size = INITIAL_WINDOW_SIZE;
    congestion_alg = congestion_algorithm;
    my_link = host_link;
    packet_id = 0;
    unack_packets = 0;
    RTO = rt;
}

void Host::addFlow(std::string dest, float data_size)
{
    float temp_num_pkts = data_size / DATA_PKT_SIZE;
    int num_packets = (int) ceil(temp_num_pkts);

    std::queue<Packet> flow;

    for (int count = 0; count < num_packets; count++){
        std::string pack_id = this->uuid + std::to_string(packet_id);
        Packet new_packet(pack_id, dest, this->uuid, DATA_PKT_SIZE, false, false, count+1);
        flow.push(new_packet);
        packet_id++;
    }

    packet_queue.addQueue(flow);
}

void Host::sendPacket(Packet new_pack, int time_now)
{
    // Insert packet to the eventHeap
    PacketEvent packet_event = PacketEvent(new_pack, new_pack.final_dest, new_pack.source, time_now);
    eventHeap.push(packet_event);

    // Insert to the eventHeap an event which is triggered once a packet has timed out
    UnackEvent unack_event = UnackEvent(new_pack, this->getId(), this->getId(), time_now + RTO);
    eventHeap.push(unack_event);

    unacknowledged_packets.insert(new_pack.uuid);
    unack_packets++;
}

void Host::giveEvent(std::unique_ptr<FlowEvent> flow_event)
{
    // Create queue of packets for host to make events out of
    addFlow(flow_event->destination, flow_event->data_size);

    // Create PacketEvents based on queue of packets based on
    // number of unacknowledged packets
    int num_events = window_size - unack_packets;
    float time_now = flow_event->eventTime();
    // push PacketEvents onto eventheap
    for (int pck = 1; pck <= num_events; pck++) {
        Packet new_pack = packet_queue.pop();
        time_now +=  float(new_pack.size) / throughput;
        sendPacket(new_pack, time_now);
    }
}

void Host::giveEvent(std::unique_ptr<UnackEvent> unack_event)
{
    Packet new_pack = unack_event->packet;

    // Check if packet has been acknowledged, if not resend
    if (unacknowledged_packets.count(new_pack.uuid) != 0)
        sendPacket(new_pack, unack_event->eventTime());
}

void Host::giveEvent(std::unique_ptr<PacketEvent> new_event)
{
    Packet pkt = new_event->packet;

    if (pkt.ack)
    {
        unack_packets--;
        unacknowledged_packets.erase(pkt.uuid);

        Packet new_packet = new_event->packet;
        std::string source = new_event->source;
        float now = new_event->eventTime();
        int test;
    }
}

<commit_msg>test2<commit_after>#include "Host.h"
#include <math.h> // ceil

static const int INITIAL_WINDOW_SIZE = 0; // TODO: change this number
static const int DATA_PKT_SIZE = 1; // TODO: change this number

Host::Host(CongestionAlg congestion_algorithm , Link& host_link, float rt) : my_link(host_link)
{
    window_size = INITIAL_WINDOW_SIZE;
    congestion_alg = congestion_algorithm;
    my_link = host_link;
    packet_id = 0;
    unack_packets = 0;
    RTO = rt;
}

void Host::addFlow(std::string dest, float data_size)
{
    float temp_num_pkts = data_size / DATA_PKT_SIZE;
    int num_packets = (int) ceil(temp_num_pkts);

    std::queue<Packet> flow;

    for (int count = 0; count < num_packets; count++){
        std::string pack_id = this->uuid + std::to_string(packet_id);
        Packet new_packet(pack_id, dest, this->uuid, DATA_PKT_SIZE, false, false, count+1);
        flow.push(new_packet);
        packet_id++;
    }

    packet_queue.addQueue(flow);
}

void Host::sendPacket(Packet new_pack, int time_now)
{
    // Insert packet to the eventHeap
    PacketEvent packet_event = PacketEvent(new_pack, new_pack.final_dest, new_pack.source, time_now);
    eventHeap.push(packet_event);

    // Insert to the eventHeap an event which is triggered once a packet has timed out
    UnackEvent unack_event = UnackEvent(new_pack, this->getId(), this->getId(), time_now + RTO);
    eventHeap.push(unack_event);

    unacknowledged_packets.insert(new_pack.uuid);
    unack_packets++;
}

void Host::giveEvent(std::unique_ptr<FlowEvent> flow_event)
{
    // Create queue of packets for host to make events out of
    addFlow(flow_event->destination, flow_event->data_size);

    // Create PacketEvents based on queue of packets based on
    // number of unacknowledged packets
    int num_events = window_size - unack_packets;
    float time_now = flow_event->eventTime();
    // push PacketEvents onto eventheap
    for (int pck = 1; pck <= num_events; pck++) {
        Packet new_pack = packet_queue.pop();
        time_now +=  float(new_pack.size) / throughput;
        sendPacket(new_pack, time_now);
    }
}

void Host::giveEvent(std::unique_ptr<UnackEvent> unack_event)
{
    Packet new_pack = unack_event->packet;

    // Check if packet has been acknowledged, if not resend
    if (unacknowledged_packets.count(new_pack.uuid) != 0)
        sendPacket(new_pack, unack_event->eventTime());
}

void Host::giveEvent(std::unique_ptr<PacketEvent> new_event)
{
    Packet pkt = new_event->packet;

    if (pkt.ack)
    {
        unack_packets--;
        unacknowledged_packets.erase(pkt.uuid);

        Packet new_packet = new_event->packet;
        std::string source = new_event->source;
        float now = new_event->eventTime();
        int test;
    }
}

<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** 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 ETH Zurich 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 HOLDER 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.
 **
 **********************************************************************************************************************/
#include "OverlayGroup.h"

#include "OverlayAccessor.h"
#include "../items/Item.h"
#include "../Scene.h"

namespace Visualization {

OverlayGroup::~OverlayGroup()
{
	for (auto & overlay : overlays_) SAFE_DELETE(overlay);
}

OverlayGroup::OverlayGroup(Scene* scene, QString name) : scene_{scene}, name_{name}
{
	Q_ASSERT(scene);
	Q_ASSERT(!name.isEmpty());
}

void OverlayGroup::hide()
{
	hidden_ = true;
	for (auto& o : overlays_) o->overlayItem()->hide();
}

void OverlayGroup::show()
{
	hidden_ = false;
	for (auto& o : overlays_) o->overlayItem()->show();
}

void OverlayGroup::addOverlay(OverlayAccessor* overlay)
{
	overlays_.append(overlay);
	overlay->overlayItem()->setUpdateNeeded(Item::StandardUpdate);
	if (hidden_) overlay->overlayItem()->hide();

	scene_->addItem(overlay->overlayItem());
	scene_->scheduleUpdate();
}

bool OverlayGroup::removeOverlay(OverlayAccessor* overlay)
{
	return removeOverlay(std::find(overlays_.begin(), overlays_.end(), overlay));
}

bool OverlayGroup::removeOverlay(Item* overlay)
{
	return removeOverlay( std::find_if(overlays_.begin(), overlays_.end(),
			[=](OverlayAccessor* o){return o->overlayItem() == overlay;}));
}

bool OverlayGroup::removeOverlayOf(Item* itemWithOverlay)
{
	return removeOverlay( std::find_if(overlays_.begin(), overlays_.end(),
			[=](OverlayAccessor* o){return o->associatedItems().contains(itemWithOverlay);}));
}

bool OverlayGroup::removeOverlay(QList<OverlayAccessor*>::iterator it)
{
	if (it != overlays_.end())
	{
		SAFE_DELETE(*it);
		overlays_.erase(it);
		scene_->scheduleUpdate();
		return true;
	}
	else return false;
}

void OverlayGroup::clear()
{
	for (auto& overlay : overlays_) SAFE_DELETE(overlay);
	overlays_.clear();
}

void OverlayGroup::setDynamic1Item(ItemGetter1Item getter)
{
	itemGetterFunction1_ = getter;
}

void OverlayGroup::setDynamic2Items(ItemGetter2Items getter)
{
	itemGetterFunction2_ = getter;
}

void OverlayGroup::setOverlayConstructor1Arg(OverlayConstructor1Arg constructor)
{
	constructorFunction1_ = constructor;
}

void OverlayGroup::setOverlayConstructor2Args(OverlayConstructor2Args constructor)
{
	constructorFunction2_ = constructor;
}

void OverlayGroup::setPostUpdateFunction(PostUpdateFunction function)
{
	postUpdateFunction_ = function;
}

void OverlayGroup::addOverlayFor(Item* item)
{
	addOverlay(constructorFunction1_(item));
}

void OverlayGroup::addOverlayFor(Item* item1, Item* item2)
{
	addOverlay(constructorFunction2_(item1, item2));
}

QList<OverlayAccessor*> OverlayGroup::overlaysForItem(const Item* item) const
{
	Q_ASSERT(item);
	QList<OverlayAccessor*> result;
	for (auto accessor: overlays_)
		if (accessor->associatedItems().contains(const_cast<Item* const>(item))) // TODO: is this really the best way?
			result << accessor;
	return result;
}

void OverlayGroup::update()
{
	if (!hidden_)
	{
		if (itemGetterFunction1_)
		{
			Q_ASSERT(constructorFunction1_);
			Item::synchronizeCollections(nullptr, itemGetterFunction1_(), overlays_,
					[](Item* itemToOverlay, OverlayAccessor* overlay)
					{
						return itemToOverlay == overlay->associatedItems().first();
					},
					[this](Item*, Item* itemToOverlay)
					{
						auto overlay = constructorFunction1_(itemToOverlay);
						Q_ASSERT(overlay);
						scene_->addItem(overlay->overlayItem());
						return overlay;
					},
					[](Item*, Item*, OverlayAccessor*) {return false;}
					);
		}

		if (itemGetterFunction2_)
		{
			Q_ASSERT(constructorFunction2_);
			Item::synchronizeCollections(nullptr, itemGetterFunction2_(), overlays_,
					[](const QPair<Item*, Item*>& pair, OverlayAccessor* overlay)
					{
						return overlay->associatedItems().size() == 2
								&& pair.first == overlay->associatedItems().first()
								&& pair.second == overlay->associatedItems().at(1);
					},
					[this](Item*, const QPair<Item*, Item*>& pair)
					{
						auto overlay = constructorFunction2_(pair.first, pair.second);
						Q_ASSERT(overlay);
						scene_->addItem(overlay->overlayItem());
						return overlay;
					},
					[](Item*, const QPair<Item*, Item*>&, OverlayAccessor*){return false;}
					);
		}

		for (auto& overlay : overlays_)
		{
			overlay->overlayItem()->setUpdateNeeded(Item::StandardUpdate);
			overlay->overlayItem()->updateSubtree();
		}

		if (postUpdateFunction_) postUpdateFunction_(*this);
	}
}

} /* namespace Visualization */
<commit_msg>Fix overlays remaining on screen after switching views<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** 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 ETH Zurich 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 HOLDER 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.
 **
 **********************************************************************************************************************/
#include "OverlayGroup.h"

#include "OverlayAccessor.h"
#include "../items/Item.h"
#include "../Scene.h"

namespace Visualization {

OverlayGroup::~OverlayGroup()
{
	for (auto & overlay : overlays_) SAFE_DELETE(overlay);
}

OverlayGroup::OverlayGroup(Scene* scene, QString name) : scene_{scene}, name_{name}
{
	Q_ASSERT(scene);
	Q_ASSERT(!name.isEmpty());
}

void OverlayGroup::hide()
{
	hidden_ = true;
	for (auto& o : overlays_) o->overlayItem()->hide();
}

void OverlayGroup::show()
{
	hidden_ = false;
	for (auto& o : overlays_) o->overlayItem()->show();
}

void OverlayGroup::addOverlay(OverlayAccessor* overlay)
{
	overlays_.append(overlay);
	overlay->overlayItem()->setUpdateNeeded(Item::StandardUpdate);
	if (hidden_) overlay->overlayItem()->hide();

	scene_->addItem(overlay->overlayItem());
	scene_->scheduleUpdate();
}

bool OverlayGroup::removeOverlay(OverlayAccessor* overlay)
{
	return removeOverlay(std::find(overlays_.begin(), overlays_.end(), overlay));
}

bool OverlayGroup::removeOverlay(Item* overlay)
{
	return removeOverlay( std::find_if(overlays_.begin(), overlays_.end(),
			[=](OverlayAccessor* o){return o->overlayItem() == overlay;}));
}

bool OverlayGroup::removeOverlayOf(Item* itemWithOverlay)
{
	return removeOverlay( std::find_if(overlays_.begin(), overlays_.end(),
			[=](OverlayAccessor* o){return o->associatedItems().contains(itemWithOverlay);}));
}

bool OverlayGroup::removeOverlay(QList<OverlayAccessor*>::iterator it)
{
	if (it != overlays_.end())
	{
		SAFE_DELETE(*it);
		overlays_.erase(it);
		scene_->scheduleUpdate();
		return true;
	}
	else return false;
}

void OverlayGroup::clear()
{
	for (auto& overlay : overlays_) SAFE_DELETE(overlay);
	overlays_.clear();
}

void OverlayGroup::setDynamic1Item(ItemGetter1Item getter)
{
	itemGetterFunction1_ = getter;
}

void OverlayGroup::setDynamic2Items(ItemGetter2Items getter)
{
	itemGetterFunction2_ = getter;
}

void OverlayGroup::setOverlayConstructor1Arg(OverlayConstructor1Arg constructor)
{
	constructorFunction1_ = constructor;
}

void OverlayGroup::setOverlayConstructor2Args(OverlayConstructor2Args constructor)
{
	constructorFunction2_ = constructor;
}

void OverlayGroup::setPostUpdateFunction(PostUpdateFunction function)
{
	postUpdateFunction_ = function;
}

void OverlayGroup::addOverlayFor(Item* item)
{
	addOverlay(constructorFunction1_(item));
}

void OverlayGroup::addOverlayFor(Item* item1, Item* item2)
{
	addOverlay(constructorFunction2_(item1, item2));
}

QList<OverlayAccessor*> OverlayGroup::overlaysForItem(const Item* item) const
{
	Q_ASSERT(item);
	QList<OverlayAccessor*> result;
	for (auto accessor: overlays_)
		if (accessor->associatedItems().contains(const_cast<Item* const>(item))) // TODO: is this really the best way?
			result << accessor;
	return result;
}

void OverlayGroup::update()
{
	if (!hidden_)
	{
		if (itemGetterFunction1_)
		{
			Q_ASSERT(constructorFunction1_);
			Item::synchronizeCollections(nullptr, itemGetterFunction1_(), overlays_,
					[](Item* itemToOverlay, OverlayAccessor* overlay)
					{
						return itemToOverlay == overlay->associatedItems().first();
					},
					[this](Item*, Item* itemToOverlay)
					{
						auto overlay = constructorFunction1_(itemToOverlay);
						Q_ASSERT(overlay);
						scene_->addItem(overlay->overlayItem());
						return overlay;
					},
					[](Item*, Item*, OverlayAccessor*) {return false;}
					);
		}

		if (itemGetterFunction2_)
		{
			Q_ASSERT(constructorFunction2_);
			Item::synchronizeCollections(nullptr, itemGetterFunction2_(), overlays_,
					[](const QPair<Item*, Item*>& pair, OverlayAccessor* overlay)
					{
						return overlay->associatedItems().size() == 2
								&& pair.first == overlay->associatedItems().first()
								&& pair.second == overlay->associatedItems().at(1);
					},
					[this](Item*, const QPair<Item*, Item*>& pair)
					{
						auto overlay = constructorFunction2_(pair.first, pair.second);
						Q_ASSERT(overlay);
						scene_->addItem(overlay->overlayItem());
						return overlay;
					},
					[](Item*, const QPair<Item*, Item*>&, OverlayAccessor*){return false;}
					);
		}

		for (auto& overlay : overlays_)
		{
			// Hide/show overlays depending on whether their associated items are visible (e.g. when changing views)
			bool allVisible = std::all_of(overlay->associatedItems().begin(), overlay->associatedItems().end(),
													[](Item* item) {return item->isVisible();});
			if (allVisible != overlay->overlayItem()->isVisible())
				overlay->overlayItem()->setVisible(allVisible);

			overlay->overlayItem()->setUpdateNeeded(Item::StandardUpdate);
			overlay->overlayItem()->updateSubtree();
		}

		if (postUpdateFunction_) postUpdateFunction_(*this);
	}
}

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


<commit_before>#ifndef PIXELBOOST_DISABLE_GRAPHICS

#include <algorithm>
#include <set>

#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/effect/effect.h"
#include "pixelboost/graphics/effect/manager.h"
#include "pixelboost/graphics/renderer/common/irenderer.h"
#include "pixelboost/graphics/renderer/common/renderable.h"
#include "pixelboost/graphics/renderer/common/renderer.h"

using namespace pb;

Renderer* Renderer::Renderer::_Instance = 0;

Renderer::Renderer()
{
    _Instance = this;

    _EffectManager = new EffectManager();
}

Renderer::~Renderer()
{
    _Instance = 0;
}

Renderer* Renderer::Instance()
{
    return _Instance;
}

void Renderer::Render()
{
    for (ViewportList::iterator it = _Viewports.begin(); it != _Viewports.end(); ++it)
    {
        (*it)->Render();

        FlushBuffer(*it);
    }
}

EffectManager* Renderer::GetEffectManager()
{
    return _EffectManager;
}

void Renderer::AddItem(Renderable* renderable)
{
    _Renderables[renderable->GetLayer()].push_back(renderable);
}

void Renderer::AddViewport(Viewport* viewport)
{
    _Viewports.push_back(viewport);
}

void Renderer::RemoveViewport(Viewport* viewport)
{
    for (ViewportList::iterator it = _Viewports.begin(); it != _Viewports.end(); ++it)
    {
        if (*it == viewport)
        {
            _Viewports.erase(it);
            return;
        }
    }
}

void Renderer::SetHandler(int renderableType, IRenderer* renderer)
{
    _RenderableHandlers[renderableType] = renderer;
}

void Renderer::FlushBuffer(Viewport* viewport)
{
    for (int i=0; i<8; i++)
    {
        RenderableList& renderables = _Renderables[i];

        if (!renderables.size())
            continue;

        Uid type = renderables[0]->GetRenderableType();
        Effect* effect = renderables[0]->GetEffect();
        int start = 0;
        int count = 0;

        for (int i=0; i < renderables.size(); i++)
        {
            Uid newType = renderables[i]->GetRenderableType();
            Effect* newEffect = renderables[i]->GetEffect();

            if (type == newType && effect == newEffect)
            {
                count++;
            } else {
                RenderBatch(viewport, count, &renderables[start], effect);
                start = i;
                count = 1;
                type = newType;
                effect = newEffect;
            }
        }

        if (count > 0)
        {
            RenderBatch(viewport, count, &renderables[start], effect);
        }
    }

    _Renderables.clear();
}

void Renderer::RenderBatch(Viewport* viewport, int count, Renderable** renderable, Effect* effect)
{
    if (!effect)
        return;

    RenderableHandlerMap::iterator it = _RenderableHandlers.find(renderable[0]->GetRenderableType());

    if (it != _RenderableHandlers.end())
    {
        EffectTechnique* technique = effect->GetTechnique(viewport->GetRenderScheme());

        if (!technique)
        {
            for (int i=0; i < count; i++)
            {
                technique = viewport->GetTechnique(renderable[i], effect);

                if (technique)
                {
                    for (int j=0; j<technique->GetNumPasses(); j++)
                    {
                        EffectPass* pass = technique->GetPass(j);
                        pass->Bind();
                        it->second->Render(1, &renderable[i], viewport, pass);
                    }
                }
            }
        } else
        {
            for (int i=0; i<technique->GetNumPasses(); i++)
            {
                EffectPass* pass = technique->GetPass(i);
                pass->Bind();
                it->second->Render(count, renderable, viewport, pass);
            }
        }
    }
}

#endif
<commit_msg>Support up to 16 layers<commit_after>#ifndef PIXELBOOST_DISABLE_GRAPHICS

#include <algorithm>
#include <set>

#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/effect/effect.h"
#include "pixelboost/graphics/effect/manager.h"
#include "pixelboost/graphics/renderer/common/irenderer.h"
#include "pixelboost/graphics/renderer/common/renderable.h"
#include "pixelboost/graphics/renderer/common/renderer.h"

using namespace pb;

Renderer* Renderer::Renderer::_Instance = 0;

Renderer::Renderer()
{
    _Instance = this;

    _EffectManager = new EffectManager();
}

Renderer::~Renderer()
{
    _Instance = 0;
}

Renderer* Renderer::Instance()
{
    return _Instance;
}

void Renderer::Render()
{
    for (ViewportList::iterator it = _Viewports.begin(); it != _Viewports.end(); ++it)
    {
        (*it)->Render();

        FlushBuffer(*it);
    }
}

EffectManager* Renderer::GetEffectManager()
{
    return _EffectManager;
}

void Renderer::AddItem(Renderable* renderable)
{
    _Renderables[renderable->GetLayer()].push_back(renderable);
}

void Renderer::AddViewport(Viewport* viewport)
{
    _Viewports.push_back(viewport);
}

void Renderer::RemoveViewport(Viewport* viewport)
{
    for (ViewportList::iterator it = _Viewports.begin(); it != _Viewports.end(); ++it)
    {
        if (*it == viewport)
        {
            _Viewports.erase(it);
            return;
        }
    }
}

void Renderer::SetHandler(int renderableType, IRenderer* renderer)
{
    _RenderableHandlers[renderableType] = renderer;
}

void Renderer::FlushBuffer(Viewport* viewport)
{
    for (int i=0; i<16; i++)
    {
        RenderableList& renderables = _Renderables[i];

        if (!renderables.size())
            continue;

        Uid type = renderables[0]->GetRenderableType();
        Effect* effect = renderables[0]->GetEffect();
        int start = 0;
        int count = 0;

        for (int i=0; i < renderables.size(); i++)
        {
            Uid newType = renderables[i]->GetRenderableType();
            Effect* newEffect = renderables[i]->GetEffect();

            if (type == newType && effect == newEffect)
            {
                count++;
            } else {
                RenderBatch(viewport, count, &renderables[start], effect);
                start = i;
                count = 1;
                type = newType;
                effect = newEffect;
            }
        }

        if (count > 0)
        {
            RenderBatch(viewport, count, &renderables[start], effect);
        }
    }

    _Renderables.clear();
}

void Renderer::RenderBatch(Viewport* viewport, int count, Renderable** renderable, Effect* effect)
{
    if (!effect)
        return;

    RenderableHandlerMap::iterator it = _RenderableHandlers.find(renderable[0]->GetRenderableType());

    if (it != _RenderableHandlers.end())
    {
        EffectTechnique* technique = effect->GetTechnique(viewport->GetRenderScheme());

        if (!technique)
        {
            for (int i=0; i < count; i++)
            {
                technique = viewport->GetTechnique(renderable[i], effect);

                if (technique)
                {
                    for (int j=0; j<technique->GetNumPasses(); j++)
                    {
                        EffectPass* pass = technique->GetPass(j);
                        pass->Bind();
                        it->second->Render(1, &renderable[i], viewport, pass);
                    }
                }
            }
        } else
        {
            for (int i=0; i<technique->GetNumPasses(); i++)
            {
                EffectPass* pass = technique->GetPass(i);
                pass->Bind();
                it->second->Render(count, renderable, viewport, pass);
            }
        }
    }
}

#endif
<|endoftext|>


<commit_before>void AnaJets(Int_t evNumber1=0, Int_t evNumber2=0)
{
//*-- Author: Andreas Morsch (CERN)

    if (gClassTable->GetID("AliRun") < 0) {
	gROOT->LoadMacro("../macros/loadlibs.C");
	loadlibs();
    }
// Connect the Root Galice file containing Geometry, Kine and Hits

    TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root");

    if (!file) {
	printf("\n Creating galice.root \n");
	file = new TFile("galice.root");
    } else {
	printf("\n galice.root found in file list");
    }
// Get AliRun object from file or create it if not on file
    if (!gAlice) {
	gAlice = (AliRun*)(file->Get("gAlice"));
	if (gAlice) printf("AliRun object found on file\n");
	if (!gAlice) {
	    printf("\n create new gAlice object");
	    gAlice = new AliRun("gAlice","Alice test program");
	}
    }
// Book histos
    TH1F *eH   = new TH1F("eH","Energy", 150,  0.0, 150.);
    TH1F *etaH = new TH1F("eEta","Eta",  180, -0.9, 0.9);
    TH1F *phiH = new TH1F("ePhi","Phi",   62, -3.1, 3.1);

    TClonesArray* jets = new TClonesArray("AliEMCALJet",10000);

    for (int nev=0; nev<= evNumber2; nev++) {
	printf("\n Event .............%d", nev);
	Int_t nparticles = gAlice->GetEvent(nev);
	Int_t nbytes     = 0;
	AliEMCAL *pEMCAL  = (AliEMCAL*) gAlice->GetModule("EMCAL");
	if (pEMCAL) {
	    TTree *TR = gAlice->TreeR();
	    Int_t nent=TR->GetEntries();
	    TR->SetBranchAddress("Jets", &jets);
	    nbytes += TR->GetEntry(0);
	    Int_t nJet = jets->GetEntries();
	    printf("\n Number of Jets %d", nJet);
	    AliEMCALJet  *mJet;
	    for (Int_t ij=0; ij < nJet; ij++) {
		mJet = (AliEMCALJet*)jets->UncheckedAt(ij);
		printf("\n Jet:%d E %f phi %f eta %f\n", ij,
		       mJet->Energy(), mJet->Phi(), mJet->Eta());
		etaH->Fill(mJet->Eta());
		phiH->Fill(mJet->Phi());
		eH  ->Fill(mJet->Energy());
	   } // jet
       } // ?EMCAL
   } // event
    TCanvas *c1 = new TCanvas("c1","Canvas 1",400,10,600,700);
    c1->Divide(2,2);
    c1->cd(1); eH->Draw();
    c1->cd(2); etaH->Draw();
    c1->cd(3); phiH->Draw();
}
<commit_msg>Analyse track information.<commit_after>void AnaJets(Int_t evNumber1=0, Int_t evNumber2=0)
{
//*-- Author: Andreas Morsch (CERN)

    if (gClassTable->GetID("AliRun") < 0) {
	gROOT->LoadMacro("loadlibs.C");
	loadlibs();
    }
// Connect the Root Galice file containing Geometry, Kine and Hits

    TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root");

    if (!file) {
	printf("\n Creating galice.root \n");
	file = new TFile("galice.root");
    } else {
	printf("\n galice.root found in file list");
    }
// Get AliRun object from file or create it if not on file
    if (!gAlice) {
	gAlice = (AliRun*)(file->Get("gAlice"));
	if (gAlice) printf("AliRun object found on file\n");
	if (!gAlice) {
	    printf("\n create new gAlice object");
	    gAlice = new AliRun("gAlice","Alice test program");
	}
    }
// Book histos
    TH1F *eH   = new TH1F("eH","Energy",    150,  0.0, 150.);
    TH1F *etaH = new TH1F("eEta","Eta",     180, -0.9,  0.9);
    TH1F *phiH = new TH1F("ePhi","Phi",      62, -3.1,  3.1);
    TH1F *tH   = new TH1F("tH","n tracks",   30,  0.5, 29.5);
    TH1F *ptH  = new TH1F("ptH","Track pT", 100., 0., 100.);
    TH1F *drH  = new TH1F("drH","Track dR", 120., 0.,   6.);

    Float_t phiT[50], etaT[50], ptT[50];

    TClonesArray* jets = new TClonesArray("AliEMCALJet",10000);

    for (int nev=0; nev<= evNumber2; nev++) {
	printf("\n Event .............%d", nev);
	Int_t nparticles = gAlice->GetEvent(nev);
	Int_t nbytes     = 0;
	AliEMCAL *pEMCAL  = (AliEMCAL*) gAlice->GetModule("EMCAL");
	if (pEMCAL) {
	    TTree *TR = gAlice->TreeR();
	    Int_t nent=TR->GetEntries();
	    TR->SetBranchAddress("EMCALJets", &jets);
	    nbytes += TR->GetEntry(0);
	    Int_t nJet = jets->GetEntries();
	    printf("\n Number of Jets %d", nJet);
	    AliEMCALJet  *mJet;
	    for (Int_t ij=0; ij < nJet; ij++) {
		mJet = (AliEMCALJet*)jets->UncheckedAt(ij);
		Float_t eta = mJet->Eta();

		printf("\n Jet:%d E %f phi %f eta %f tracks %d\n", ij,
		       mJet->Energy(), mJet->Phi(), eta,
		       mJet->NTracks());
		etaH->Fill(mJet->Eta());
		phiH->Fill(mJet->Phi());
		if (TMath::Abs(eta) < 0.4)
		    eH->Fill(mJet->Energy());
		tH  ->Fill((Float_t)mJet->NTracks());

		mJet->TrackList(ptT, etaT, phiT);
		for (Int_t it = 0; it < mJet->NTracks(); it++)
		{
		    printf("\n Track: %5d pT %8.3f eta %8.3f phi %8.3f",
			   it, ptT[it], etaT[it], phiT[it]);
		    ptH->Fill(ptT[it]);
		    Float_t dPhi = phiT[it]-mJet->Phi();
		    Float_t dEta = etaT[it]-mJet->Eta();
		    Float_t dr = TMath::Sqrt(dPhi*dPhi+dEta*dEta);
		    drH->Fill(dr);
		}
	   } // jet
       } // ?EMCAL
   } // event
    TCanvas *c1 = new TCanvas("c1","Canvas 1",400,10,600,700);
    c1->Divide(2,2);
    c1->cd(1); eH->Draw();
    c1->cd(2); etaH->Draw();
    c1->cd(3); phiH->Draw();
    c1->cd(4); tH->Draw();

    TCanvas *c2 = new TCanvas("c2","Canvas 2",400,10,600,700);
    c2->Divide(2,2);
    c2->cd(1); ptH->Draw();
    c2->cd(2); drH->Draw();
}

<|endoftext|>


<commit_before>#include "Core.hh"
#include "PluginsManager.hh"
//#include "TestEventSystem1.hh"
//#include "TestEventSystem2.hh"
//#include "VulkanRenderer.hh"

int main()
{
	Obake::Core c;
	//System::TestEventSystem1 system1;
	//System::TestEventSystem2 system2;
	//System::VulkanRenderer vulkan;

	//system1.registerCore(&c);
	//system2.registerCore(&c);
	//vulkan.registerCore(&c);
	//system1.initialize();
	//system2.initialize();
	//vulkan.initialize();

	//c.registerSystem(&system1);
	//c.registerSystem(&system2);

	//Obake::SharedLibrary testLib;

	//if (!testLib.open(".\\Plugins\\TestPlugin.dll"))
	//	std::cout << "Failed to open dll" << std::endl;
	//else
	//{
	//	Obake::PluginInfos* infos;

	//	testLib.sym("exports", reinterpret_cast<void**>(&infos));
	//	std::cout << "Plugin Info: "
	//		<< "\n\tAPI Version: " << infos->apiVersion
	//		<< "\n\tFile Name: " << infos->fileName
	//		<< "\n\tClass Name: " << infos->className
	//		<< "\n\tPlugin Name: " << infos->pluginName
	//		<< "\n\tPlugin Version: " << infos->pluginVersion
	//		<< std::endl;
	//}

	Obake::PluginsManager pluginsManager;

	pluginsManager.loadAllAvailablePlugins();
	pluginsManager.displayPluginsInfos();
	const std::vector<Obake::AvailablePlugin*>& availablePlugins = pluginsManager.getAllAvailablePlugins();

	for (Obake::AvailablePlugin* plugin : availablePlugins)
	{
		if (plugin->isLoaded())
		{
			c.registerSystem(plugin->getPlugin());
			plugin->getPlugin()->sayHello();
		}
	}

	// Vulkan tests
	/*
	{
	auto device = vkRender._device;
	auto queue = vkRender._queue;

	// SYNCHRONISATION VAR
	// Waits for the GPU to be ready on the CPU side
	VkFence fence;
	{
	VkFenceCreateInfo fenceCreateInfo =
	{
	// (MANDATORY) sType is the type of the structure
	fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	fenceCreateInfo.pNext = nullptr,
	// A flag that defines the initial state and behavior of the fence. Either signaled or unsignaled.
	fenceCreateInfo.flags = 0
	};
	vkCreateFence(device, &fenceCreateInfo, nullptr, &fence);
	}

	// Tells the GPU when other process in the GPU are completed
	VkSemaphore semaphore;
	{
	VkSemaphoreCreateInfo semaphoreCreateInfo =
	{
	// (MANDATORY) sType is the type of the structure
	semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	semaphoreCreateInfo.pNext = nullptr,
	// Flag reserved for future use
	semaphoreCreateInfo.flags = 0
	};

	vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphore);
	}
	// - - -

	// COMMAND BUFFERS
	VkCommandPool commandPool;
	{
	VkCommandPoolCreateInfo poolCreateInfo =
	{
	// (MANDATORY) sType is the type of the structure
	poolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	poolCreateInfo.pNext = nullptr,
	// A bitmask indicating usage behavior for the pool and command buffers allocated from it
	poolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
	// (NOTE) All command buffers created from this command pool must be submitted on queues from the same queue family.
	poolCreateInfo.queueFamilyIndex = vkRender._graphicsFamilyIndex
	};
	vkCreateCommandPool(device, &poolCreateInfo, nullptr, &commandPool);
	}

	VkCommandBuffer commandBuffer[2];
	{
	VkCommandBufferAllocateInfo commandBufferInfo =
	{
	// (MANDATORY) sType is the type of the structure
	commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	commandBufferInfo.pNext = nullptr,
	// The command pool that will be used to allocate the command buffer(s)
	commandBufferInfo.commandPool = commandPool,
	// Determines whether the command buffers are primary or secondary command buffers. Secondary command buffers are contained in primary command buffers.
	commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
	// The number of command buffers you want to allocate
	commandBufferInfo.commandBufferCount = 2
	};

	vkAllocateCommandBuffers(device, &commandBufferInfo, commandBuffer);
	}
	// - - -

	// RECORDING IN COMMAND BUFFER(S)
	{
	{
	VkCommandBufferBeginInfo beginInfo =
	{
	// (MANDATORY) sType is the type of the structure
	beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	beginInfo.pNext = nullptr,
	// A bitmask indicating usage behavior for the command buffer.
	beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
	// A pointer to a VkCommandBufferInheritanceInfo structure, which is used if commandBuffer is a secondary command buffer.
	beginInfo.pInheritanceInfo = nullptr
	};
	vkBeginCommandBuffer(commandBuffer[0], &beginInfo);

	vkCmdPipelineBarrier(
	commandBuffer[0],
	VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
	VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
	0,
	0, nullptr,
	0, nullptr,
	0, nullptr);

	// Filling the command buffer
	{
	VkViewport viewport =
	{
	viewport.maxDepth = 1.0f,
	viewport.minDepth = 0.0f,
	viewport.width = 512,
	viewport.height = 512,
	viewport.x = 0,
	viewport.y = 0
	};
	vkCmdSetViewport(commandBuffer[0], 0, 1, &viewport);
	}

	vkEndCommandBuffer(commandBuffer[0]);
	}

	{
	VkCommandBufferBeginInfo beginInfo =
	{
	// (MANDATORY) sType is the type of the structure
	beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	beginInfo.pNext = nullptr,
	// A bitmask indicating usage behavior for the command buffer.
	beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
	// A pointer to a VkCommandBufferInheritanceInfo structure, which is used if commandBuffer is a secondary command buffer.
	beginInfo.pInheritanceInfo = nullptr
	};
	vkBeginCommandBuffer(commandBuffer[1], &beginInfo);

	VkViewport viewport{};
	viewport.maxDepth = 1.0f;
	viewport.minDepth = 0.0f;
	viewport.width = 512;
	viewport.height = 512;
	viewport.x = 0;
	viewport.y = 0;
	vkCmdSetViewport(commandBuffer[1], 0, 1, &viewport);

	vkEndCommandBuffer(commandBuffer[1]);
	}

	{
	VkSubmitInfo submitInfo =
	{
	// (MANDATORY) sType is the type of the structure
	submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	submitInfo.pNext = nullptr,
	// The number of semaphores upon which to wait before executing the command buffers for the batch.
	submitInfo.waitSemaphoreCount = 0,
	// A pointer to an array of semaphores upon which to wait before executing the command buffers in the batch
	submitInfo.pWaitSemaphores = nullptr,
	// A pointer to an array of pipeline stages at which each corresponding semaphore wait will occur.
	submitInfo.pWaitDstStageMask = nullptr,
	// Contains the number of command buffers to execute in the batch
	submitInfo.commandBufferCount = 1,
	// A pointer to an array of command buffers to execute in the batch.
	// The command buffers submitted in a batch begin execution in the order they appear in pCommandBuffers, but may complete out of order
	submitInfo.pCommandBuffers = &commandBuffer[0],
	// The number of semaphores to be signaled once the commands specified in pCommandBuffers have completed execution.
	submitInfo.signalSemaphoreCount = 1,
	// A pointer to an array of semaphores which will be signaled when the command buffers for this batch have completed execution.
	submitInfo.pSignalSemaphores = &semaphore
	};

	vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
	}
	{
	VkPipelineStageFlags flags[]{ VK_PIPELINE_STAGE_ALL_COMMANDS_BIT };
	VkSubmitInfo submitInfo =
	{
	// (MANDATORY) sType is the type of the structure
	submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	submitInfo.pNext = nullptr,
	// The number of semaphores upon which to wait before executing the command buffers for the batch.
	submitInfo.waitSemaphoreCount = 1,
	// A pointer to an array of semaphores upon which to wait before executing the command buffers in the batch
	submitInfo.pWaitSemaphores = &semaphore,
	// A pointer to an array of pipeline stages at which each corresponding semaphore wait will occur.
	submitInfo.pWaitDstStageMask = flags,
	// Contains the number of command buffers to execute in the batch
	submitInfo.commandBufferCount = 1,
	// A pointer to an array of command buffers to execute in the batch.
	// The command buffers submitted in a batch begin execution in the order they appear in pCommandBuffers, but may complete out of order
	submitInfo.pCommandBuffers = &commandBuffer[1],
	// The number of semaphores to be signaled once the commands specified in pCommandBuffers have completed execution.
	submitInfo.signalSemaphoreCount = 1,
	// A pointer to an array of semaphores which will be signaled when the command buffers for this batch have completed execution.
	submitInfo.pSignalSemaphores = &semaphore
	};

	vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
	}
	}

	// Synchronisation
	{
	//			vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX);
	vkQueueWaitIdle(queue);
	}

	// Freeing up things that have been allocated
	{
	vkDestroyCommandPool(device, commandPool, nullptr);
	vkDestroyFence(device, fence, nullptr);
	vkDestroySemaphore(device, semaphore, nullptr);
	}
	}
	*/

	//int runRet = c.run();
	system("Pause");
	//return runRet;
	return 0;
}
<commit_msg>[ADD] window & vulkan link. Need to fix core error<commit_after>#include "Core.hh"
#include "PluginsManager.hh"
//#include "TestEventSystem1.hh"
//#include "TestEventSystem2.hh"
//#include "VulkanRenderer.hh"

int main()
{
	Obake::Core core;
	//System::TestEventSystem1 system1;
	//System::TestEventSystem2 system2;
	//System::VulkanRenderer vulkan;

	//system1.registerCore(&c);
	//system2.registerCore(&c);
	//vulkan.registerCore(&c);
	//system1.initialize();
	//system2.initialize();
	//vulkan.initialize();

	Obake::PluginsManager pluginsManager;

	pluginsManager.loadAllAvailablePlugins();
	pluginsManager.displayPluginsInfos();
	const std::vector<Obake::AvailablePlugin*>& availablePlugins = pluginsManager.getAllAvailablePlugins();

	for (Obake::AvailablePlugin* plugin : availablePlugins)
	{
		if (plugin->isLoaded())
		{
			plugin->getPlugin()->registerCore(&core);
			plugin->getPlugin()->initialize();
			core.registerSystem(reinterpret_cast<Obake::ASystem*>(plugin->getPlugin()));
		}
	}

	// Vulkan tests
	/*
	{
	auto device = vkRender._device;
	auto queue = vkRender._queue;

	// SYNCHRONISATION VAR
	// Waits for the GPU to be ready on the CPU side
	VkFence fence;
	{
	VkFenceCreateInfo fenceCreateInfo =
	{
	// (MANDATORY) sType is the type of the structure
	fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	fenceCreateInfo.pNext = nullptr,
	// A flag that defines the initial state and behavior of the fence. Either signaled or unsignaled.
	fenceCreateInfo.flags = 0
	};
	vkCreateFence(device, &fenceCreateInfo, nullptr, &fence);
	}

	// Tells the GPU when other process in the GPU are completed
	VkSemaphore semaphore;
	{
	VkSemaphoreCreateInfo semaphoreCreateInfo =
	{
	// (MANDATORY) sType is the type of the structure
	semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	semaphoreCreateInfo.pNext = nullptr,
	// Flag reserved for future use
	semaphoreCreateInfo.flags = 0
	};

	vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphore);
	}
	// - - -

	// COMMAND BUFFERS
	VkCommandPool commandPool;
	{
	VkCommandPoolCreateInfo poolCreateInfo =
	{
	// (MANDATORY) sType is the type of the structure
	poolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	poolCreateInfo.pNext = nullptr,
	// A bitmask indicating usage behavior for the pool and command buffers allocated from it
	poolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
	// (NOTE) All command buffers created from this command pool must be submitted on queues from the same queue family.
	poolCreateInfo.queueFamilyIndex = vkRender._graphicsFamilyIndex
	};
	vkCreateCommandPool(device, &poolCreateInfo, nullptr, &commandPool);
	}

	VkCommandBuffer commandBuffer[2];
	{
	VkCommandBufferAllocateInfo commandBufferInfo =
	{
	// (MANDATORY) sType is the type of the structure
	commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	commandBufferInfo.pNext = nullptr,
	// The command pool that will be used to allocate the command buffer(s)
	commandBufferInfo.commandPool = commandPool,
	// Determines whether the command buffers are primary or secondary command buffers. Secondary command buffers are contained in primary command buffers.
	commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
	// The number of command buffers you want to allocate
	commandBufferInfo.commandBufferCount = 2
	};

	vkAllocateCommandBuffers(device, &commandBufferInfo, commandBuffer);
	}
	// - - -

	// RECORDING IN COMMAND BUFFER(S)
	{
	{
	VkCommandBufferBeginInfo beginInfo =
	{
	// (MANDATORY) sType is the type of the structure
	beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	beginInfo.pNext = nullptr,
	// A bitmask indicating usage behavior for the command buffer.
	beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
	// A pointer to a VkCommandBufferInheritanceInfo structure, which is used if commandBuffer is a secondary command buffer.
	beginInfo.pInheritanceInfo = nullptr
	};
	vkBeginCommandBuffer(commandBuffer[0], &beginInfo);

	vkCmdPipelineBarrier(
	commandBuffer[0],
	VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
	VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
	0,
	0, nullptr,
	0, nullptr,
	0, nullptr);

	// Filling the command buffer
	{
	VkViewport viewport =
	{
	viewport.maxDepth = 1.0f,
	viewport.minDepth = 0.0f,
	viewport.width = 512,
	viewport.height = 512,
	viewport.x = 0,
	viewport.y = 0
	};
	vkCmdSetViewport(commandBuffer[0], 0, 1, &viewport);
	}

	vkEndCommandBuffer(commandBuffer[0]);
	}

	{
	VkCommandBufferBeginInfo beginInfo =
	{
	// (MANDATORY) sType is the type of the structure
	beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	beginInfo.pNext = nullptr,
	// A bitmask indicating usage behavior for the command buffer.
	beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
	// A pointer to a VkCommandBufferInheritanceInfo structure, which is used if commandBuffer is a secondary command buffer.
	beginInfo.pInheritanceInfo = nullptr
	};
	vkBeginCommandBuffer(commandBuffer[1], &beginInfo);

	VkViewport viewport{};
	viewport.maxDepth = 1.0f;
	viewport.minDepth = 0.0f;
	viewport.width = 512;
	viewport.height = 512;
	viewport.x = 0;
	viewport.y = 0;
	vkCmdSetViewport(commandBuffer[1], 0, 1, &viewport);

	vkEndCommandBuffer(commandBuffer[1]);
	}

	{
	VkSubmitInfo submitInfo =
	{
	// (MANDATORY) sType is the type of the structure
	submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	submitInfo.pNext = nullptr,
	// The number of semaphores upon which to wait before executing the command buffers for the batch.
	submitInfo.waitSemaphoreCount = 0,
	// A pointer to an array of semaphores upon which to wait before executing the command buffers in the batch
	submitInfo.pWaitSemaphores = nullptr,
	// A pointer to an array of pipeline stages at which each corresponding semaphore wait will occur.
	submitInfo.pWaitDstStageMask = nullptr,
	// Contains the number of command buffers to execute in the batch
	submitInfo.commandBufferCount = 1,
	// A pointer to an array of command buffers to execute in the batch.
	// The command buffers submitted in a batch begin execution in the order they appear in pCommandBuffers, but may complete out of order
	submitInfo.pCommandBuffers = &commandBuffer[0],
	// The number of semaphores to be signaled once the commands specified in pCommandBuffers have completed execution.
	submitInfo.signalSemaphoreCount = 1,
	// A pointer to an array of semaphores which will be signaled when the command buffers for this batch have completed execution.
	submitInfo.pSignalSemaphores = &semaphore
	};

	vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
	}
	{
	VkPipelineStageFlags flags[]{ VK_PIPELINE_STAGE_ALL_COMMANDS_BIT };
	VkSubmitInfo submitInfo =
	{
	// (MANDATORY) sType is the type of the structure
	submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
	// (MANDATORY) pNext is NULL or a pointer to an extension-specific structure.
	submitInfo.pNext = nullptr,
	// The number of semaphores upon which to wait before executing the command buffers for the batch.
	submitInfo.waitSemaphoreCount = 1,
	// A pointer to an array of semaphores upon which to wait before executing the command buffers in the batch
	submitInfo.pWaitSemaphores = &semaphore,
	// A pointer to an array of pipeline stages at which each corresponding semaphore wait will occur.
	submitInfo.pWaitDstStageMask = flags,
	// Contains the number of command buffers to execute in the batch
	submitInfo.commandBufferCount = 1,
	// A pointer to an array of command buffers to execute in the batch.
	// The command buffers submitted in a batch begin execution in the order they appear in pCommandBuffers, but may complete out of order
	submitInfo.pCommandBuffers = &commandBuffer[1],
	// The number of semaphores to be signaled once the commands specified in pCommandBuffers have completed execution.
	submitInfo.signalSemaphoreCount = 1,
	// A pointer to an array of semaphores which will be signaled when the command buffers for this batch have completed execution.
	submitInfo.pSignalSemaphores = &semaphore
	};

	vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
	}
	}

	// Synchronisation
	{
	//			vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX);
	vkQueueWaitIdle(queue);
	}

	// Freeing up things that have been allocated
	{
	vkDestroyCommandPool(device, commandPool, nullptr);
	vkDestroyFence(device, fence, nullptr);
	vkDestroySemaphore(device, semaphore, nullptr);
	}
	}
	*/

	//int runRet = core.run();
	system("Pause");
	//return runRet;

	for (Obake::AvailablePlugin* plugin : availablePlugins)
	{
		if (plugin->isLoaded())
		{
			plugin->getPlugin()->unload();
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9a_omi_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9a_omi_scom.C
///
// *HWP HWP Owner: Benjamin Gass <bgass@us.ibm.com>
// *HWP HWP Backup: Daniel Crowell <dcrowell@us.ibm.com>
// *HWP Team:
// *HWP Level: 2
// *HWP Consumed by: HB
<commit_msg>Adding omi_init procedures.<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9a_omi_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9a_omi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_2 = 2;
constexpr uint64_t literal_0b1 = 0b1;
constexpr uint64_t literal_1 = 1;

fapi2::ReturnCode p9a_omi_scom(const fapi2::Target<fapi2::TARGET_TYPE_MI>& TGT0,
                               const fapi2::Target<fapi2::TARGET_TYPE_OMI>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_MCC>& TGT2,
                               const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT3)
{
    {
        fapi2::ATTR_CHIP_UNIT_POS_Type l_TGT1_ATTR_CHIP_UNIT_POS;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, TGT1, l_TGT1_ATTR_CHIP_UNIT_POS));
        uint64_t l_def_OMI_POSITION = (l_TGT1_ATTR_CHIP_UNIT_POS % literal_2);
        fapi2::ATTR_CHIP_UNIT_POS_Type l_TGT2_ATTR_CHIP_UNIT_POS;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, TGT2, l_TGT2_ATTR_CHIP_UNIT_POS));
        uint64_t l_def_MCC_POSITION = (l_TGT2_ATTR_CHIP_UNIT_POS % literal_2);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if (((l_def_MCC_POSITION == literal_0) && (l_def_OMI_POSITION == literal_0)))
            {
                l_scom_buffer.insert<53, 1, 63, uint64_t>(literal_0b1 );
            }

            if (((l_def_MCC_POSITION == literal_0) && (l_def_OMI_POSITION == literal_1)))
            {
                l_scom_buffer.insert<54, 1, 63, uint64_t>(literal_0b1 );
            }

            if (((l_def_MCC_POSITION == literal_1) && (l_def_OMI_POSITION == literal_0)))
            {
                l_scom_buffer.insert<55, 1, 63, uint64_t>(literal_0b1 );
            }

            if (((l_def_MCC_POSITION == literal_1) && (l_def_OMI_POSITION == literal_1)))
            {
                l_scom_buffer.insert<56, 1, 63, uint64_t>(literal_0b1 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>#include "FrameBuffer.h"

#include <string>

FrameBuffer::FrameBuffer(void)
{
	handle			= 0;

	memset(colourTex, 0, sizeof(colourTex));

	numTargets		= 0;

	depthTex		= 0;

	width = height	= 0;

	maxSize			= 4096;
}

FrameBuffer::~FrameBuffer(void)
{
	//Release everything from graphics memory
	Release();
}

void FrameBuffer::Release(void)
{
	//Can only release data if there is a handle to get the data
	if(handle)
	{
		//Delete the FBO
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glDeleteFramebuffers(1, &handle);

		//Delete the textures
		glBindTexture(GL_TEXTURE_2D, 0);
		if(*colourTex)
		{
			glDeleteTextures(1, colourTex);
		}

		//Reset the values
		handle			= 0;
		memset(colourTex, 0, sizeof(colourTex));
		numTargets		= 0;
		depthTex		= 0;
		width = height	= 0;
	}
}

int FrameBuffer::Initialize(unsigned int w, unsigned int h,
							unsigned int colour, bool useDepth, bool useHDR,
							bool useLinearFilter, bool clamp)
{
	if(w && h && (colour || useDepth))
	{
		//Maximum dimension
		if(w <= maxSize && h <= maxSize)
		{
			const unsigned short filtering = useLinearFilter ?
				GL_LINEAR : GL_NEAREST;
			const unsigned short wrapping = clamp ?
				GL_CLAMP_TO_EDGE : GL_REPEAT;
			const unsigned short colourBit = useHDR ?
				GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
			const unsigned short colourFormat = useHDR ?
				GL_RGBA16 : GL_RGBA8;

			this->width		= w;
			this->height	= h;

			//init FBO
			glGenFramebuffers(1, &handle);
			glBindFramebuffer(GL_FRAMEBUFFER, handle);

			if(colour)
			{
				int maxTargets;
				glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxTargets);
				numTargets = (int)colour <= maxTargets ? colour : maxTargets;

				glGenTextures(1, colourTex);

				for(unsigned int i = 0; i < numTargets ; ++i)
				{
					glGenTextures(1, colourTex + i);
					glBindTexture(GL_TEXTURE_2D, *colourTex);
					glTexImage2D(GL_TEXTURE_2D, 0, colourFormat, width, height, 0, GL_RGBA, colourBit, 0);

					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);

					glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, *(colourTex + i), 0);
				}
			}

			if(useDepth)
			{
				glGenTextures(1, &depthTex);
				glBindTexture(GL_TEXTURE_2D, depthTex);
				glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);

				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);

				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTex, 0);
			}

			int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

			if(status == GL_FRAMEBUFFER_COMPLETE)
			{
				glBindTexture(GL_TEXTURE_2D, 0);
				glBindFramebuffer(GL_FRAMEBUFFER, 0);

				return 1;
			}

			Release();
		}
	}

	return 0;
}

void FrameBuffer::Activate() const
{
	//If the FBO has been created and has a handle
	if(handle)
	{
		//Bind the FBO
		glBindFramebuffer(GL_FRAMEBUFFER, handle);

		if(numTargets)
		{
			const GLenum targetName[16] = {
				GL_COLOR_ATTACHMENT0,
				GL_COLOR_ATTACHMENT1,
				GL_COLOR_ATTACHMENT2,
				GL_COLOR_ATTACHMENT3,
				GL_COLOR_ATTACHMENT4,
				GL_COLOR_ATTACHMENT5,
				GL_COLOR_ATTACHMENT6,
				GL_COLOR_ATTACHMENT7,
				GL_COLOR_ATTACHMENT8,
				GL_COLOR_ATTACHMENT9,
				GL_COLOR_ATTACHMENT10,
				GL_COLOR_ATTACHMENT11,
				GL_COLOR_ATTACHMENT12,
				GL_COLOR_ATTACHMENT13,
				GL_COLOR_ATTACHMENT14,
				GL_COLOR_ATTACHMENT15,
			};

			glDrawBuffers(numTargets, targetName);
		}
		else
		{
			glDrawBuffer(GL_NONE);
		}

		if(depthTex)
		{
			glEnable(GL_DEPTH_TEST);
		}
		else
		{
			glDisable(GL_DEPTH_TEST);
		}
	}
}

void FrameBuffer::Deactivate(void)
{
	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	glDrawBuffer(GL_BACK);

	glEnable(GL_DEPTH_TEST);
}

void FrameBuffer::UnbindTextures(void)
{
	glBindTexture(GL_TEXTURE_2D, 0);
}

//////////
//SETTERS
//////////

void FrameBuffer::BindColour(unsigned int target) const
{
	if(target < 16)
	{
		if(numTargets)
		{
			glBindTexture(GL_TEXTURE_2D, *(colourTex + target));
		}
	}
}

void FrameBuffer::BindDepth() const
{
	if(depthTex)
	{
		glBindTexture(GL_TEXTURE_2D, depthTex);
	}
}

void FrameBuffer::SetTexture(unsigned int texture)
{
	if(texture < 16)
	{
		glActiveTexture(GL_TEXTURE0 + texture);
	}
}<commit_msg>Fixed Frame buffer MRTs<commit_after>#include "FrameBuffer.h"

#include <string>

FrameBuffer::FrameBuffer(void)
{
	handle = 0;

	memset(colourTex, 0, sizeof(colourTex));

	numTargets = 0;

	depthTex = 0;

	width = height = 0;

	maxSize = 4096;
}

FrameBuffer::~FrameBuffer(void)
{
	//Release everything from graphics memory
	Release();
}

void FrameBuffer::Release(void)
{
	//Can only release data if there is a handle to get the data
	if (handle)
	{
		//Delete the FBO
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glDeleteFramebuffers(1, &handle);

		//Delete the textures
		glBindTexture(GL_TEXTURE_2D, 0);
		if (*colourTex)
		{
			glDeleteTextures(1, colourTex);
		}

		//Reset the values
		handle = 0;
		memset(colourTex, 0, sizeof(colourTex));
		numTargets = 0;
		depthTex = 0;
		width = height = 0;
	}
}

int FrameBuffer::Initialize(unsigned int w, unsigned int h,
	unsigned int colour, bool useDepth, bool useHDR,
	bool useLinearFilter, bool clamp)
{
	if (w && h && (colour || useDepth))
	{
		if (w < maxSize && w < maxSize)
		{
			width = w;
			height = h;

			const unsigned short filtering = useLinearFilter ?
			GL_LINEAR : GL_NEAREST;
			const unsigned short wrapping = clamp ?
			GL_CLAMP_TO_EDGE : GL_REPEAT;
			const unsigned short colourBit = useHDR ?
			GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
			const unsigned short colourFormat = useHDR ?
			GL_RGBA16 : GL_RGBA8;

			glGenFramebuffers(1, &handle);
			glBindFramebuffer(GL_FRAMEBUFFER, handle);

			if (colour)
			{
				//Get the maximum number of targets aloud
				int maxTargets;
				glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxTargets);

				//Detremine the number of targets this FBO will have
				if (colour > maxTargets)
					numTargets = maxTargets;
				else
					numTargets = colour;

				glGenTextures(numTargets, colourTex);

				for (unsigned int i = 0; i < numTargets; ++i)
				{
					glBindTexture(GL_TEXTURE_2D, *colourTex + i);

					glTexImage2D(GL_TEXTURE_2D, 0, colourFormat, width, height, 0, GL_RGBA, colourBit, 0);

					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);

					glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, *colourTex + i, 0);
				}
			}

			if (useDepth)
			{
				glGenTextures(1, &depthTex);
				glBindTexture(GL_TEXTURE_2D, depthTex);
				glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);

				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);

				//glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTex, 0);
				glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTex, 0);
			}

			return true;
		}
	}

	return false;
}

void FrameBuffer::Activate() const
{
	//If the FBO has been created and has a handle
	if (handle)
	{
		//Bind the FBO
		glBindFramebuffer(GL_FRAMEBUFFER, handle);

		if (numTargets)
		{
			const GLenum targetName[16] = {
				GL_COLOR_ATTACHMENT0,
				GL_COLOR_ATTACHMENT1,
				GL_COLOR_ATTACHMENT2,
				GL_COLOR_ATTACHMENT3,
				GL_COLOR_ATTACHMENT4,
				GL_COLOR_ATTACHMENT5,
				GL_COLOR_ATTACHMENT6,
				GL_COLOR_ATTACHMENT7,
				GL_COLOR_ATTACHMENT8,
				GL_COLOR_ATTACHMENT9,
				GL_COLOR_ATTACHMENT10,
				GL_COLOR_ATTACHMENT11,
				GL_COLOR_ATTACHMENT12,
				GL_COLOR_ATTACHMENT13,
				GL_COLOR_ATTACHMENT14,
				GL_COLOR_ATTACHMENT15,
			};

			glDrawBuffers(numTargets, targetName);
		}
		else
		{
			glDrawBuffer(GL_NONE);
		}

		if (depthTex)
		{
			glEnable(GL_DEPTH_TEST);
		}
		else
		{
			glDisable(GL_DEPTH_TEST);
		}
	}
}

void FrameBuffer::Deactivate(void)
{
	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	glDrawBuffer(GL_FRONT);

	glEnable(GL_DEPTH_TEST);
}

void FrameBuffer::UnbindTextures(void)
{
	glBindTexture(GL_TEXTURE_2D, 0);
}

//////////
//SETTERS
//////////

void FrameBuffer::BindColour(unsigned int target) const
{
	if (target < 16)
	{
		if (numTargets)
		{
			glBindTexture(GL_TEXTURE_2D, *(colourTex + target));
		}
	}
}

void FrameBuffer::BindDepth() const
{
	if (depthTex)
	{
		glBindTexture(GL_TEXTURE_2D, depthTex);
	}
}

void FrameBuffer::SetTexture(unsigned int texture)
{
	if (texture < 16)
	{
		glActiveTexture(GL_TEXTURE0 + texture);
	}
}<|endoftext|>