<commit_before>/*
 * DIPlib 3.0
 * This file contains the definition for the dip::MeasurementToObject function.
 *
 * (c)2016, Cris Luengo.
 * Based on original DIPlib code: (c)1995-2014, Delft University of Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "diplib.h"
#include "diplib/measurement.h"

namespace dip {

void ObjectToMeasurement(
      Image const& /*label*/,
      Image& /*out*/,
      Measurement::IteratorFeature const& /*featureValues*/
) {
   // TODO, requires LUT function.
}

} // namespace dip
<commit_msg>Implemented `dip::ObjectToMeasurement`.<commit_after>/*
 * DIPlib 3.0
 * This file contains the definition for the dip::MeasurementToObject function.
 *
 * (c)2016, Cris Luengo.
 * Based on original DIPlib code: (c)1995-2014, Delft University of Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <algorithm>

#include "diplib.h"
#include "diplib/measurement.h"
#include "diplib/lookup_table.h"

namespace dip {

void ObjectToMeasurement(
      Image const& label,
      Image& out,
      Measurement::IteratorFeature const& featureValues
) {
   DIP_THROW_IF( !label.IsScalar(), E::IMAGE_NOT_SCALAR );
   DIP_THROW_IF( !label.DataType().IsUInt(), E::DATA_TYPE_NOT_SUPPORTED );
   UnsignedArray const& objects = featureValues.Objects();
   dip::uint maxObject = *std::max_element( objects.begin(), objects.end() );
   dip::uint nElements = featureValues.NumberOfValues();
   bool protect = out.IsProtected();
   if( !protect ) {
      // If the user didn't protect the output image, we set it to SFLOAT, which is the default output type
      out.ReForge( label.Sizes(), nElements, DT_SFLOAT );
      out.Protect();
   }
   Image lutIm( { maxObject + 1 }, nElements, DT_DFLOAT );
   lutIm.Fill( 0.0 );
   DIP_ASSERT( lutIm.TensorStride() == 1 );
   dfloat* data = static_cast< dfloat* >( lutIm.Origin() );
   dip::sint stride = lutIm.Stride( 0 );
   auto it = featureValues.FirstObject();
   while( it ) {
      dfloat* dest = data + static_cast<dip::sint>( it.ObjectID() ) * stride;
      std::copy( it.begin(), it.end(), dest );
   }
   LookupTable lut( lutIm );
   lut.Apply( label, out );
   out.Protect( protect );
}

} // namespace dip
<|endoftext|>


<commit_before>#include "media/delivery/irtpstreamer.h"
#include "media/delivery/kvzrtp/rtpstreamer.h"
#include "rtpstreamer.h"
#include "framedsourcefilter.h"
#include "rtpsinkfilter.h"
#include "common.h"

#include <QtEndian>
#include <QHostInfo>
#include <QDebug>

#include <kvzrtp/rtp_opus.hh>

#include <iostream>

IRTPStreamer::~IRTPStreamer()
{
}

RTPStreamer::RTPStreamer():
  rtp_ctx_(),
  isIniated_(false)
{
}

RTPStreamer::~RTPStreamer()
{
}

void RTPStreamer::init(StatisticsInterface *stats)
{
  stats_ = stats;
  isIniated_ = true;
}

void RTPStreamer::uninit()
{
  removeAllPeers();
  isIniated_ = false;
}

void RTPStreamer::run()
{
  if (!isIniated_)
  {
    init(stats_);
  }
}

void RTPStreamer::stop()
{
  isRunning_ = false;
}

bool RTPStreamer::addPeer(uint32_t sessionID, QHostAddress video_ip, QHostAddress audio_ip)
{
  Q_ASSERT(sessionID != 0);

  // not being destroyed
  if (destroyed_.tryLock(0))
  {
    iniated_.lock(); // not being iniated

    qDebug() << "Adding peer to following IP: " << video_ip.toString() << audio_ip.toString();

    Peer *peer = new Peer;

    peer->video_ip = video_ip;
    peer->audio_ip = audio_ip;
    peer->videoSender = nullptr;
    peer->videoReceiver = nullptr;
    peer->audioSender = nullptr;
    peer->audioReceiver = nullptr;

    if((uint32_t)peers_.size() >= sessionID && peers_.at(sessionID - 1) == nullptr)
    {
      peers_[sessionID - 1] = peer;
    }
    else
    {
      while((uint32_t)peers_.size() < sessionID - 1)
      {
        peers_.append(nullptr);
      }

      peers_.push_back(peer);
    }

    iniated_.unlock();
    destroyed_.unlock();

    qDebug() << "RTP streamer: SessionID #" << sessionID << "added to rtp streamer.";

    return true;
  }
  qWarning() <<  "Trying to add peer while RTP was being destroyed.";

  return false;
}

std::shared_ptr<Filter> RTPStreamer::addSendStream(uint32_t peer, uint16_t port, QString codec, uint8_t rtpNum)
{
  Q_ASSERT(checkSessionID(peer));

  rtp_format_t type = typeFromString(codec);

  if (type == RTP_FORMAT_HEVC)
  {
    if (peers_.at(peer - 1)->videoSender)
    {
      destroySender(peers_.at(peer - 1)->videoSender);
    }

    peers_.at(peer - 1)->videoSender = addSender(peers_.at(peer - 1)->video_ip, port, type, rtpNum);
    return peers_.at(peer - 1)->videoSender->sourcefilter;
  }
  else if (type == RTP_FORMAT_OPUS || type == RTP_FORMAT_GENERIC)
  {
    if (peers_.at(peer - 1)->audioSender)
    {
      destroySender(peers_.at(peer - 1)->audioSender);
    }

    peers_.at(peer - 1)->audioSender = addSender(peers_.at(peer - 1)->audio_ip, port, type, rtpNum);
    return peers_.at(peer - 1)->audioSender->sourcefilter;
  }

  return nullptr;
}

std::shared_ptr<Filter> RTPStreamer::addReceiveStream(uint32_t peer, uint16_t port, QString codec, uint8_t rtpNum)
{
  Q_ASSERT(checkSessionID(peer));

  rtp_format_t type = typeFromString(codec);

  if (type == RTP_FORMAT_HEVC)
  {
    if (peers_.at(peer - 1)->videoReceiver)
    {
      destroyReceiver(peers_.at(peer - 1)->videoReceiver);
    }

    peers_.at(peer - 1)->videoReceiver = addReceiver(peers_.at(peer - 1)->video_ip, port, type, rtpNum);
    return peers_.at(peer - 1)->videoReceiver->sink;
  }
  else if (type == RTP_FORMAT_OPUS || type == RTP_FORMAT_GENERIC)
  {
    if (peers_.at(peer - 1)->audioReceiver)
    {
      destroyReceiver(peers_.at(peer - 1)->audioReceiver);
    }

    peers_.at(peer - 1)->audioReceiver = addReceiver(peers_.at(peer - 1)->audio_ip, port, type, rtpNum);
    return peers_.at(peer - 1)->audioReceiver->sink;
  }

  return nullptr;
}

void RTPStreamer::removeSendVideo(uint32_t sessionID)
{
  if (peers_.at(sessionID - 1) && peers_.at(sessionID)->videoSender)
  {
      destroySender(peers_.at(sessionID - 1)->videoSender);
      peers_[sessionID - 1]->videoSender = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to remove videoSender that doesn't exist!");
  }
}

void RTPStreamer::removeSendAudio(uint32_t sessionID)
{
  if (peers_.at(sessionID - 1) && peers_.at(sessionID)->audioSender)
  {
      destroySender(peers_.at(sessionID - 1)->audioSender);
      peers_[sessionID - 1]->audioSender = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to remove audioSender that doesn't exist!");
  }
}

void RTPStreamer::removeReceiveVideo(uint32_t sessionID)
{
  if (peers_.at(sessionID - 1) && peers_.at(sessionID)->videoReceiver)
  {
      destroyReceiver(peers_.at(sessionID - 1)->videoReceiver);
      peers_[sessionID - 1]->videoReceiver = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to remove videoReceiver that doesn't exist!");
  }
}

void RTPStreamer::removeReceiveAudio(uint32_t sessionID)
{
  if (peers_.at(sessionID - 1) && peers_.at(sessionID)->audioReceiver)
  {
      destroyReceiver(peers_.at(sessionID - 1)->audioReceiver);
      peers_[sessionID - 1]->audioReceiver = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to remove audioReceiver that doesn't exist!");
  }
}

void RTPStreamer::removePeer(uint32_t sessionID)
{
  qDebug() << "Removing peer" << sessionID << "from RTPStreamer";

  if (peers_.at(sessionID - 1) != nullptr)
  {
    if (peers_.at(sessionID -1 )->audioSender)
      destroySender(peers_.at(sessionID - 1)->audioSender);

    if (peers_.at(sessionID - 1)->videoSender)
      destroySender(peers_.at(sessionID - 1)->videoSender);

    if (peers_.at(sessionID - 1)->audioReceiver)
      destroyReceiver(peers_.at(sessionID - 1)->audioReceiver);

    if (peers_.at(sessionID - 1)->videoReceiver)
      destroyReceiver(peers_.at(sessionID - 1)->videoReceiver);

    delete peers_.at(sessionID - 1);
    peers_[sessionID - 1] = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to destroy an already freed peer",
              { "SessionID" }, { QString(sessionID) });
  }
}

void RTPStreamer::removeAllPeers()
{
  for (int i = 0; i < peers_.size(); ++i)
  {
    if (peers_.at(i) != nullptr)
    {
      removePeer(i + 1);
    }
  }
}

void RTPStreamer::destroySender(Sender *sender)
{
  Q_ASSERT(sender);

  if (sender)
  {
    printDebug(DEBUG_NORMAL, this, DC_REMOVE_MEDIA, "Destroying sender");

    if (rtp_ctx_.destroy_writer(sender->writer) != RTP_OK)
    {
      printDebug(DEBUG_ERROR, this, DC_REMOVE_MEDIA, "Failed to destroy RTP Writer");
    }

    delete sender;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to delete sender a second time");
  }
}
void RTPStreamer::destroyReceiver(Receiver *recv)
{
  Q_ASSERT(recv);

  if (recv)
  {
    printDebug(DEBUG_NORMAL, this, DC_REMOVE_MEDIA, "Destroying receiver");

    if (rtp_ctx_.destroy_reader(recv->reader) != RTP_OK)
    {
      printDebug(DEBUG_ERROR, this, DC_REMOVE_MEDIA, "Failed to destroy RTP Reader");
    }

    delete recv;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to delete receiver a second time");
  }
}

bool RTPStreamer::checkSessionID(uint32_t sessionID)
{
  return (uint32_t)peers_.size() >= sessionID && peers_.at(sessionID - 1) != nullptr;
}

RTPStreamer::Sender *RTPStreamer::addSender(QHostAddress ip, uint16_t port, rtp_format_t type, uint8_t rtpNum)
{
  qDebug() << "Iniating send RTP/RTCP stream to port:" << port << "With type:" << type;

  Sender *sender = new Sender;

  /* TODO: source port (1337 is not valid!) */

  sender->writer = rtp_ctx_.create_writer(ip.toString().toStdString(), port, 1337, type);
  sender->writer->start();

  // TODO is this necessary????
  QString mediaName = QString::number(port);
  DataType realType = NONE;
  kvz_rtp::opus::opus_config *config;

  switch (type)
  {
    case RTP_FORMAT_HEVC:
      mediaName += "_HEVC";
      realType = HEVCVIDEO;
      break;

    case RTP_FORMAT_OPUS:
      config = new kvz_rtp::opus::opus_config;

      config->channels = 2;
      config->samplerate = 48000;
      config->config_number = 15; // Hydrib | FB | 20 ms
      sender->writer->set_config(config);

      mediaName += "_OPUS";
      realType = OPUSAUDIO;
      break;

    case RTP_FORMAT_GENERIC:
      mediaName += "_RAW_AUDIO";
      realType = RAWAUDIO;
      break;

    default :
      qWarning() << "Warning: RTP support not implemented for this format";
      mediaName += "_UNKNOWN";
      break;
  }

  sender->sourcefilter = std::shared_ptr<FramedSourceFilter>(
      new FramedSourceFilter(
        ip.toString() + "_",
        stats_,
        realType,
        mediaName,
        sender->writer
      )
  );

  return sender;
}

RTPStreamer::Receiver *RTPStreamer::addReceiver(QHostAddress ip, uint16_t port, rtp_format_t type, uint8_t rtpNum)
{
  qDebug() << "Iniating send RTP/RTCP stream to port:" << port << "With type:" << type;

  Receiver *receiver = new Receiver;
  receiver->reader   = rtp_ctx_.create_reader(ip.toString().toStdString(), port, type);
  receiver->reader->start();

  /* unsigned int estimatedSessionBandwidth = 10000; // in kbps; for RTCP b/w share */

  // todo: negotiate payload number TODO mitä??
  QString mediaName = QString::number(port);
  DataType realType = NONE;

  switch(type)
  {
    case RTP_FORMAT_HEVC:
      mediaName += "_HEVC";
      realType = HEVCVIDEO;
      break;

    case RTP_FORMAT_OPUS:
      mediaName += "_OPUS";
      realType = OPUSAUDIO;
      break;

    case RTP_FORMAT_GENERIC:
      mediaName += "_RAW_AUDIO";
      realType = RAWAUDIO;
      break;

    default :
      qWarning() << "Warning: RTP support not implemented for this format";
      break;
  }

  // shared_ptr which does not release
  receiver->sink = std::shared_ptr<RTPSinkFilter>(
      new RTPSinkFilter(
        ip.toString() + "_",
        stats_,
        realType,
        mediaName,
        receiver->reader
      )
  );

  return receiver;
}

rtp_format_t RTPStreamer::typeFromString(QString type)
{
  std::map<QString, rtp_format_t> xmap = {
      { "pcm",  RTP_FORMAT_GENERIC },
      { "opus", RTP_FORMAT_OPUS },
      { "h265", RTP_FORMAT_HEVC }
  };

  if (xmap.find(type) == xmap.end())
  {
    qDebug() << "ERROR: Tried to use non-defined codec type in RTPSreamer.";
    return RTP_FORMAT_GENERIC;
  }

  return xmap[type];
}
<commit_msg>fix(Delivery): Convert IPv6 address to IPv4 before using it<commit_after>#include "media/delivery/irtpstreamer.h"
#include "media/delivery/kvzrtp/rtpstreamer.h"
#include "rtpstreamer.h"
#include "framedsourcefilter.h"
#include "rtpsinkfilter.h"
#include "common.h"

#include <QtEndian>
#include <QHostInfo>
#include <QDebug>

#include <kvzrtp/rtp_opus.hh>

#include <iostream>

IRTPStreamer::~IRTPStreamer()
{
}

RTPStreamer::RTPStreamer():
  rtp_ctx_(),
  isIniated_(false)
{
}

RTPStreamer::~RTPStreamer()
{
}

void RTPStreamer::init(StatisticsInterface *stats)
{
  stats_ = stats;
  isIniated_ = true;
}

void RTPStreamer::uninit()
{
  removeAllPeers();
  isIniated_ = false;
}

void RTPStreamer::run()
{
  if (!isIniated_)
  {
    init(stats_);
  }
}

void RTPStreamer::stop()
{
  isRunning_ = false;
}

bool RTPStreamer::addPeer(uint32_t sessionID, QHostAddress video_ip, QHostAddress audio_ip)
{
  Q_ASSERT(sessionID != 0);

  // check if the IP addresses start with ::ffff: and remove it, kvzrtp only accepts IPv4 addresses
  if (video_ip.toString().left(7) == "::ffff:")
  {
    video_ip = QHostAddress(video_ip.toString().mid(7));
  }

  if (audio_ip.toString().left(7) == "::ffff:")
  {
    audio_ip = QHostAddress(audio_ip.toString().mid(7));
  }

  // not being destroyed
  if (destroyed_.tryLock(0))
  {
    iniated_.lock(); // not being iniated

    qDebug() << "Adding peer to following IP: " << video_ip.toString() << audio_ip.toString();

    Peer *peer = new Peer;

    peer->video_ip = video_ip;
    peer->audio_ip = audio_ip;
    peer->videoSender = nullptr;
    peer->videoReceiver = nullptr;
    peer->audioSender = nullptr;
    peer->audioReceiver = nullptr;

    if((uint32_t)peers_.size() >= sessionID && peers_.at(sessionID - 1) == nullptr)
    {
      peers_[sessionID - 1] = peer;
    }
    else
    {
      while((uint32_t)peers_.size() < sessionID - 1)
      {
        peers_.append(nullptr);
      }

      peers_.push_back(peer);
    }

    iniated_.unlock();
    destroyed_.unlock();

    qDebug() << "RTP streamer: SessionID #" << sessionID << "added to rtp streamer.";

    return true;
  }
  qWarning() <<  "Trying to add peer while RTP was being destroyed.";

  return false;
}

std::shared_ptr<Filter> RTPStreamer::addSendStream(uint32_t peer, uint16_t port, QString codec, uint8_t rtpNum)
{
  Q_ASSERT(checkSessionID(peer));

  rtp_format_t type = typeFromString(codec);

  if (type == RTP_FORMAT_HEVC)
  {
    if (peers_.at(peer - 1)->videoSender)
    {
      destroySender(peers_.at(peer - 1)->videoSender);
    }

    peers_.at(peer - 1)->videoSender = addSender(peers_.at(peer - 1)->video_ip, port, type, rtpNum);
    return peers_.at(peer - 1)->videoSender->sourcefilter;
  }
  else if (type == RTP_FORMAT_OPUS || type == RTP_FORMAT_GENERIC)
  {
    if (peers_.at(peer - 1)->audioSender)
    {
      destroySender(peers_.at(peer - 1)->audioSender);
    }

    peers_.at(peer - 1)->audioSender = addSender(peers_.at(peer - 1)->audio_ip, port, type, rtpNum);
    return peers_.at(peer - 1)->audioSender->sourcefilter;
  }

  return nullptr;
}

std::shared_ptr<Filter> RTPStreamer::addReceiveStream(uint32_t peer, uint16_t port, QString codec, uint8_t rtpNum)
{
  Q_ASSERT(checkSessionID(peer));

  rtp_format_t type = typeFromString(codec);

  if (type == RTP_FORMAT_HEVC)
  {
    if (peers_.at(peer - 1)->videoReceiver)
    {
      destroyReceiver(peers_.at(peer - 1)->videoReceiver);
    }

    peers_.at(peer - 1)->videoReceiver = addReceiver(peers_.at(peer - 1)->video_ip, port, type, rtpNum);
    return peers_.at(peer - 1)->videoReceiver->sink;
  }
  else if (type == RTP_FORMAT_OPUS || type == RTP_FORMAT_GENERIC)
  {
    if (peers_.at(peer - 1)->audioReceiver)
    {
      destroyReceiver(peers_.at(peer - 1)->audioReceiver);
    }

    peers_.at(peer - 1)->audioReceiver = addReceiver(peers_.at(peer - 1)->audio_ip, port, type, rtpNum);
    return peers_.at(peer - 1)->audioReceiver->sink;
  }

  return nullptr;
}

void RTPStreamer::removeSendVideo(uint32_t sessionID)
{
  if (peers_.at(sessionID - 1) && peers_.at(sessionID)->videoSender)
  {
      destroySender(peers_.at(sessionID - 1)->videoSender);
      peers_[sessionID - 1]->videoSender = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to remove videoSender that doesn't exist!");
  }
}

void RTPStreamer::removeSendAudio(uint32_t sessionID)
{
  if (peers_.at(sessionID - 1) && peers_.at(sessionID)->audioSender)
  {
      destroySender(peers_.at(sessionID - 1)->audioSender);
      peers_[sessionID - 1]->audioSender = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to remove audioSender that doesn't exist!");
  }
}

void RTPStreamer::removeReceiveVideo(uint32_t sessionID)
{
  if (peers_.at(sessionID - 1) && peers_.at(sessionID)->videoReceiver)
  {
      destroyReceiver(peers_.at(sessionID - 1)->videoReceiver);
      peers_[sessionID - 1]->videoReceiver = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to remove videoReceiver that doesn't exist!");
  }
}

void RTPStreamer::removeReceiveAudio(uint32_t sessionID)
{
  if (peers_.at(sessionID - 1) && peers_.at(sessionID)->audioReceiver)
  {
      destroyReceiver(peers_.at(sessionID - 1)->audioReceiver);
      peers_[sessionID - 1]->audioReceiver = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to remove audioReceiver that doesn't exist!");
  }
}

void RTPStreamer::removePeer(uint32_t sessionID)
{
  qDebug() << "Removing peer" << sessionID << "from RTPStreamer";

  if (peers_.at(sessionID - 1) != nullptr)
  {
    if (peers_.at(sessionID -1 )->audioSender)
      destroySender(peers_.at(sessionID - 1)->audioSender);

    if (peers_.at(sessionID - 1)->videoSender)
      destroySender(peers_.at(sessionID - 1)->videoSender);

    if (peers_.at(sessionID - 1)->audioReceiver)
      destroyReceiver(peers_.at(sessionID - 1)->audioReceiver);

    if (peers_.at(sessionID - 1)->videoReceiver)
      destroyReceiver(peers_.at(sessionID - 1)->videoReceiver);

    delete peers_.at(sessionID - 1);
    peers_[sessionID - 1] = nullptr;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to destroy an already freed peer",
              { "SessionID" }, { QString(sessionID) });
  }
}

void RTPStreamer::removeAllPeers()
{
  for (int i = 0; i < peers_.size(); ++i)
  {
    if (peers_.at(i) != nullptr)
    {
      removePeer(i + 1);
    }
  }
}

void RTPStreamer::destroySender(Sender *sender)
{
  Q_ASSERT(sender);

  if (sender)
  {
    printDebug(DEBUG_NORMAL, this, DC_REMOVE_MEDIA, "Destroying sender");

    if (rtp_ctx_.destroy_writer(sender->writer) != RTP_OK)
    {
      printDebug(DEBUG_ERROR, this, DC_REMOVE_MEDIA, "Failed to destroy RTP Writer");
    }

    delete sender;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to delete sender a second time");
  }
}
void RTPStreamer::destroyReceiver(Receiver *recv)
{
  Q_ASSERT(recv);

  if (recv)
  {
    printDebug(DEBUG_NORMAL, this, DC_REMOVE_MEDIA, "Destroying receiver");

    if (rtp_ctx_.destroy_reader(recv->reader) != RTP_OK)
    {
      printDebug(DEBUG_ERROR, this, DC_REMOVE_MEDIA, "Failed to destroy RTP Reader");
    }

    delete recv;
  }
  else
  {
    printDebug(DEBUG_WARNING, this, DC_REMOVE_MEDIA, "Tried to delete receiver a second time");
  }
}

bool RTPStreamer::checkSessionID(uint32_t sessionID)
{
  return (uint32_t)peers_.size() >= sessionID && peers_.at(sessionID - 1) != nullptr;
}

RTPStreamer::Sender *RTPStreamer::addSender(QHostAddress ip, uint16_t port, rtp_format_t type, uint8_t rtpNum)
{
  qDebug() << "Iniating send RTP/RTCP stream to port:" << port << "With type:" << type;

  Sender *sender = new Sender;

  /* TODO: source port (1337 is not valid!) */

  sender->writer = rtp_ctx_.create_writer(ip.toString().toStdString(), port, 1337, type);
  sender->writer->start();

  // TODO is this necessary????
  QString mediaName = QString::number(port);
  DataType realType = NONE;
  kvz_rtp::opus::opus_config *config;

  switch (type)
  {
    case RTP_FORMAT_HEVC:
      mediaName += "_HEVC";
      realType = HEVCVIDEO;
      break;

    case RTP_FORMAT_OPUS:
      config = new kvz_rtp::opus::opus_config;

      config->channels = 2;
      config->samplerate = 48000;
      config->config_number = 15; // Hydrib | FB | 20 ms
      sender->writer->set_config(config);

      mediaName += "_OPUS";
      realType = OPUSAUDIO;
      break;

    case RTP_FORMAT_GENERIC:
      mediaName += "_RAW_AUDIO";
      realType = RAWAUDIO;
      break;

    default :
      qWarning() << "Warning: RTP support not implemented for this format";
      mediaName += "_UNKNOWN";
      break;
  }

  sender->sourcefilter = std::shared_ptr<FramedSourceFilter>(
      new FramedSourceFilter(
        ip.toString() + "_",
        stats_,
        realType,
        mediaName,
        sender->writer
      )
  );

  return sender;
}

RTPStreamer::Receiver *RTPStreamer::addReceiver(QHostAddress ip, uint16_t port, rtp_format_t type, uint8_t rtpNum)
{
  qDebug() << "Iniating send RTP/RTCP stream to port:" << port << "With type:" << type;

  Receiver *receiver = new Receiver;
  receiver->reader   = rtp_ctx_.create_reader(ip.toString().toStdString(), port, type);
  receiver->reader->start();

  /* unsigned int estimatedSessionBandwidth = 10000; // in kbps; for RTCP b/w share */

  // todo: negotiate payload number TODO mitä??
  QString mediaName = QString::number(port);
  DataType realType = NONE;

  switch(type)
  {
    case RTP_FORMAT_HEVC:
      mediaName += "_HEVC";
      realType = HEVCVIDEO;
      break;

    case RTP_FORMAT_OPUS:
      mediaName += "_OPUS";
      realType = OPUSAUDIO;
      break;

    case RTP_FORMAT_GENERIC:
      mediaName += "_RAW_AUDIO";
      realType = RAWAUDIO;
      break;

    default :
      qWarning() << "Warning: RTP support not implemented for this format";
      break;
  }

  // shared_ptr which does not release
  receiver->sink = std::shared_ptr<RTPSinkFilter>(
      new RTPSinkFilter(
        ip.toString() + "_",
        stats_,
        realType,
        mediaName,
        receiver->reader
      )
  );

  return receiver;
}

rtp_format_t RTPStreamer::typeFromString(QString type)
{
  std::map<QString, rtp_format_t> xmap = {
      { "pcm",  RTP_FORMAT_GENERIC },
      { "opus", RTP_FORMAT_OPUS },
      { "h265", RTP_FORMAT_HEVC }
  };

  if (xmap.find(type) == xmap.end())
  {
    qDebug() << "ERROR: Tried to use non-defined codec type in RTPSreamer.";
    return RTP_FORMAT_GENERIC;
  }

  return xmap[type];
}
<|endoftext|>


<commit_before>#include <map>

#include "CSE.h"
#include "IRMutator.h"
#include "IREquality.h"

namespace Halide {
namespace Internal {

using std::vector;
using std::string;
using std::map;
using std::set;
using std::pair;
using std::make_pair;

struct RemoveLets : public IRMutator {
    set<Expr, ExprDeepCompare> canonical;
    vector<map<Expr, Expr, ExprCompare> > replacement;

    RemoveLets() {
        enter_scope();
    }

    Expr canonicalize(Expr e) {
        set<Expr, ExprDeepCompare>::iterator i = canonical.find(e);
        if (i != canonical.end()) {
            return *i;
        } else {
            canonical.insert(e);
            return e;
        }
    }

    using IRMutator::mutate;

    Expr mutate(Expr e) {
        e = canonicalize(e);

        Expr r = find_replacement(e);
        if (r.defined()) {
            return r;
        } else {
            Expr new_expr = canonicalize(IRMutator::mutate(e));
            add_replacement(e, new_expr);
            return new_expr;
        }

    }

    Expr find_replacement(Expr e) {
        for (size_t i = replacement.size(); i > 0; i--) {
            map<Expr, Expr, ExprCompare>::iterator iter = replacement[i-1].find(e);
            if (iter != replacement[i-1].end()) return iter->second;
        }
        return Expr();
    }

    void add_replacement(Expr key, Expr value) {
        replacement[replacement.size()-1][key] = value;
    }

    void enter_scope() {
        replacement.resize(replacement.size()+1);
    }

    void leave_scope() {
        replacement.pop_back();
    }

    using IRMutator::visit;

    void visit(const Let *let) {
        Expr var = canonicalize(Variable::make(let->value.type(), let->name));

        Expr new_value = mutate(let->value);
        enter_scope();
        add_replacement(var, new_value);
        expr = mutate(let->body);
        leave_scope();
    }

    void visit(const LetStmt *let) {
        Expr var = canonicalize(Variable::make(let->value.type(), let->name));
        Expr new_value = mutate(let->value);
        enter_scope();
        add_replacement(var, new_value);
        stmt = mutate(let->body);
        leave_scope();
    }
};

Expr remove_lets(Expr e) {
    return RemoveLets().mutate(e);
}

Stmt remove_lets(Stmt s) {
    return RemoveLets().mutate(s);
}

struct ReplaceExpr : public IRMutator {
    using IRMutator::mutate;

    map<Expr, Expr, ExprCompare> mutated;

    Expr mutate(Expr e) {
        map<Expr, Expr, ExprCompare>::iterator iter = mutated.find(e);
        if (iter != mutated.end()) {
            return iter->second;
        } else {
            Expr new_expr = IRMutator::mutate(e);
            mutated[e] = new_expr;
            return new_expr;
        }
    }
};

Expr replace_expr(Expr e, Expr old_expr, Expr replacement) {
    ReplaceExpr r;
    r.mutated[old_expr] = replacement;
    return r.mutate(e);
}

struct FindOneCommonSubexpression : public IRGraphVisitor {
    Expr result;

    using IRGraphVisitor::include;

    void include(const Expr &e) {
        if (result.defined()) return;

        set<const IRNode *>::iterator iter = visited.find(e.ptr);

        if (iter != visited.end()) {
            if (e.as<IntImm>() || e.as<FloatImm>() || e.as<Variable>() || e.as<Cast>()) {
                return;
            }
            result = e;
        } else {
            e.accept(this);
            visited.insert(e.ptr);
        }
    }
};

Expr common_subexpression_elimination(Expr e) {

    // debug(0) << "Input to letify " << e << "\n";

    e = remove_lets(e);

    // debug(0) << "Deletified letify " << e << "\n";

    vector<pair<string, Expr> > lets;

    while (1) {
        FindOneCommonSubexpression finder;
        finder.include(e);
        if (!finder.result.defined()) break;

        // debug(0) << "\nHoisting out " << finder.result << " from " << e << "\n";

        string name = unique_name('t');

        lets.push_back(make_pair(name, finder.result));

        e = replace_expr(e, finder.result, Variable::make(finder.result.type(), name));
        // debug(0) << "Result: " << e << "\n";
    }

    for (size_t i = lets.size(); i > 0; i--) {
        e = Let::make(lets[i-1].first, lets[i-1].second, e);
    }

    // debug(0) << "Output of letify " << e << "\n";

    return e;
}

class LetifyStmt : public IRMutator {
public:
    using IRMutator::mutate;

    Expr mutate(Expr e) {
        return common_subexpression_elimination(e);
    }
};

Stmt common_subexpression_elimination(Stmt s) {
    return LetifyStmt().mutate(s);
}

}
}
<commit_msg>Allow CSE lifting of casts.<commit_after>#include <map>

#include "CSE.h"
#include "IRMutator.h"
#include "IREquality.h"
#include "IROperator.h"

namespace Halide {
namespace Internal {

using std::vector;
using std::string;
using std::map;
using std::set;
using std::pair;
using std::make_pair;

struct RemoveLets : public IRMutator {
    set<Expr, ExprDeepCompare> canonical;
    vector<map<Expr, Expr, ExprCompare> > replacement;

    RemoveLets() {
        enter_scope();
    }

    Expr canonicalize(Expr e) {
        set<Expr, ExprDeepCompare>::iterator i = canonical.find(e);
        if (i != canonical.end()) {
            return *i;
        } else {
            canonical.insert(e);
            return e;
        }
    }

    using IRMutator::mutate;

    Expr mutate(Expr e) {
        e = canonicalize(e);

        Expr r = find_replacement(e);
        if (r.defined()) {
            return r;
        } else {
            Expr new_expr = canonicalize(IRMutator::mutate(e));
            add_replacement(e, new_expr);
            return new_expr;
        }

    }

    Expr find_replacement(Expr e) {
        for (size_t i = replacement.size(); i > 0; i--) {
            map<Expr, Expr, ExprCompare>::iterator iter = replacement[i-1].find(e);
            if (iter != replacement[i-1].end()) return iter->second;
        }
        return Expr();
    }

    void add_replacement(Expr key, Expr value) {
        replacement[replacement.size()-1][key] = value;
    }

    void enter_scope() {
        replacement.resize(replacement.size()+1);
    }

    void leave_scope() {
        replacement.pop_back();
    }

    using IRMutator::visit;

    void visit(const Let *let) {
        Expr var = canonicalize(Variable::make(let->value.type(), let->name));

        Expr new_value = mutate(let->value);
        enter_scope();
        add_replacement(var, new_value);
        expr = mutate(let->body);
        leave_scope();
    }

    void visit(const LetStmt *let) {
        Expr var = canonicalize(Variable::make(let->value.type(), let->name));
        Expr new_value = mutate(let->value);
        enter_scope();
        add_replacement(var, new_value);
        stmt = mutate(let->body);
        leave_scope();
    }
};

Expr remove_lets(Expr e) {
    return RemoveLets().mutate(e);
}

Stmt remove_lets(Stmt s) {
    return RemoveLets().mutate(s);
}

struct ReplaceExpr : public IRMutator {
    using IRMutator::mutate;

    map<Expr, Expr, ExprCompare> mutated;

    Expr mutate(Expr e) {
        map<Expr, Expr, ExprCompare>::iterator iter = mutated.find(e);
        if (iter != mutated.end()) {
            return iter->second;
        } else {
            Expr new_expr = IRMutator::mutate(e);
            mutated[e] = new_expr;
            return new_expr;
        }
    }
};

Expr replace_expr(Expr e, Expr old_expr, Expr replacement) {
    ReplaceExpr r;
    r.mutated[old_expr] = replacement;
    return r.mutate(e);
}

struct FindOneCommonSubexpression : public IRGraphVisitor {
    Expr result;

    using IRGraphVisitor::include;

    void include(const Expr &e) {
        if (result.defined()) return;

        set<const IRNode *>::iterator iter = visited.find(e.ptr);

        if (iter != visited.end()) {
            if (e.as<Variable>() || is_const(e)) {
                return;
            }

            result = e;
        } else {
            e.accept(this);
            visited.insert(e.ptr);
        }
    }
};

Expr common_subexpression_elimination(Expr e) {

    // debug(0) << "Input to letify " << e << "\n";

    e = remove_lets(e);

    // debug(0) << "Deletified letify " << e << "\n";

    vector<pair<string, Expr> > lets;

    while (1) {
        FindOneCommonSubexpression finder;
        finder.include(e);
        if (!finder.result.defined()) break;

        // debug(0) << "\nHoisting out " << finder.result << " from " << e << "\n";

        string name = unique_name('t');

        lets.push_back(make_pair(name, finder.result));

        e = replace_expr(e, finder.result, Variable::make(finder.result.type(), name));
        // debug(0) << "Result: " << e << "\n";
    }

    for (size_t i = lets.size(); i > 0; i--) {
        e = Let::make(lets[i-1].first, lets[i-1].second, e);
    }

    // debug(0) << "Output of letify " << e << "\n";

    return e;
}

class LetifyStmt : public IRMutator {
public:
    using IRMutator::mutate;

    Expr mutate(Expr e) {
        return common_subexpression_elimination(e);
    }
};

Stmt common_subexpression_elimination(Stmt s) {
    return LetifyStmt().mutate(s);
}

}
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "outlinefactory.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>

#include <QToolButton>
#include <QLabel>
#include <QStackedWidget>

#include <QDebug>

namespace TextEditor {
namespace Internal {

OutlineWidgetStack::OutlineWidgetStack(OutlineFactory *factory) :
    QStackedWidget(),
    m_factory(factory),
    m_syncWithEditor(true),
    m_position(-1)
{
    QLabel *label = new QLabel(tr("No outline available"), this);
    label->setAlignment(Qt::AlignCenter);

    // set background to be white
    label->setAutoFillBackground(true);
    label->setBackgroundRole(QPalette::Base);

    addWidget(label);

    m_toggleSync = new QToolButton;
    m_toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
    m_toggleSync->setCheckable(true);
    m_toggleSync->setChecked(true);
    m_toggleSync->setToolTip(tr("Synchronize with Editor"));
    connect(m_toggleSync, SIGNAL(clicked(bool)), this, SLOT(toggleCursorSynchronization()));

    m_filterButton = new QToolButton;
    m_filterButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));
    m_filterButton->setToolTip(tr("Filter tree"));
    m_filterButton->setPopupMode(QToolButton::InstantPopup);
    m_filterButton->setProperty("noArrow", true);
    m_filterMenu = new QMenu(m_filterButton);
    m_filterButton->setMenu(m_filterMenu);

    connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(updateCurrentEditor(Core::IEditor*)));
    updateCurrentEditor(Core::EditorManager::currentEditor());
}

OutlineWidgetStack::~OutlineWidgetStack()
{
}

QToolButton *OutlineWidgetStack::toggleSyncButton()
{
    return m_toggleSync;
}

QToolButton *OutlineWidgetStack::filterButton()
{
    return m_filterButton;
}

static inline QString outLineKey(int position)
{
    return QLatin1String("Outline.") + QString::number(position) + QLatin1String(".SyncWithEditor");
}

void OutlineWidgetStack::restoreSettings(int position)
{
    m_position = position; // save it so that we can save/restore in updateCurrentEditor

    QSettings *settings = Core::ICore::settings();
    const bool toggleSync = settings->value(outLineKey(position), true).toBool();
    toggleSyncButton()->setChecked(toggleSync);

    if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
        outlineWidget->restoreSettings(position);
}

void OutlineWidgetStack::saveSettings(int position)
{
    Q_ASSERT(position == m_position);

    QSettings *settings = Core::ICore::settings();
    settings->setValue(outLineKey(position), toggleSyncButton()->isEnabled());

    if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
        outlineWidget->saveSettings(position);
}

bool OutlineWidgetStack::isCursorSynchronized() const
{
    return m_syncWithEditor;
}

void OutlineWidgetStack::toggleCursorSynchronization()
{
    m_syncWithEditor = !m_syncWithEditor;
    if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
        outlineWidget->setCursorSynchronization(m_syncWithEditor);
}

void OutlineWidgetStack::updateFilterMenu()
{
    m_filterMenu->clear();
    if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget())) {
        foreach (QAction *filterAction, outlineWidget->filterMenuActions()) {
            m_filterMenu->addAction(filterAction);
        }
    }
    m_filterButton->setEnabled(!m_filterMenu->actions().isEmpty());
}

void OutlineWidgetStack::updateCurrentEditor(Core::IEditor *editor)
{
    IOutlineWidget *newWidget = 0;

    if (editor) {
        foreach (IOutlineWidgetFactory *widgetFactory, m_factory->widgetFactories()) {
            if (widgetFactory->supportsEditor(editor)) {
                newWidget = widgetFactory->createWidget(editor);
                break;
            }
        }
    }

    if (newWidget != currentWidget()) {
        // delete old widget
        if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget())) {
            if (m_position > -1)
                outlineWidget->saveSettings(m_position);
            removeWidget(outlineWidget);
            delete outlineWidget;
        }
        if (newWidget) {
            if (m_position > -1)
                newWidget->restoreSettings(m_position);
            newWidget->setCursorSynchronization(m_syncWithEditor);
            addWidget(newWidget);
            setCurrentWidget(newWidget);
            setFocusProxy(newWidget);
        }

        updateFilterMenu();
    }
}

QList<IOutlineWidgetFactory*> OutlineFactory::widgetFactories() const
{
    return m_factories;
}

void OutlineFactory::setWidgetFactories(QList<IOutlineWidgetFactory*> factories)
{
    m_factories = factories;
}

QString OutlineFactory::displayName() const
{
    return tr("Outline");
}

int OutlineFactory::priority() const
{
    return 600;
}

Core::Id OutlineFactory::id() const
{
    return "Outline";
}

QKeySequence OutlineFactory::activationSequence() const
{
    return QKeySequence();
}

Core::NavigationView OutlineFactory::createWidget()
{
    Core::NavigationView n;
    OutlineWidgetStack *placeHolder = new OutlineWidgetStack(this);
    n.widget = placeHolder;
    n.dockToolBarWidgets.append(placeHolder->filterButton());
    n.dockToolBarWidgets.append(placeHolder->toggleSyncButton());
    return n;
}

void OutlineFactory::saveSettings(int position, QWidget *widget)
{
    OutlineWidgetStack *widgetStack = qobject_cast<OutlineWidgetStack *>(widget);
    Q_ASSERT(widgetStack);
    widgetStack->saveSettings(position);
}

void OutlineFactory::restoreSettings(int position, QWidget *widget)
{
    OutlineWidgetStack *widgetStack = qobject_cast<OutlineWidgetStack *>(widget);
    Q_ASSERT(widgetStack);
    widgetStack->restoreSettings(position);
}

} // namespace Internal
} // namespace TextEditor
<commit_msg>TextEditor: Hide filter button in outline sidebar<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "outlinefactory.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>

#include <QToolButton>
#include <QLabel>
#include <QStackedWidget>

#include <QDebug>

namespace TextEditor {
namespace Internal {

OutlineWidgetStack::OutlineWidgetStack(OutlineFactory *factory) :
    QStackedWidget(),
    m_factory(factory),
    m_syncWithEditor(true),
    m_position(-1)
{
    QLabel *label = new QLabel(tr("No outline available"), this);
    label->setAlignment(Qt::AlignCenter);

    // set background to be white
    label->setAutoFillBackground(true);
    label->setBackgroundRole(QPalette::Base);

    addWidget(label);

    m_toggleSync = new QToolButton;
    m_toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
    m_toggleSync->setCheckable(true);
    m_toggleSync->setChecked(true);
    m_toggleSync->setToolTip(tr("Synchronize with Editor"));
    connect(m_toggleSync, SIGNAL(clicked(bool)), this, SLOT(toggleCursorSynchronization()));

    m_filterButton = new QToolButton;
    m_filterButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));
    m_filterButton->setToolTip(tr("Filter tree"));
    m_filterButton->setPopupMode(QToolButton::InstantPopup);
    m_filterButton->setProperty("noArrow", true);
    m_filterMenu = new QMenu(m_filterButton);
    m_filterButton->setMenu(m_filterMenu);

    connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(updateCurrentEditor(Core::IEditor*)));
    updateCurrentEditor(Core::EditorManager::currentEditor());
}

OutlineWidgetStack::~OutlineWidgetStack()
{
}

QToolButton *OutlineWidgetStack::toggleSyncButton()
{
    return m_toggleSync;
}

QToolButton *OutlineWidgetStack::filterButton()
{
    return m_filterButton;
}

static inline QString outLineKey(int position)
{
    return QLatin1String("Outline.") + QString::number(position) + QLatin1String(".SyncWithEditor");
}

void OutlineWidgetStack::restoreSettings(int position)
{
    m_position = position; // save it so that we can save/restore in updateCurrentEditor

    QSettings *settings = Core::ICore::settings();
    const bool toggleSync = settings->value(outLineKey(position), true).toBool();
    toggleSyncButton()->setChecked(toggleSync);

    if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
        outlineWidget->restoreSettings(position);
}

void OutlineWidgetStack::saveSettings(int position)
{
    Q_ASSERT(position == m_position);

    QSettings *settings = Core::ICore::settings();
    settings->setValue(outLineKey(position), toggleSyncButton()->isEnabled());

    if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
        outlineWidget->saveSettings(position);
}

bool OutlineWidgetStack::isCursorSynchronized() const
{
    return m_syncWithEditor;
}

void OutlineWidgetStack::toggleCursorSynchronization()
{
    m_syncWithEditor = !m_syncWithEditor;
    if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
        outlineWidget->setCursorSynchronization(m_syncWithEditor);
}

void OutlineWidgetStack::updateFilterMenu()
{
    m_filterMenu->clear();
    if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget())) {
        foreach (QAction *filterAction, outlineWidget->filterMenuActions()) {
            m_filterMenu->addAction(filterAction);
        }
    }
    m_filterButton->setVisible(!m_filterMenu->actions().isEmpty());
}

void OutlineWidgetStack::updateCurrentEditor(Core::IEditor *editor)
{
    IOutlineWidget *newWidget = 0;

    if (editor) {
        foreach (IOutlineWidgetFactory *widgetFactory, m_factory->widgetFactories()) {
            if (widgetFactory->supportsEditor(editor)) {
                newWidget = widgetFactory->createWidget(editor);
                break;
            }
        }
    }

    if (newWidget != currentWidget()) {
        // delete old widget
        if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget())) {
            if (m_position > -1)
                outlineWidget->saveSettings(m_position);
            removeWidget(outlineWidget);
            delete outlineWidget;
        }
        if (newWidget) {
            if (m_position > -1)
                newWidget->restoreSettings(m_position);
            newWidget->setCursorSynchronization(m_syncWithEditor);
            addWidget(newWidget);
            setCurrentWidget(newWidget);
            setFocusProxy(newWidget);
        }

        updateFilterMenu();
    }
}

QList<IOutlineWidgetFactory*> OutlineFactory::widgetFactories() const
{
    return m_factories;
}

void OutlineFactory::setWidgetFactories(QList<IOutlineWidgetFactory*> factories)
{
    m_factories = factories;
}

QString OutlineFactory::displayName() const
{
    return tr("Outline");
}

int OutlineFactory::priority() const
{
    return 600;
}

Core::Id OutlineFactory::id() const
{
    return "Outline";
}

QKeySequence OutlineFactory::activationSequence() const
{
    return QKeySequence();
}

Core::NavigationView OutlineFactory::createWidget()
{
    Core::NavigationView n;
    OutlineWidgetStack *placeHolder = new OutlineWidgetStack(this);
    n.widget = placeHolder;
    n.dockToolBarWidgets.append(placeHolder->filterButton());
    n.dockToolBarWidgets.append(placeHolder->toggleSyncButton());
    return n;
}

void OutlineFactory::saveSettings(int position, QWidget *widget)
{
    OutlineWidgetStack *widgetStack = qobject_cast<OutlineWidgetStack *>(widget);
    Q_ASSERT(widgetStack);
    widgetStack->saveSettings(position);
}

void OutlineFactory::restoreSettings(int position, QWidget *widget)
{
    OutlineWidgetStack *widgetStack = qobject_cast<OutlineWidgetStack *>(widget);
    Q_ASSERT(widgetStack);
    widgetStack->restoreSettings(position);
}

} // namespace Internal
} // namespace TextEditor
<|endoftext|>


<commit_before>#include "nw_content_renderer_hooks.h"

// base
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/native_library.h"
#include "base/strings/utf_string_conversions.h"

#if defined(OS_MACOSX)
#include "base/mac/bundle_locations.h"
#endif

#define CONTENT_IMPLEMENTATION 1
#include "content/common/content_export.h"

// v8
#include "v8/include/v8.h"

// third_party/node
// FIXME: node_webkit.h should include v8 headers
#include "third_party/node-nw/src/node_webkit.h"

#if defined(OS_WIN)
#define _USE_MATH_DEFINES
#include <math.h>
#endif

#if defined(COMPONENT_BUILD) && defined(WIN32)
#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn;
#else
#define NW_HOOK_MAP(type, sym, fn) extern type fn;
#endif
#include "content/nw/src/common/node_hooks.h"
#undef NW_HOOK_MAP

namespace nw {

// renderer
void LoadNodeSymbols() {
  base::NativeLibraryLoadError error;
#if defined(OS_MACOSX)
  base::FilePath node_dll_path = base::mac::FrameworkBundlePath().Append(base::FilePath::FromUTF8Unsafe(base::GetNativeLibraryName("node")));
#else
  base::FilePath node_dll_path = base::FilePath::FromUTF8Unsafe(base::GetNativeLibraryName("node"));
#endif
  base::NativeLibrary node_dll = base::LoadNativeLibrary(node_dll_path, &error);
  if(!node_dll)
    LOG_IF(FATAL, true) << "Failed to load node library (error: " << error.ToString() << ")";
  else {
    #define NW_HOOK_MAP(type, sym, fn) fn = (type) base::GetFunctionPointerFromNativeLibrary(node_dll, sym); \
                                       DCHECK(fn) << "Unable to find symbol for " << sym;
    #include "content/nw/src/common/node_hooks.h"
    #undef NW_HOOK_MAP
  }
}

void KickNextTick() {
  v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);
  void* env = g_get_node_env_fn();
  if (env)
    g_call_tick_callback_fn(env);
}

} // nw
<commit_msg>Linux: Prefer own symbols in libnode.so<commit_after>#include "nw_content_renderer_hooks.h"

// base
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/native_library.h"
#include "base/strings/utf_string_conversions.h"

#if defined(OS_MACOSX)
#include "base/mac/bundle_locations.h"
#endif

#define CONTENT_IMPLEMENTATION 1
#include "content/common/content_export.h"

// v8
#include "v8/include/v8.h"

// third_party/node
// FIXME: node_webkit.h should include v8 headers
#include "third_party/node-nw/src/node_webkit.h"

#if defined(OS_WIN)
#define _USE_MATH_DEFINES
#include <math.h>
#endif

#if defined(COMPONENT_BUILD) && defined(WIN32)
#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn;
#else
#define NW_HOOK_MAP(type, sym, fn) extern type fn;
#endif
#include "content/nw/src/common/node_hooks.h"
#undef NW_HOOK_MAP

namespace nw {

// renderer
void LoadNodeSymbols() {
  base::NativeLibraryLoadError error;
#if defined(OS_MACOSX)
  base::FilePath node_dll_path = base::mac::FrameworkBundlePath().Append(base::FilePath::FromUTF8Unsafe(base::GetNativeLibraryName("node")));
#else
  base::FilePath node_dll_path = base::FilePath::FromUTF8Unsafe(base::GetNativeLibraryName("node"));
#endif
  base::NativeLibraryOptions options;
  options.prefer_own_symbols = true;
  base::NativeLibrary node_dll = base::LoadNativeLibraryWithOptions(node_dll_path, options, &error);
  if(!node_dll)
    LOG_IF(FATAL, true) << "Failed to load node library (error: " << error.ToString() << ")";
  else {
    #define NW_HOOK_MAP(type, sym, fn) fn = (type) base::GetFunctionPointerFromNativeLibrary(node_dll, sym); \
                                       DCHECK(fn) << "Unable to find symbol for " << sym;
    #include "content/nw/src/common/node_hooks.h"
    #undef NW_HOOK_MAP
  }
}

void KickNextTick() {
  v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);
  void* env = g_get_node_env_fn();
  if (env)
    g_call_tick_callback_fn(env);
}

} // nw
<|endoftext|>


<commit_before>#include "GUI.hpp"
#include "globals.hpp"
GUI::GUI()
{
	timeBarTexture.loadFromFile(std::string(PATH) + "img/timeBar.png");
	timeBarTexture.setRepeated(true);
	timeSprite = new sf::Sprite();
	timeSprite->setTexture(timeBarTexture);
	timeSprite->setPosition(10,screenHeight-30);

	itemTexture.loadFromFile(std::string(PATH) + "img/items.png");
	coinSprite = new sf::Sprite();
	coinSprite->setTexture(itemTexture);
	coinSprite->setTextureRect(sf::IntRect(0,80,16,16));

	keySprite = new sf::Sprite();
	keySprite->setTexture(itemTexture);
	keySprite->setTextureRect(sf::IntRect(0,32,16,16));

	timeoutClock = sf::Clock();
	timeoutClock.restart();

}
void GUI::setTimeout(int seconds)
{
	timeoutClock.restart();
	timeoutSeconds = seconds;
	timeBuff = 0;
}
void GUI::applyTimeBufff(float seconds)
{
	timeBuff += seconds;
}

void GUI::update (sf::Time deltaTime) {
	sf::Int32 currTime = globalClock.getElapsedTime().asMilliseconds();
	float elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff);
	float progress = 1-(elapsedSeconds / timeoutSeconds);
	//TODO: use min, max
	if (progress > 1)
	{
		progress = 1;
	}
	if (progress < 0)
	{
		progress = 0;
	}
	int width = (progress* (screenWidth-20));
	timeSprite->setTextureRect(sf::IntRect(width - int(elapsedSeconds) % width, 0, width, 20));
	window.draw(*timeSprite);

	for (int i = 0;i < coins;i++)
	{
		//TODO: Draw coins
		coinSprite->setPosition(screenWidth-25,10+(i*16));
		window.draw(*coinSprite);
	}

	for (int i = 0;i < keys;i++)
	{
		//TODO: Draw coins
		keySprite->setPosition(i*16+40,screenHeight-50);
		window.draw(*keySprite);
	}
}

void GUI::resetCoins()
{
	coins = 0;
}

void GUI::addCoins(int amount)
{
	coins += amount;
}

void GUI::resetKeys()
{
	keys = 0;
}

void GUI::addKeys(int amount)
{
	keys += amount;
}
<commit_msg>GUI-ANimationsbug gefixt<commit_after>#include "GUI.hpp"
#include "globals.hpp"
GUI::GUI()
{
	timeBarTexture.loadFromFile(std::string(PATH) + "img/timeBar.png");
	timeBarTexture.setRepeated(true);
	timeSprite = new sf::Sprite();
	timeSprite->setTexture(timeBarTexture);
	timeSprite->setPosition(10,screenHeight-30);

	itemTexture.loadFromFile(std::string(PATH) + "img/items.png");
	coinSprite = new sf::Sprite();
	coinSprite->setTexture(itemTexture);
	coinSprite->setTextureRect(sf::IntRect(0,80,16,16));

	keySprite = new sf::Sprite();
	keySprite->setTexture(itemTexture);
	keySprite->setTextureRect(sf::IntRect(0,32,16,16));

	timeoutClock = sf::Clock();
	timeoutClock.restart();

}
void GUI::setTimeout(int seconds)
{
	timeoutClock.restart();
	timeoutSeconds = seconds;
	timeBuff = 0;
}
void GUI::applyTimeBufff(float seconds)
{
	timeBuff += seconds;
}

void GUI::update (sf::Time deltaTime) {
	sf::Int32 currTime = globalClock.getElapsedTime().asMilliseconds();
	float elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff);
	float progress = 1-(elapsedSeconds / timeoutSeconds);
	//TODO: use min, max
	if (progress > 1)
	{
		progress = 1;
	}
	if (progress < 0)
	{
		progress = 0;
	}
	int width = (progress* (screenWidth-20));
	timeSprite->setTextureRect(sf::IntRect(width - int(elapsedSeconds) % 46, 0, width, 20));
	window.draw(*timeSprite);

	for (int i = 0;i < coins;i++)
	{
		//TODO: Draw coins
		coinSprite->setPosition(screenWidth-25,10+(i*16));
		window.draw(*coinSprite);
	}

	for (int i = 0;i < keys;i++)
	{
		//TODO: Draw coins
		keySprite->setPosition(i*16+40,screenHeight-50);
		window.draw(*keySprite);
	}
}

void GUI::resetCoins()
{
	coins = 0;
}

void GUI::addCoins(int amount)
{
	coins += amount;
}

void GUI::resetKeys()
{
	keys = 0;
}

void GUI::addKeys(int amount)
{
	keys += amount;
}
<|endoftext|>


<commit_before><commit_msg>Removed double include due to hidden merge conflict.<commit_after><|endoftext|>


<commit_before>#include "superParallaxDemo.h"
#include "vrambatcher.h"

SuperParallaxDemo::SuperParallaxDemo() {}
SuperParallaxDemo::~SuperParallaxDemo() {}
void SuperParallaxDemo::Load() {}
void SuperParallaxDemo::Unload() {}

struct BgPointerRecord {
	vu16* hOffset;
	vu16* vOffset;
	vu16* bgcnt;
} BgPointers[4] = {
	{ REG_BG0HOFS, REG_BG0VOFS, REG_BG0CNT },
	{ REG_BG1HOFS, REG_BG1VOFS, REG_BG1CNT },
	{ REG_BG2HOFS, REG_BG2VOFS, REG_BG2CNT },
	{ REG_BG3HOFS, REG_BG3VOFS, REG_BG3CNT }
};

void SuperParallaxDemo::PrepareFrame(VramBatcher &batcher) {

	//tick _all_ regions

	for (int scanline = 0; scanline < SCREEN_HEIGHT; ++scanline) {
		//find topmost two regions that have the lowest depth

		//for each of the two regions, with the lowest depth one first
		{
			ParallaxRegion region;
			//determinate the background layer to use
			BgPointerRecord bgPtrs;
			//ensure that the map pointer is set

			//ensure that the palette is set
			//compute the scroll Y position for the line
			int layerYOffset = region.top - (scanline - yPos);
			batcher.AddPoke(scanline, layerYOffset, bgPtrs.vOffset);
			//compute the base scroll X position for the region
			int layerXOffset = xPos*region.scrollRate;
			//add in the modulation
			layerXOffset += sin(region.wobblePhase+layerYOffset*region.wobbleLinePhase)*region.wobbleAmplitude;
			batcher.AddPoke(scanline, layerXOffset, bgPtrs.hOffset);
		}
	}

}

SuperParallaxDemo::ParallaxRegion::ParallaxRegion() {
}

SuperParallaxDemo::ParallaxRegion::~ParallaxRegion() {
}

void SuperParallaxDemo::ParallaxRegion::tick() {
	wobblePhase += wobbleRate;
}<commit_msg>Set the mapbase for the region<commit_after>#include "superParallaxDemo.h"
#include "vrambatcher.h"

SuperParallaxDemo::SuperParallaxDemo() {}
SuperParallaxDemo::~SuperParallaxDemo() {}
void SuperParallaxDemo::Load() {}
void SuperParallaxDemo::Unload() {}

struct BgPointerRecord {
	vu16* hOffset;
	vu16* vOffset;
	vu16* bgcnt;
} BgPointers[4] = {
	{ REG_BG0HOFS, REG_BG0VOFS, REG_BG0CNT },
	{ REG_BG1HOFS, REG_BG1VOFS, REG_BG1CNT },
	{ REG_BG2HOFS, REG_BG2VOFS, REG_BG2CNT },
	{ REG_BG3HOFS, REG_BG3VOFS, REG_BG3CNT }
};

void SuperParallaxDemo::PrepareFrame(VramBatcher &batcher) {

	//tick _all_ regions

	for (int scanline = 0; scanline < SCREEN_HEIGHT; ++scanline) {
		//find topmost two regions that have the lowest depth

		//for each of the two regions, with the lowest depth one first
		{
			ParallaxRegion region;
			//determinate the background layer to use
			BgPointerRecord bgPtrs;
			//ensure that the map pointer is set
			batcher.AddPoke(scanline, region.mapBase << 8, 0x1F00, bgPtrs.bgcnt);
			//ensure that the palette is set
			//compute the scroll Y position for the line
			int layerYOffset = region.top - (scanline - yPos);
			batcher.AddPoke(scanline, layerYOffset, bgPtrs.vOffset);
			//compute the base scroll X position for the region
			int layerXOffset = xPos*region.scrollRate;
			//add in the modulation
			layerXOffset += sin(region.wobblePhase+layerYOffset*region.wobbleLinePhase)*region.wobbleAmplitude;
			batcher.AddPoke(scanline, layerXOffset, bgPtrs.hOffset);
		}
	}

}

SuperParallaxDemo::ParallaxRegion::ParallaxRegion() {
}

SuperParallaxDemo::ParallaxRegion::~ParallaxRegion() {
}

void SuperParallaxDemo::ParallaxRegion::tick() {
	wobblePhase += wobbleRate;
}<|endoftext|>


<commit_before>/*
 * app.cpp
 *
 * Author: Ming Tsang
 * Copyright (c) 2014 HKUST SmartCar Team
 * Refer to LICENSE for details
 */

#include <functional>

#include <libsc/k60/system.h>
#include <libutil/misc.h>

#include "app.h"
#include "car.h"
#include "looper.h"

using namespace libsc::k60;
using namespace std;

#define CMD_MASK 0xC0
#define CMD_SHIFT 6
#define CMD(x) ((x << CMD_SHIFT) & CMD_MASK)

#define TURN_MASK 0x3F
#define TURN_SHIFT 0

#define SPD_MASK 0x3F
#define SPD_SHIFT 0

#define FLAG_BEEP_MASK 0x1
#define FLAG_BEEP_SHIFT 0
#define FLAG_LED_MASK 0x2
#define FLAG_LED_SHIFT 1

namespace inno
{

class App::Intepreter
{
public:
	static void ProcessCommand(const Byte cmd, App *parent);

private:
	static void ProcessTurnCommand(const Byte cmd, App *parent);
	static void ProcessSpeedCommand(const Byte cmd, App *parent);
	static void ProcessFlagCommand(const Byte cmd, App *parent);
};

void App::Intepreter::ProcessCommand(const Byte cmd, App *parent)
{
	if ((cmd & CMD_MASK) == CMD(3))
	{

	}
	else if ((cmd & CMD_MASK) == CMD(2))
	{
		ProcessTurnCommand(cmd, parent);
	}
	else if ((cmd & CMD_MASK) == CMD(1))
	{
		ProcessSpeedCommand(cmd, parent);
	}
	else // (cmd & CMD_MASK) == CMD(0)
	{
		ProcessFlagCommand(cmd, parent);
	}
}

void App::Intepreter::ProcessTurnCommand(const Byte cmd, App *parent)
{
	const int turn = cmd & TURN_MASK;
	// [0, 0x3F] -> [-1000, 1000]
	const int expand = turn * 2000 / TURN_MASK - 1000;
	parent->m_car.SetTurning(expand);
}

void App::Intepreter::ProcessSpeedCommand(const Byte cmd, App *parent)
{
	const int spd = cmd & SPD_MASK;
	// [0, 0x3F] -> [-1000, 1000]
	const int expand = spd * 2000 / TURN_MASK - 1000;
	parent->m_car.SetMotorPower(expand);
}

void App::Intepreter::ProcessFlagCommand(const Byte cmd, App *parent)
{
	if ((cmd & FLAG_BEEP_MASK) && !parent->m_car.GetBeep())
	{
		parent->Beep(500);
	}
	if (cmd & FLAG_LED_MASK)
	{
		parent->m_car.SwitchLed(3);
	}
}

App::App()
{}

App::~App()
{}

void App::Run()
{
	System::Init();
	m_car.UartSendLiteral("Welcome to InnoCarnival 2014\n");
	m_car.UartSendLiteral("Hello from Smart Car\n");
	m_car.SetLed(0, true);
	m_car.EnableUartRx(std::bind(&App::OnUartReceive, this, placeholders::_1,
			placeholders::_2));
	m_looper.RunAfter(200, std::bind(&App::Breath, this));
	Beep(200);

	m_looper.Loop();
}

void App::Breath()
{
	m_car.SwitchLed(0);
	m_car.SwitchLed(1);
	m_looper.RunAfter(200, std::bind(&App::Breath, this));
}

void App::Beep(const uint32_t duration)
{
	m_car.SetBeep(true);
	m_looper.RunAfter(duration,
			[this](const Timer::TimerInt, const Timer::TimerInt)
			{
				m_car.SetBeep(false);
			});
}

void App::OnUartReceive(const Byte *bytes, const size_t size)
{
	for (size_t i = 0; i < size; ++i)
	{
		Intepreter::ProcessCommand(bytes[i], this);
	}
}

}
<commit_msg>Renew command control<commit_after>/*
 * app.cpp
 *
 * Author: Ming Tsang
 * Copyright (c) 2014 HKUST SmartCar Team
 * Refer to LICENSE for details
 */

#include <functional>

#include <libsc/k60/system.h>
#include <libutil/misc.h>

#include "app.h"
#include "car.h"
#include "looper.h"

using namespace libsc::k60;
using namespace std;

#define CMD_MASK 0xC0
#define CMD_SHIFT 6
#define CMD(x) ((x << CMD_SHIFT) & CMD_MASK)

#define TURN_MASK 0x3F
#define TURN_SHIFT 0

#define SPD_MASK 0x3F
#define SPD_SHIFT 0

#define FLAG_BEEP_MASK 0x1
#define FLAG_BEEP_SHIFT 0
#define FLAG_LED_MASK 0x2
#define FLAG_LED_SHIFT 1

namespace inno
{

class App::Intepreter
{
public:
	static void ProcessCommand(const Byte cmd, App *parent);
};

void App::Intepreter::ProcessCommand(const Byte cmd, App *parent)
{
	switch (cmd)
	{
	case 'L':
		parent->m_car.SetTurning(-1000);
		break;

	case 'M':
		parent->m_car.SetTurning(0);
		break;

	case 'R':
		parent->m_car.SetTurning(1000);
		break;

	case '0':
		parent->m_car.SetMotorPower(0);
		break;

	case '1':
		parent->m_car.SetMotorPower(210);
		break;

	case '2':
		parent->m_car.SetMotorPower(250);
		break;

	case '3':
		parent->m_car.SetMotorPower(290);
		break;

	case 'B':
		parent->m_car.SetMotorPower(-210);
		break;
	}
}

App::App()
{}

App::~App()
{}

void App::Run()
{
	System::Init();
	m_car.UartSendLiteral("Welcome to InnoCarnival 2014\n");
	m_car.UartSendLiteral("Hello from Smart Car\n");
	m_car.SetLed(0, true);
	m_car.EnableUartRx(std::bind(&App::OnUartReceive, this, placeholders::_1,
			placeholders::_2));
	m_looper.RunAfter(200, std::bind(&App::Breath, this));
	Beep(200);

	m_looper.Loop();
}

void App::Breath()
{
	m_car.SwitchLed(0);
	m_car.SwitchLed(1);
	m_looper.RunAfter(200, std::bind(&App::Breath, this));
}

void App::Beep(const uint32_t duration)
{
	m_car.SetBeep(true);
	m_looper.RunAfter(duration,
			[this](const Timer::TimerInt, const Timer::TimerInt)
			{
				m_car.SetBeep(false);
			});
}

void App::OnUartReceive(const Byte *bytes, const size_t size)
{
	for (size_t i = 0; i < size; ++i)
	{
		Intepreter::ProcessCommand(bytes[i], this);
	}
}

}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCLogModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCLogModule
//    @Desc             :
// -------------------------------------------------------------------------

#define GLOG_NO_ABBREVIATED_SEVERITIES
#include "NFComm/NFPluginModule/NFIActorManager.h"
#include "NFComm/NFPluginModule/NFIActor.h"
#include "glog/logging.h"
#include <time.h>
//#include "NFStackWalker.h"
#include "NFCLogModule.h"
#include <boost/filesystem.hpp>
#include <stdarg.h>

NFCLogModule::NFCLogModule(NFIPluginManager* p)
{
    pPluginManager = p;

    //m_pFd = NULL;
}

bool NFCLogModule::Init()
{
#ifdef NF_DYNAMIC_PLUGIN

    NFIActor* pActor = (NFIActor*)(pPluginManager);
    if (pActor->GetActorID() == NFIActorManager::EACTOR_MAIN)
    {
#endif

        char szName[MAX_PATH] = {0};

#ifdef _MSC_VER
        GetConsoleTitle(szName, MAX_PATH);
        std::string strLogFile(szName);
#else
        std::string strLogFile ="LinuxLogFileName";
#endif // _MSC_VER

        google::InitGoogleLogging(strLogFile.c_str());

        std::string strPath = std::string("./log/") + szName;
        if (!boost::filesystem::exists(strPath))
        {
            boost::filesystem::create_directories(strPath);
        }

#ifdef NF_DEBUG_MODE
        google::SetStderrLogging(google::GLOG_INFO); //设置级别高于 google::INFO 的日志同时输出到屏幕
#else
        google::SetStderrLogging(google::GLOG_FATAL);//设置级别高于 google::FATAL 的日志同时输出到屏幕
#endif

#ifdef _MSC_VER
        FLAGS_colorlogtostderr = true;    //设置输出到屏幕的日志显示相应颜色
        FLAGS_servitysinglelog = true;
#else

#endif // _MSC_VER
        google::SetLogDestination(google::GLOG_FATAL, std::string(strPath + "/log_fatal_").c_str());
        google::SetLogDestination(google::GLOG_ERROR, std::string(strPath + "/log_error_").c_str());      //设置 google::error 级别的日志存储路径和文件名前缀
        google::SetLogDestination(google::GLOG_WARNING, std::string(strPath + "/log_warning_").c_str());  //设置 google::WARNING 级别的日志存储路径和文件名前缀
        google::SetLogDestination(google::GLOG_INFO, std::string(strPath + "/log_Info_").c_str());        //设置 google::INFO 级别的日志存储路径和文件名前缀

        FLAGS_logbufsecs = 0;                       //缓冲日志输出，默认为30秒，此处改为立即输出
        FLAGS_max_log_size = 100;                   //最大日志大小为 100MB
        FLAGS_stop_logging_if_full_disk = true;     //当磁盘被写满时，停止日志输出

#ifdef NF_DYNAMIC_PLUGIN
    }
#endif

    //google::SetLogFilenameExtension("91_");   //设置文件名扩展，如平台？或其它需要区分的信息
    //google::InstallFailureSignalHandler();    //捕捉 core dumped
    //google::InstallFailureWriter(&Log);       //默认捕捉 SIGSEGV 信号信息输出会输出到 stderr，可以通过下面的方法自定义输出方式：

    return true;
}

bool NFCLogModule::Shut()
{
#ifdef NF_DYNAMIC_PLUGIN
    NFIActor* pActor = (NFIActor*)(pPluginManager);
    if (pActor->GetActorID() == NFIActorManager::EACTOR_MAIN)
    {
        google::ShutdownGoogleLogging();
    }
#else
    google::ShutdownGoogleLogging();
#endif

    return true;
}

bool NFCLogModule::BeforeShut()
{
    return true;

}

bool NFCLogModule::AfterInit()
{
    return true;

}

bool NFCLogModule::Execute(const float fLasFrametime, const float fStartedTime)
{
    return true;

}

bool NFCLogModule::Log(const NF_LOG_LEVEL nll, const char* format, ...)
{
    char szBuffer[1024 * 10] = {0};

    va_list args;
    va_start(args, format);
    vsnprintf(szBuffer, sizeof(szBuffer) - 1, format, args);
    va_end(args);

#ifdef NF_DYNAMIC_PLUGIN
    NFIActor* pActor = (NFIActor*)(pPluginManager);
    if (!pActor->GetActorID() == NFIActorManager::EACTOR_MAIN)
    {
        NFIActorMessage message;
        message.eType = NFIActorMessage::EACTOR_LOG_MSG;
        message.data = szBuffer;

        const Theron::Address address = pActor->GetActorManager()->GetAddress(NFIActorManager::EACTOR_MAIN);
        if (address != Theron::Address::Null())
        {
            pActor->GetFramework().Send(message, pActor->GetAddress(), address);
        }

        return true;
    }
#endif

    switch (nll)
    {
        case NFILogModule::NLL_INFO_NORMAL:
            LOG(INFO) << szBuffer;
            break;
        case NFILogModule::NLL_WARING_NORMAL:
            LOG(WARNING) << szBuffer;
            break;
        case NFILogModule::NLL_ERROR_NORMAL:
        {
            LOG(ERROR) << szBuffer;
            //LogStack();
        }
        break;
        default:
            LOG(INFO) << szBuffer;
            break;
    }

    return true;
}

bool NFCLogModule::LogElement(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strElement, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[ELEMENT] Ident=%lld Element=%s %s %s %d\n", ident.nData64, strElement.c_str(), strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[ELEMENT] Ident=%lld Element=%s %s\n", ident.nData64, strElement.c_str(), strDesc.c_str());
    }

    return true;
}

bool NFCLogModule::LogProperty(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strProperty, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[PROPERTY] Ident=%lld Element=%s %s %s %d\n", ident.nData64, strProperty.c_str(), strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[PROPERTY] Ident=%lld Element=%s %s\n", ident.nData64, strProperty.c_str(), strDesc.c_str());
    }

    return true;

}

bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strRecord, const std::string& strDesc, const int nRow, const int nCol, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[RECORD] Ident=%lld Record=%s Row=%d Col=%d %s %s %d\n", ident.nData64, strRecord.c_str(), nRow, nCol, strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[RECORD] Ident=%lld Record=%s Row=%d Col=%d %s \n", ident.nData64, strRecord.c_str(), nRow, nCol, strDesc.c_str());
    }

    return true;

}

bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strRecord, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[RECORD] Ident=%lld Record=%s %s %s %d\n", ident.nData64, strRecord.c_str(), strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[RECORD] Ident=%lld Record=%s %s\n", ident.nData64, strRecord.c_str(), strDesc.c_str());
    }

    return true;
}

bool NFCLogModule::LogObject(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[OBJECT] Ident=%lld %s %s %d\n", ident.nData64,  strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[OBJECT] Ident=%lld %s\n", ident.nData64, strDesc.c_str());
    }

    return true;

}

void NFCLogModule::LogStack()
{

//To Add
/*
#ifdef NF_DEBUG_MODE
    time_t t = time(0);
    char szDmupName[MAX_PATH];
    tm* ptm = localtime(&t);

    sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp",  ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
    // 创建Dump文件
    HANDLE hDumpFile = CreateFile(szDmupName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    // Dump信息
    MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
    //dumpInfo.ExceptionPointers = pException;
    dumpInfo.ThreadId = GetCurrentThreadId();
    dumpInfo.ClientPointers = TRUE;

    // 写入Dump文件内容
    MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);

    CloseHandle(hDumpFile);

#endif
*/
}

bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %s %s %d\n", ident.nData64, strInfo.c_str(), strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %s \n", ident.nData64, strInfo.c_str(), strDesc.c_str());
    }

    return true;
}

bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const int nDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %d %s %d\n", ident.nData64, strInfo.c_str(), nDesc, func, line);
    }
    else
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %d\n", ident.nData64, strInfo.c_str(), nDesc);
    }

    return true;
}

bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::ostringstream& stream, const char* func, int line)
{
    switch (nll)
    {
        case NFILogModule::NLL_INFO_NORMAL:
        {
            if (0 == line)
            {
                LOG(INFO) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str();
            }
            else
            {
                LOG(INFO) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line;
            }
        }
        break;
        case NFILogModule::NLL_WARING_NORMAL:
        {
            if (0 == line)
            {
                LOG(WARNING) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str();
            }
            else
            {
                LOG(WARNING) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line;
            }
        }
        break;
        case NFILogModule::NLL_ERROR_NORMAL:
        {
            if (0 == line)
            {
                LOG(ERROR) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str();
            }
            else
            {
                LOG(ERROR) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line;
            }
        }
        break;
        default:
            break;
    }
    return true;
}

bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const char* func /*= ""*/, int line /*= 0*/)
{
    if (line > 0)
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %s %d\n", ident.nData64, strInfo.c_str(), func, line);
    }
    else
    {
        Log(nll, "[NORMAL] Ident=%lld  %s\n", ident.nData64, strInfo.c_str());
    }

    return true;
}
<commit_msg>modify logModule<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCLogModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCLogModule
//    @Desc             :
// -------------------------------------------------------------------------

#define GLOG_NO_ABBREVIATED_SEVERITIES
#include "NFComm/NFPluginModule/NFIActorManager.h"
#include "NFComm/NFPluginModule/NFIActor.h"
#include "glog/logging.h"
#include <time.h>
//#include "NFStackWalker.h"
#include "NFCLogModule.h"
#include <boost/filesystem.hpp>
#include <stdarg.h>

NFCLogModule::NFCLogModule(NFIPluginManager* p)
{
    pPluginManager = p;

    //m_pFd = NULL;
}

bool NFCLogModule::Init()
{
#ifdef NF_DYNAMIC_PLUGIN

    NFIActor* pActor = (NFIActor*)(pPluginManager);
    if (pActor->GetActorID() == NFIActorManager::EACTOR_MAIN)
    {
#endif

        char szName[MAX_PATH] = {0};
        google::InitGoogleLogging(szName);

        std::string strPath = std::string("./log/");
        if (!boost::filesystem::exists(strPath))
        {
            boost::filesystem::create_directories(strPath);
        }

#ifdef NF_DEBUG_MODE
        google::SetStderrLogging(google::GLOG_INFO); //设置级别高于 google::INFO 的日志同时输出到屏幕
#else
        google::SetStderrLogging(google::GLOG_ERROR);//设置级别高于 google::ERROR 的日志同时输出到屏幕
#endif

        FLAGS_colorlogtostderr = true;    //设置输出到屏幕的日志显示相应颜色
        FLAGS_servitysinglelog = true;

        google::SetLogDestination(google::GLOG_FATAL, std::string(strPath + "/log_fatal_").c_str());
        google::SetLogDestination(google::GLOG_ERROR, std::string(strPath + "/log_error_").c_str());      //设置 google::error 级别的日志存储路径和文件名前缀
        google::SetLogDestination(google::GLOG_WARNING, std::string(strPath + "/log_warning_").c_str());  //设置 google::WARNING 级别的日志存储路径和文件名前缀
        google::SetLogDestination(google::GLOG_INFO, std::string(strPath + "/log_Info_").c_str());        //设置 google::INFO 级别的日志存储路径和文件名前缀

        FLAGS_logbufsecs = 0;                       //缓冲日志输出，默认为30秒，此处改为立即输出
        FLAGS_max_log_size = 100;                   //最大日志大小为 100MB
        FLAGS_stop_logging_if_full_disk = true;     //当磁盘被写满时，停止日志输出

#ifdef NF_DYNAMIC_PLUGIN
    }
#endif

    //google::SetLogFilenameExtension("91_");   //设置文件名扩展，如平台？或其它需要区分的信息
    //google::InstallFailureSignalHandler();    //捕捉 core dumped
    //google::InstallFailureWriter(&Log);       //默认捕捉 SIGSEGV 信号信息输出会输出到 stderr，可以通过下面的方法自定义输出方式：

    return true;
}

bool NFCLogModule::Shut()
{
#ifdef NF_DYNAMIC_PLUGIN
    NFIActor* pActor = (NFIActor*)(pPluginManager);
    if (pActor->GetActorID() == NFIActorManager::EACTOR_MAIN)
    {
        google::ShutdownGoogleLogging();
    }
#else
    google::ShutdownGoogleLogging();
#endif

    return true;
}

bool NFCLogModule::BeforeShut()
{
    return true;

}

bool NFCLogModule::AfterInit()
{
    return true;

}

bool NFCLogModule::Execute(const float fLasFrametime, const float fStartedTime)
{
    return true;

}

bool NFCLogModule::Log(const NF_LOG_LEVEL nll, const char* format, ...)
{
    char szBuffer[1024 * 10] = {0};

    va_list args;
    va_start(args, format);
    vsnprintf(szBuffer, sizeof(szBuffer) - 1, format, args);
    va_end(args);

#ifdef NF_DYNAMIC_PLUGIN
    NFIActor* pActor = (NFIActor*)(pPluginManager);
    if (!pActor->GetActorID() == NFIActorManager::EACTOR_MAIN)
    {
        NFIActorMessage message;
        message.eType = NFIActorMessage::EACTOR_LOG_MSG;
        message.data = szBuffer;

        const Theron::Address address = pActor->GetActorManager()->GetAddress(NFIActorManager::EACTOR_MAIN);
        if (address != Theron::Address::Null())
        {
            pActor->GetFramework().Send(message, pActor->GetAddress(), address);
        }

        return true;
    }
#endif

    switch (nll)
    {
        case NFILogModule::NLL_INFO_NORMAL:
            LOG(INFO) << szBuffer;
            break;
        case NFILogModule::NLL_WARING_NORMAL:
            LOG(WARNING) << szBuffer;
            break;
        case NFILogModule::NLL_ERROR_NORMAL:
        {
            LOG(ERROR) << szBuffer;
            //LogStack();
        }
        break;
        default:
            LOG(INFO) << szBuffer;
            break;
    }

    return true;
}

bool NFCLogModule::LogElement(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strElement, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[ELEMENT] Ident=%lld Element=%s %s %s %d\n", ident.nData64, strElement.c_str(), strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[ELEMENT] Ident=%lld Element=%s %s\n", ident.nData64, strElement.c_str(), strDesc.c_str());
    }

    return true;
}

bool NFCLogModule::LogProperty(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strProperty, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[PROPERTY] Ident=%lld Element=%s %s %s %d\n", ident.nData64, strProperty.c_str(), strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[PROPERTY] Ident=%lld Element=%s %s\n", ident.nData64, strProperty.c_str(), strDesc.c_str());
    }

    return true;

}

bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strRecord, const std::string& strDesc, const int nRow, const int nCol, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[RECORD] Ident=%lld Record=%s Row=%d Col=%d %s %s %d\n", ident.nData64, strRecord.c_str(), nRow, nCol, strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[RECORD] Ident=%lld Record=%s Row=%d Col=%d %s \n", ident.nData64, strRecord.c_str(), nRow, nCol, strDesc.c_str());
    }

    return true;

}

bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strRecord, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[RECORD] Ident=%lld Record=%s %s %s %d\n", ident.nData64, strRecord.c_str(), strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[RECORD] Ident=%lld Record=%s %s\n", ident.nData64, strRecord.c_str(), strDesc.c_str());
    }

    return true;
}

bool NFCLogModule::LogObject(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[OBJECT] Ident=%lld %s %s %d\n", ident.nData64,  strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[OBJECT] Ident=%lld %s\n", ident.nData64, strDesc.c_str());
    }

    return true;

}

void NFCLogModule::LogStack()
{

//To Add
/*
#ifdef NF_DEBUG_MODE
    time_t t = time(0);
    char szDmupName[MAX_PATH];
    tm* ptm = localtime(&t);

    sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp",  ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
    // 创建Dump文件
    HANDLE hDumpFile = CreateFile(szDmupName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    // Dump信息
    MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
    //dumpInfo.ExceptionPointers = pException;
    dumpInfo.ThreadId = GetCurrentThreadId();
    dumpInfo.ClientPointers = TRUE;

    // 写入Dump文件内容
    MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);

    CloseHandle(hDumpFile);

#endif
*/
}

bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const std::string& strDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %s %s %d\n", ident.nData64, strInfo.c_str(), strDesc.c_str(), func, line);
    }
    else
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %s \n", ident.nData64, strInfo.c_str(), strDesc.c_str());
    }

    return true;
}

bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const int nDesc, const char* func, int line)
{
    if (line > 0)
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %d %s %d\n", ident.nData64, strInfo.c_str(), nDesc, func, line);
    }
    else
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %d\n", ident.nData64, strInfo.c_str(), nDesc);
    }

    return true;
}

bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::ostringstream& stream, const char* func, int line)
{
    switch (nll)
    {
        case NFILogModule::NLL_INFO_NORMAL:
        {
            if (0 == line)
            {
                LOG(INFO) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str();
            }
            else
            {
                LOG(INFO) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line;
            }
        }
        break;
        case NFILogModule::NLL_WARING_NORMAL:
        {
            if (0 == line)
            {
                LOG(WARNING) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str();
            }
            else
            {
                LOG(WARNING) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line;
            }
        }
        break;
        case NFILogModule::NLL_ERROR_NORMAL:
        {
            if (0 == line)
            {
                LOG(ERROR) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str();
            }
            else
            {
                LOG(ERROR) << "[NORMAL] Ident=" << ident.nData64 << " " << stream.str() << " " << func << " " << line;
            }
        }
        break;
        default:
            break;
    }
    return true;
}

bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFIDENTID ident, const std::string& strInfo, const char* func /*= ""*/, int line /*= 0*/)
{
    if (line > 0)
    {
        Log(nll, "[NORMAL] Ident=%lld  %s %s %d\n", ident.nData64, strInfo.c_str(), func, line);
    }
    else
    {
        Log(nll, "[NORMAL] Ident=%lld  %s\n", ident.nData64, strInfo.c_str());
    }

    return true;
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2008 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

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

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgrePrerequisites.h"
#include "OgreMemoryNedAlloc.h"
#include "OgrePlatformInformation.h"
#include "OgreMemoryTracker.h"

#if OGRE_MEMORY_ALLOCATOR == OGRE_MEMORY_ALLOCATOR_NED

// include ned implementation
#include <nedmalloc.c>

namespace Ogre
{

	//---------------------------------------------------------------------
	void* NedAllocImpl::allocBytes(size_t count,
		const char* file, int line, const char* func)
	{
		void* ptr = nedalloc::nedmalloc(count);
	#if OGRE_MEMORY_TRACKER
		// this alloc policy doesn't do pools (yet, ned can do it)
		MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
	#else
		// avoid unused params warning
		file;line;func;
	#endif
		return ptr;
	}
	//---------------------------------------------------------------------
	void NedAllocImpl::deallocBytes(void* ptr)
	{
#if OGRE_MEMORY_TRACKER
		MemoryTracker::get()._recordDealloc(ptr);
#endif
		nedalloc::nedfree(ptr);
	}
	//---------------------------------------------------------------------
	void* NedAllocImpl::allocBytesAligned(size_t align, size_t count,
		const char* file, int line, const char* func)
	{
		// default to platform SIMD alignment if none specified
		void* ptr =  align ? nedalloc::nedmemalign(align, count)
			: nedalloc::nedmemalign(OGRE_SIMD_ALIGNMENT, count);
#if OGRE_MEMORY_TRACKER
		// this alloc policy doesn't do pools (yet, ned can do it)
		MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
#else
		// avoid unused params warning
		file;line;func;
#endif
		return ptr;
	}
	//---------------------------------------------------------------------
	void NedAllocImpl::deallocBytesAligned(size_t align, void* ptr)
	{
#if OGRE_MEMORY_TRACKER
		// this alloc policy doesn't do pools (yet, ned can do it)
		MemoryTracker::get()._recordDealloc(ptr);
#endif
		nedalloc::nedfree(ptr);
	}

}

#endif

<commit_msg>Ned deallocator should deal with null pointers<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2008 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

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

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgrePrerequisites.h"
#include "OgreMemoryNedAlloc.h"
#include "OgrePlatformInformation.h"
#include "OgreMemoryTracker.h"

#if OGRE_MEMORY_ALLOCATOR == OGRE_MEMORY_ALLOCATOR_NED

// include ned implementation
#include <nedmalloc.c>

namespace Ogre
{

	//---------------------------------------------------------------------
	void* NedAllocImpl::allocBytes(size_t count,
		const char* file, int line, const char* func)
	{
		void* ptr = nedalloc::nedmalloc(count);
	#if OGRE_MEMORY_TRACKER
		// this alloc policy doesn't do pools (yet, ned can do it)
		MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
	#else
		// avoid unused params warning
		file;line;func;
	#endif
		return ptr;
	}
	//---------------------------------------------------------------------
	void NedAllocImpl::deallocBytes(void* ptr)
	{
		// deal with null
		if (!ptr)
			return;
#if OGRE_MEMORY_TRACKER
		MemoryTracker::get()._recordDealloc(ptr);
#endif
		nedalloc::nedfree(ptr);
	}
	//---------------------------------------------------------------------
	void* NedAllocImpl::allocBytesAligned(size_t align, size_t count,
		const char* file, int line, const char* func)
	{
		// default to platform SIMD alignment if none specified
		void* ptr =  align ? nedalloc::nedmemalign(align, count)
			: nedalloc::nedmemalign(OGRE_SIMD_ALIGNMENT, count);
#if OGRE_MEMORY_TRACKER
		// this alloc policy doesn't do pools (yet, ned can do it)
		MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
#else
		// avoid unused params warning
		file;line;func;
#endif
		return ptr;
	}
	//---------------------------------------------------------------------
	void NedAllocImpl::deallocBytesAligned(size_t align, void* ptr)
	{
		// deal with null
		if (!ptr)
			return;
#if OGRE_MEMORY_TRACKER
		// this alloc policy doesn't do pools (yet, ned can do it)
		MemoryTracker::get()._recordDealloc(ptr);
#endif
		nedalloc::nedfree(ptr);
	}

}

#endif

<|endoftext|>