<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "gtest/gtest.h"
#include "webrtc/modules/video_coding/codecs/vp8/vp8_impl.h"
#include "webrtc/modules/video_coding/codecs/test_framework/video_source.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/test/testsupport/fileutils.h"

namespace webrtc {

enum { kMaxWaitEncTimeMs = 100 };
enum { kMaxWaitDecTimeMs = 25 };

// TODO(mikhal): Replace these with mocks.
class Vp8UnitTestEncodeCompleteCallback : public webrtc::EncodedImageCallback {
 public:
  Vp8UnitTestEncodeCompleteCallback(VideoFrame* frame,
                                    unsigned int decoderSpecificSize,
                                    void* decoderSpecificInfo)
     : encoded_video_frame_(frame),
       encode_complete_(false) {}
  int Encoded(EncodedImage& encodedImage,
              const CodecSpecificInfo* codecSpecificInfo,
              const RTPFragmentationHeader*);
  bool EncodeComplete();
  // Note that this only makes sense if an encode has been completed
  VideoFrameType EncodedFrameType() const {return  encoded_frame_type_;}

 private:
  VideoFrame* encoded_video_frame_;
  bool encode_complete_;
  VideoFrameType encoded_frame_type_;
};

int Vp8UnitTestEncodeCompleteCallback::Encoded(EncodedImage& encodedImage,
    const CodecSpecificInfo* codecSpecificInfo,
    const RTPFragmentationHeader* fragmentation) {
  encoded_video_frame_->VerifyAndAllocate(encodedImage._size);
  encoded_video_frame_->CopyFrame(encodedImage._size, encodedImage._buffer);
  encoded_video_frame_->SetLength(encodedImage._length);
  // TODO(mikhal): Update frame type API.
  // encoded_video_frame_->SetFrameType(encodedImage._frameType);
  encoded_video_frame_->SetWidth(encodedImage._encodedWidth);
  encoded_video_frame_->SetHeight(encodedImage._encodedHeight);
  encoded_video_frame_->SetTimeStamp(encodedImage._timeStamp);
  encode_complete_ = true;
  encoded_frame_type_ = encodedImage._frameType;
  return 0;
}

bool Vp8UnitTestEncodeCompleteCallback::EncodeComplete() {
  if (encode_complete_) {
    encode_complete_ = false;
    return true;
  }
  return false;
}

class Vp8UnitTestDecodeCompleteCallback : public webrtc::DecodedImageCallback {
 public:
  explicit Vp8UnitTestDecodeCompleteCallback(I420VideoFrame* frame)
      : decoded_video_frame_(frame),
        decode_complete(false) {}
  int Decoded(webrtc::I420VideoFrame& frame);
  bool DecodeComplete();
 private:
  I420VideoFrame* decoded_video_frame_;
  bool decode_complete;
};

bool Vp8UnitTestDecodeCompleteCallback::DecodeComplete() {
  if (decode_complete) {
    decode_complete = false;
    return true;
  }
  return false;
}

int Vp8UnitTestDecodeCompleteCallback::Decoded(I420VideoFrame& image) {
  decoded_video_frame_->CopyFrame(image);
  decode_complete = true;
  return 0;
}

class TestVp8Impl : public ::testing::Test {
 protected:
  virtual void SetUp() {
    encoder_.reset(new VP8EncoderImpl());
    decoder_.reset(new VP8DecoderImpl());
    memset(&codec_inst_, 0, sizeof(codec_inst_));
    encode_complete_callback_.reset(new
        Vp8UnitTestEncodeCompleteCallback(&encoded_video_frame_, 0, NULL));
    decode_complete_callback_.reset(new
        Vp8UnitTestDecodeCompleteCallback(&decoded_video_frame_));
    encoder_->RegisterEncodeCompleteCallback(encode_complete_callback_.get());
    decoder_->RegisterDecodeCompleteCallback(decode_complete_callback_.get());
  }

  int WaitForEncodedFrame() const {
    int64_t startTime = TickTime::MillisecondTimestamp();
    while (TickTime::MillisecondTimestamp() - startTime < kMaxWaitEncTimeMs) {
      if (encode_complete_callback_->EncodeComplete()) {
        return encoded_video_frame_.Length();
      }
    }
    return 0;
  }

  int WaitForDecodedFrame() const {
    int64_t startTime = TickTime::MillisecondTimestamp();
    while (TickTime::MillisecondTimestamp() - startTime < kMaxWaitDecTimeMs) {
      if (decode_complete_callback_->DecodeComplete()) {
        return CalcBufferSize(kI420, decoded_video_frame_.width(),
                              decoded_video_frame_.height());
      }
    }
    return 0;
  }

  void VideoFrameToEncodedImage(VideoFrame& frame, EncodedImage &image) {
    image._buffer = frame.Buffer();
    image._length = frame.Length();
    image._size = frame.Size();
    image._timeStamp = frame.TimeStamp();
    image._encodedWidth = frame.Width();
    image._encodedHeight = frame.Height();
    image._completeFrame = true;
  }

  scoped_ptr<Vp8UnitTestEncodeCompleteCallback> encode_complete_callback_;
  scoped_ptr<Vp8UnitTestDecodeCompleteCallback> decode_complete_callback_;
  scoped_array<uint8_t> source_buffer_;
  FILE* source_file_;
  scoped_ptr<VideoEncoder> encoder_;
  scoped_ptr<VideoDecoder> decoder_;
  VideoFrame encoded_video_frame_;
  I420VideoFrame decoded_video_frame_;
  unsigned int length_source_frame_;
  VideoCodec codec_inst_;
};

TEST_F(TestVp8Impl, AlignedStrideEncodeDecode) {
  // Using a QCIF image (aligned stride (u,v planse) > width).
  // Processing only one frame.
  const VideoSource source(test::ResourcePath("paris_qcif", "yuv"), kQCIF);
  length_source_frame_ = source.GetFrameLength();
  source_buffer_.reset(new uint8_t[length_source_frame_]);
  source_file_ = fopen(source.GetFileName().c_str(), "rb");
  ASSERT_TRUE(source_file_ != NULL);
  codec_inst_.maxFramerate = source.GetFrameRate();
  codec_inst_.startBitrate = 300;
  codec_inst_.maxBitrate = 4000;
  codec_inst_.width = source.GetWidth();
  codec_inst_.height = source.GetHeight();
  codec_inst_.codecSpecific.VP8.denoisingOn = true;

  // Get input frame.
  ASSERT_EQ(fread(source_buffer_.get(), 1, length_source_frame_, source_file_),
            length_source_frame_);
  // Setting aligned stride values.
  int stride_uv = 0;
  int stride_y = 0;
  Calc16ByteAlignedStride(codec_inst_.width, &stride_y, &stride_uv);
  EXPECT_EQ(stride_y, 176);
  EXPECT_EQ(stride_uv, 96);

  I420VideoFrame input_frame;
  input_frame.CreateEmptyFrame(codec_inst_.width, codec_inst_.height,
                               stride_y, stride_uv, stride_uv);
  // Using ConvertToI420 to add stride to the image.
  EXPECT_EQ(0, ConvertToI420(kI420, source_buffer_.get(), 0, 0,
                             codec_inst_.width, codec_inst_.height,
                             0, kRotateNone, &input_frame));

  EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, encoder_->InitEncode(&codec_inst_, 1, 1440));
  encoder_->Encode(input_frame, NULL, NULL);
  EXPECT_GT(WaitForEncodedFrame(), 0);
  EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->InitDecode(&codec_inst_, 1));
  EncodedImage encodedImage;
  VideoFrameToEncodedImage(encoded_video_frame_, encodedImage);
  EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->Decode(encodedImage, false, NULL));
  EXPECT_GT(WaitForDecodedFrame(), 0);
  // Compute PSNR on all planes (faster than SSIM).
  EXPECT_GT(I420PSNR(&input_frame, &decoded_video_frame_), 36);
}

}  // namespace webrtc
<commit_msg>vp8 test: Updating creation of enc/dec<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "gtest/gtest.h"
#include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h"
#include "webrtc/modules/video_coding/codecs/test_framework/video_source.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/test/testsupport/fileutils.h"

namespace webrtc {

enum { kMaxWaitEncTimeMs = 100 };
enum { kMaxWaitDecTimeMs = 25 };

// TODO(mikhal): Replace these with mocks.
class Vp8UnitTestEncodeCompleteCallback : public webrtc::EncodedImageCallback {
 public:
  Vp8UnitTestEncodeCompleteCallback(VideoFrame* frame,
                                    unsigned int decoderSpecificSize,
                                    void* decoderSpecificInfo)
     : encoded_video_frame_(frame),
       encode_complete_(false) {}
  int Encoded(EncodedImage& encodedImage,
              const CodecSpecificInfo* codecSpecificInfo,
              const RTPFragmentationHeader*);
  bool EncodeComplete();
  // Note that this only makes sense if an encode has been completed
  VideoFrameType EncodedFrameType() const {return  encoded_frame_type_;}

 private:
  VideoFrame* encoded_video_frame_;
  bool encode_complete_;
  VideoFrameType encoded_frame_type_;
};

int Vp8UnitTestEncodeCompleteCallback::Encoded(EncodedImage& encodedImage,
    const CodecSpecificInfo* codecSpecificInfo,
    const RTPFragmentationHeader* fragmentation) {
  encoded_video_frame_->VerifyAndAllocate(encodedImage._size);
  encoded_video_frame_->CopyFrame(encodedImage._size, encodedImage._buffer);
  encoded_video_frame_->SetLength(encodedImage._length);
  // TODO(mikhal): Update frame type API.
  // encoded_video_frame_->SetFrameType(encodedImage._frameType);
  encoded_video_frame_->SetWidth(encodedImage._encodedWidth);
  encoded_video_frame_->SetHeight(encodedImage._encodedHeight);
  encoded_video_frame_->SetTimeStamp(encodedImage._timeStamp);
  encode_complete_ = true;
  encoded_frame_type_ = encodedImage._frameType;
  return 0;
}

bool Vp8UnitTestEncodeCompleteCallback::EncodeComplete() {
  if (encode_complete_) {
    encode_complete_ = false;
    return true;
  }
  return false;
}

class Vp8UnitTestDecodeCompleteCallback : public webrtc::DecodedImageCallback {
 public:
  explicit Vp8UnitTestDecodeCompleteCallback(I420VideoFrame* frame)
      : decoded_video_frame_(frame),
        decode_complete(false) {}
  int Decoded(webrtc::I420VideoFrame& frame);
  bool DecodeComplete();
 private:
  I420VideoFrame* decoded_video_frame_;
  bool decode_complete;
};

bool Vp8UnitTestDecodeCompleteCallback::DecodeComplete() {
  if (decode_complete) {
    decode_complete = false;
    return true;
  }
  return false;
}

int Vp8UnitTestDecodeCompleteCallback::Decoded(I420VideoFrame& image) {
  decoded_video_frame_->CopyFrame(image);
  decode_complete = true;
  return 0;
}

class TestVp8Impl : public ::testing::Test {
 protected:
  virtual void SetUp() {
    encoder_.reset(VP8Encoder::Create());
    decoder_.reset(VP8Decoder::Create());
    memset(&codec_inst_, 0, sizeof(codec_inst_));
    encode_complete_callback_.reset(new
        Vp8UnitTestEncodeCompleteCallback(&encoded_video_frame_, 0, NULL));
    decode_complete_callback_.reset(new
        Vp8UnitTestDecodeCompleteCallback(&decoded_video_frame_));
    encoder_->RegisterEncodeCompleteCallback(encode_complete_callback_.get());
    decoder_->RegisterDecodeCompleteCallback(decode_complete_callback_.get());
  }

  int WaitForEncodedFrame() const {
    int64_t startTime = TickTime::MillisecondTimestamp();
    while (TickTime::MillisecondTimestamp() - startTime < kMaxWaitEncTimeMs) {
      if (encode_complete_callback_->EncodeComplete()) {
        return encoded_video_frame_.Length();
      }
    }
    return 0;
  }

  int WaitForDecodedFrame() const {
    int64_t startTime = TickTime::MillisecondTimestamp();
    while (TickTime::MillisecondTimestamp() - startTime < kMaxWaitDecTimeMs) {
      if (decode_complete_callback_->DecodeComplete()) {
        return CalcBufferSize(kI420, decoded_video_frame_.width(),
                              decoded_video_frame_.height());
      }
    }
    return 0;
  }

  void VideoFrameToEncodedImage(VideoFrame& frame, EncodedImage &image) {
    image._buffer = frame.Buffer();
    image._length = frame.Length();
    image._size = frame.Size();
    image._timeStamp = frame.TimeStamp();
    image._encodedWidth = frame.Width();
    image._encodedHeight = frame.Height();
    image._completeFrame = true;
  }

  scoped_ptr<Vp8UnitTestEncodeCompleteCallback> encode_complete_callback_;
  scoped_ptr<Vp8UnitTestDecodeCompleteCallback> decode_complete_callback_;
  scoped_array<uint8_t> source_buffer_;
  FILE* source_file_;
  scoped_ptr<VideoEncoder> encoder_;
  scoped_ptr<VideoDecoder> decoder_;
  VideoFrame encoded_video_frame_;
  I420VideoFrame decoded_video_frame_;
  unsigned int length_source_frame_;
  VideoCodec codec_inst_;
};

TEST_F(TestVp8Impl, AlignedStrideEncodeDecode) {
  // Using a QCIF image (aligned stride (u,v planse) > width).
  // Processing only one frame.
  const VideoSource source(test::ResourcePath("paris_qcif", "yuv"), kQCIF);
  length_source_frame_ = source.GetFrameLength();
  source_buffer_.reset(new uint8_t[length_source_frame_]);
  source_file_ = fopen(source.GetFileName().c_str(), "rb");
  ASSERT_TRUE(source_file_ != NULL);
  codec_inst_.maxFramerate = source.GetFrameRate();
  codec_inst_.startBitrate = 300;
  codec_inst_.maxBitrate = 4000;
  codec_inst_.width = source.GetWidth();
  codec_inst_.height = source.GetHeight();
  codec_inst_.codecSpecific.VP8.denoisingOn = true;

  // Get input frame.
  ASSERT_EQ(fread(source_buffer_.get(), 1, length_source_frame_, source_file_),
            length_source_frame_);
  // Setting aligned stride values.
  int stride_uv = 0;
  int stride_y = 0;
  Calc16ByteAlignedStride(codec_inst_.width, &stride_y, &stride_uv);
  EXPECT_EQ(stride_y, 176);
  EXPECT_EQ(stride_uv, 96);

  I420VideoFrame input_frame;
  input_frame.CreateEmptyFrame(codec_inst_.width, codec_inst_.height,
                               stride_y, stride_uv, stride_uv);
  // Using ConvertToI420 to add stride to the image.
  EXPECT_EQ(0, ConvertToI420(kI420, source_buffer_.get(), 0, 0,
                             codec_inst_.width, codec_inst_.height,
                             0, kRotateNone, &input_frame));

  EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, encoder_->InitEncode(&codec_inst_, 1, 1440));
  encoder_->Encode(input_frame, NULL, NULL);
  EXPECT_GT(WaitForEncodedFrame(), 0);
  EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->InitDecode(&codec_inst_, 1));
  EncodedImage encodedImage;
  VideoFrameToEncodedImage(encoded_video_frame_, encodedImage);
  EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->Decode(encodedImage, false, NULL));
  EXPECT_GT(WaitForDecodedFrame(), 0);
  // Compute PSNR on all planes (faster than SSIM).
  EXPECT_GT(I420PSNR(&input_frame, &decoded_video_frame_), 36);
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/*
 * fiberrenderer.cpp
 *
 * Created on: 28.12.2012
 * @author Ralph Schurade
 */
#include "tuberenderer.h"
#include "tuberendererthread.h"

#include "glfunctions.h"

#include "../../data/enums.h"
#include "../../data/datasets/fiberselector.h"
#include "../../data/properties/propertygroup.h"

#include <QtOpenGL/QGLShaderProgram>
#include <QDebug>

TubeRenderer::TubeRenderer( FiberSelector* selector, QVector< QVector< float > >* data, QVector< QVector< float > >* extraData )  :
    ObjectRenderer(),
    m_selector( selector ),
    vboIds( new GLuint[ 4 ] ),
    m_data( data ),
    m_extraData( extraData ),
    m_numLines( data->size() ),
    m_numPoints( 0 ),
    m_isInitialized( false )
{
    m_colorField.resize( m_numLines );
}

TubeRenderer::~TubeRenderer()
{
    glDeleteBuffers( 4, vboIds );
}

void TubeRenderer::init()
{
    glGenBuffers( 4, vboIds );
}

void TubeRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup* props )
{
    float alpha = props->get( Fn::Property::D_ALPHA ).toFloat();

    if ( renderMode == 0 ) // picking
    {
        return;
    }
    else if ( renderMode == 1 ) // we are drawing opaque objects
    {
        if ( alpha < 1.0 )
        {
            // obviously not opaque
            return;
        }
    }
    else // we are drawing tranparent objects
    {
        if ( !(alpha < 1.0 ) )
        {
            // not transparent
            return;
        }
    }

    QGLShaderProgram* program = GLFunctions::getShader( "tube" );
    program->bind();

    GLFunctions::setupTextures();
    GLFunctions::setTextureUniforms( GLFunctions::getShader( "tube" ), "maingl" );

    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "mv_matrixTI", mv_matrix.transposed().inverted() );

    //glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    initGeometry();

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    setShaderVars( props );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[2] );
    int extraLocation = program->attributeLocation( "a_extra" );
    program->enableAttributeArray( extraLocation );
    glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[3] );
    int indexLocation = program->attributeLocation( "a_indexes" );
    program->enableAttributeArray( indexLocation );
    glVertexAttribPointer( indexLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );

    QVector<bool>*selected = m_selector->getSelection();
    for ( int i = 0; i < m_data->size(); ++i )
    {
        if ( selected->at( i ) )
        {
            program->setUniformValue( "u_color", m_colorField[i].redF(),
                                                   m_colorField[i].greenF(),
                                                   m_colorField[i].blueF(), 1.0 );
            program->setUniformValue( "u_globalColor", m_globalColorField[i].x(),
                                                         m_globalColorField[i].y(),
                                                         m_globalColorField[i].z(), 1.0 );
            glDrawArrays( GL_QUAD_STRIP, m_startIndexes[i]*2, m_pointsPerLine[i]*2 );
        }
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    //glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
}

void TubeRenderer::setupTextures()
{
}

void TubeRenderer::setShaderVars( PropertyGroup* props )
{
    QGLShaderProgram* program = GLFunctions::getShader( "tube" );

    program->bind();

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int numFloats = 7;

    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset );

    offset += sizeof(float) * 3;
    int normalLocation = program->attributeLocation( "a_normal" );
    program->enableAttributeArray( normalLocation );
    glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset );

    offset += sizeof(float) * 3;
    int dirLocation = program->attributeLocation( "a_direction" );
    program->enableAttributeArray( dirLocation );
    glVertexAttribPointer( dirLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset );

    program->setUniformValue( "u_fibGrowth", props->get( Fn::Property::D_FIBER_GROW_LENGTH).toFloat() );
    program->setUniformValue( "u_colorMode", props->get( Fn::Property::D_COLORMODE ).toInt() );
    program->setUniformValue( "u_colormap", props->get( Fn::Property::D_COLORMAP ).toInt() );
    program->setUniformValue( "u_color", 1.0, 0.0, 0.0, 1.0 );
    program->setUniformValue( "u_selectedMin", props->get( Fn::Property::D_SELECTED_MIN ).toFloat() );
    program->setUniformValue( "u_selectedMax", props->get( Fn::Property::D_SELECTED_MAX ).toFloat() );
    program->setUniformValue( "u_lowerThreshold", props->get( Fn::Property::D_LOWER_THRESHOLD ).toFloat() );
    program->setUniformValue( "u_upperThreshold", props->get( Fn::Property::D_UPPER_THRESHOLD ).toFloat() );
    program->setUniformValue( "u_thickness", props->get( Fn::Property::D_FIBER_THICKNESS ).toFloat() / 100.f );
}

void TubeRenderer::initGeometry()
{
    if ( m_isInitialized )
    {
        return;
    }
    qDebug() << "create tube vbo's...";
    int numThreads = GLFunctions::idealThreadCount;

    QVector<TubeRendererThread*> threads;
    // create threads
    for ( int i = 0; i < numThreads; ++i )
    {
        threads.push_back( new TubeRendererThread( m_data, i ) );
    }

    // run threads
    for ( int i = 0; i < numThreads; ++i )
    {
        threads[i]->start();
    }

    // wait for all threads to finish
    for ( int i = 0; i < numThreads; ++i )
    {
        threads[i]->wait();
    }

    QVector<float> verts;
    // combine verts from all threads
    m_globalColorField.clear();
    for ( int i = 0; i < numThreads; ++i )
    {
        verts += *( threads[i]->getVerts() );
        m_globalColorField += *( threads[i]->getGlobalColors() );
    }

    for ( int i = 0; i < numThreads; ++i )
    {
        delete threads[i];
    }

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    glBufferData( GL_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    m_pointsPerLine.resize( m_data->size() );
    m_startIndexes.resize( m_data->size() );

    int currentStart = 0;
    for ( int i = 0; i < m_data->size(); ++i )
    {
        m_pointsPerLine[i] = m_data->at( i ).size() / 3;
        m_startIndexes[i] = currentStart;
        currentStart += m_pointsPerLine[i];
    }

    updateExtraData( m_extraData );

    qDebug() << "create tube vbo's done";

    m_numPoints = verts.size() / 7;

    m_isInitialized = true;
}

void TubeRenderer::colorChanged( QVariant color )
{
    QVector<bool>*selected = m_selector->getSelection();
    for ( int i = 0; i < m_numLines; ++i )
    {
        if ( selected->at( i ) )
        {
            m_colorField.replace( i, color.value<QColor>() );
        }
    }
}

void TubeRenderer::updateExtraData( QVector< QVector< float > >* extraData )
{
    m_extraData = extraData;
    QVector<float>data;
    QVector<float>indexes;
    for ( int i = 0; i < extraData->size(); ++i )
    {
        QVector<float>fib = extraData->at(i);
        for ( int k = 0; k < fib.size(); ++k )
        {
            data.push_back( fib[k]);
            data.push_back( fib[k]);
            indexes.push_back( k );
            indexes.push_back( k );
        }
    }

    glDeleteBuffers( 1, &vboIds[2] );
    glGenBuffers( 1, &vboIds[2] );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[2] );
    glBufferData( GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    glDeleteBuffers( 1, &vboIds[2] );
    glGenBuffers( 1, &vboIds[2] );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[3] );
    glBufferData( GL_ARRAY_BUFFER, indexes.size() * sizeof(GLfloat), indexes.data(), GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
<commit_msg>fixed crash with tuberenderer<commit_after>/*
 * fiberrenderer.cpp
 *
 * Created on: 28.12.2012
 * @author Ralph Schurade
 */
#include "tuberenderer.h"
#include "tuberendererthread.h"

#include "glfunctions.h"

#include "../../data/enums.h"
#include "../../data/datasets/fiberselector.h"
#include "../../data/properties/propertygroup.h"

#include <QtOpenGL/QGLShaderProgram>
#include <QDebug>

TubeRenderer::TubeRenderer( FiberSelector* selector, QVector< QVector< float > >* data, QVector< QVector< float > >* extraData )  :
    ObjectRenderer(),
    m_selector( selector ),
    vboIds( new GLuint[ 4 ] ),
    m_data( data ),
    m_extraData( extraData ),
    m_numLines( data->size() ),
    m_numPoints( 0 ),
    m_isInitialized( false )
{
    m_colorField.resize( m_numLines );
}

TubeRenderer::~TubeRenderer()
{
    glDeleteBuffers( 4, vboIds );
}

void TubeRenderer::init()
{
    glGenBuffers( 4, vboIds );
}

void TubeRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup* props )
{
    float alpha = props->get( Fn::Property::D_ALPHA ).toFloat();

    if ( renderMode == 0 ) // picking
    {
        return;
    }
    else if ( renderMode == 1 ) // we are drawing opaque objects
    {
        if ( alpha < 1.0 )
        {
            // obviously not opaque
            return;
        }
    }
    else // we are drawing tranparent objects
    {
        if ( !(alpha < 1.0 ) )
        {
            // not transparent
            return;
        }
    }

    QGLShaderProgram* program = GLFunctions::getShader( "tube" );
    program->bind();

    GLFunctions::setupTextures();
    GLFunctions::setTextureUniforms( GLFunctions::getShader( "tube" ), "maingl" );

    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "mv_matrixTI", mv_matrix.transposed().inverted() );

    //glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    initGeometry();

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    setShaderVars( props );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[2] );
    int extraLocation = program->attributeLocation( "a_extra" );
    program->enableAttributeArray( extraLocation );
    glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[3] );
    int indexLocation = program->attributeLocation( "a_indexes" );
    program->enableAttributeArray( indexLocation );
    glVertexAttribPointer( indexLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );

    QVector<bool>*selected = m_selector->getSelection();
    for ( int i = 0; i < m_data->size(); ++i )
    {
        if ( selected->at( i ) )
        {
            program->setUniformValue( "u_color", m_colorField[i].redF(),
                                                   m_colorField[i].greenF(),
                                                   m_colorField[i].blueF(), 1.0 );
            program->setUniformValue( "u_globalColor", m_globalColorField[i].x(),
                                                         m_globalColorField[i].y(),
                                                         m_globalColorField[i].z(), 1.0 );
            glDrawArrays( GL_QUAD_STRIP, m_startIndexes[i]*2, m_pointsPerLine[i]*2 );
        }
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    //glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
}

void TubeRenderer::setupTextures()
{
}

void TubeRenderer::setShaderVars( PropertyGroup* props )
{
    QGLShaderProgram* program = GLFunctions::getShader( "tube" );

    program->bind();

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int numFloats = 7;

    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset );

    offset += sizeof(float) * 3;
    int normalLocation = program->attributeLocation( "a_normal" );
    program->enableAttributeArray( normalLocation );
    glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset );

    offset += sizeof(float) * 3;
    int dirLocation = program->attributeLocation( "a_direction" );
    program->enableAttributeArray( dirLocation );
    glVertexAttribPointer( dirLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset );

    program->setUniformValue( "u_fibGrowth", props->get( Fn::Property::D_FIBER_GROW_LENGTH).toFloat() );
    program->setUniformValue( "u_colorMode", props->get( Fn::Property::D_COLORMODE ).toInt() );
    program->setUniformValue( "u_colormap", props->get( Fn::Property::D_COLORMAP ).toInt() );
    program->setUniformValue( "u_color", 1.0, 0.0, 0.0, 1.0 );
    program->setUniformValue( "u_selectedMin", props->get( Fn::Property::D_SELECTED_MIN ).toFloat() );
    program->setUniformValue( "u_selectedMax", props->get( Fn::Property::D_SELECTED_MAX ).toFloat() );
    program->setUniformValue( "u_lowerThreshold", props->get( Fn::Property::D_LOWER_THRESHOLD ).toFloat() );
    program->setUniformValue( "u_upperThreshold", props->get( Fn::Property::D_UPPER_THRESHOLD ).toFloat() );
    program->setUniformValue( "u_thickness", props->get( Fn::Property::D_FIBER_THICKNESS ).toFloat() / 100.f );
}

void TubeRenderer::initGeometry()
{
    if ( m_isInitialized )
    {
        return;
    }
    qDebug() << "create tube vbo's...";
    int numThreads = GLFunctions::idealThreadCount;

    QVector<TubeRendererThread*> threads;
    // create threads
    for ( int i = 0; i < numThreads; ++i )
    {
        threads.push_back( new TubeRendererThread( m_data, i ) );
    }

    // run threads
    for ( int i = 0; i < numThreads; ++i )
    {
        threads[i]->start();
    }

    // wait for all threads to finish
    for ( int i = 0; i < numThreads; ++i )
    {
        threads[i]->wait();
    }

    QVector<float> verts;
    // combine verts from all threads
    m_globalColorField.clear();
    for ( int i = 0; i < numThreads; ++i )
    {
        verts += *( threads[i]->getVerts() );
        m_globalColorField += *( threads[i]->getGlobalColors() );
    }

    for ( int i = 0; i < numThreads; ++i )
    {
        delete threads[i];
    }

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    glBufferData( GL_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    m_pointsPerLine.resize( m_data->size() );
    m_startIndexes.resize( m_data->size() );

    int currentStart = 0;
    for ( int i = 0; i < m_data->size(); ++i )
    {
        m_pointsPerLine[i] = m_data->at( i ).size() / 3;
        m_startIndexes[i] = currentStart;
        currentStart += m_pointsPerLine[i];
    }

    updateExtraData( m_extraData );

    qDebug() << "create tube vbo's done";

    m_numPoints = verts.size() / 7;

    m_isInitialized = true;
}

void TubeRenderer::colorChanged( QVariant color )
{
    QVector<bool>*selected = m_selector->getSelection();
    for ( int i = 0; i < m_numLines; ++i )
    {
        if ( selected->at( i ) )
        {
            m_colorField.replace( i, color.value<QColor>() );
        }
    }
}

void TubeRenderer::updateExtraData( QVector< QVector< float > >* extraData )
{
    m_extraData = extraData;
    QVector<float>data;
    QVector<float>indexes;
    for ( int i = 0; i < extraData->size(); ++i )
    {
        QVector<float>fib = extraData->at(i);
        for ( int k = 0; k < fib.size(); ++k )
        {
            data.push_back( fib[k]);
            data.push_back( fib[k]);
            indexes.push_back( k );
            indexes.push_back( k );
        }
    }

    glDeleteBuffers( 1, &vboIds[2] );
    glGenBuffers( 1, &vboIds[2] );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[2] );
    glBufferData( GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    glDeleteBuffers( 1, &vboIds[3] );
    glGenBuffers( 1, &vboIds[3] );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[3] );
    glBufferData( GL_ARRAY_BUFFER, indexes.size() * sizeof(GLfloat), indexes.data(), GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
<|endoftext|>


<commit_before>void hsumanim() {
//
// This script is a slightly modified version of hsum.C.
// When run in batch mode, it produces an animated gif file.
//Authors: Rene Brun, Valeriy Onuchin

  c1 = new TCanvas("c1","The HSUM example",200,10,600,400);
  c1->SetGrid();

  gBenchmark->Start("hsum");

// Create some histograms.
  total  = new TH1F("total","This is the total distribution",100,-4,4);
  main   = new TH1F("main","Main contributor",100,-4,4);
  s1     = new TH1F("s1","This is the first signal",100,-4,4);
  s2     = new TH1F("s2","This is the second signal",100,-4,4);
  total->Sumw2();   // this makes sure that the sum of squares of weights will be stored
  total->SetMarkerStyle(21);
  total->SetMarkerSize(0.7);
  main->SetFillColor(16);
  s1->SetFillColor(42);
  s2->SetFillColor(46);
  TSlider *slider = 0;
  gSystem->Unlink("hsumanim.gif"); // delete old file

// Fill histograms randomly
  gRandom->SetSeed();
  const Int_t kUPDATE = 500;
  Float_t xs1, xs2, xmain;
  Int_t gifcnt = 0;
  for ( Int_t i=0; i<10000; i++) {
     xmain = gRandom->Gaus(-1,1.5);
     xs1   = gRandom->Gaus(-0.5,0.5);
     xs2   = gRandom->Landau(1,0.15);
     main->Fill(xmain);
     s1->Fill(xs1,0.3);
     s2->Fill(xs2,0.2);
     total->Fill(xmain);
     total->Fill(xs1,0.3);
     total->Fill(xs2,0.2);
     if (i && (i%kUPDATE) == 0) {
        if (i == kUPDATE) {
           total->Draw("e1p");
           main->Draw("same");
           s1->Draw("same");
           s2->Draw("same");
           c1->Update();
           slider = new TSlider("slider","test",4.2,0,4.6,total->GetMaximum(),38);
           slider->SetFillColor(46);
        }
        if (slider) slider->SetRange(0,Float_t(i)/10000.);
        c1->Modified();
        c1->Update();
        if (gROOT->IsBatch()) {
           c1->Print("hsumanim.gif+");
           printf("i = %d\n", i);
        }
     }
  }
  slider->SetRange(0,1);
  total->Draw("sameaxis"); // to redraw axis hidden by the fill area
  c1->Modified();
  // make infinite animation by adding "++" to the file name
  if (gROOT->IsBatch()) c1->Print("hsumanim.gif++");

  //You can view the animated file hsumanim.gif with Netscape/IE or mozilla

  gBenchmark->Show("hsum");
}
<commit_msg>update histogram in real-time when not in batch mode.<commit_after>void hsumanim() {
//
// This script is a slightly modified version of hsum.C.
// When run in batch mode, it produces an animated gif file.
//Authors: Rene Brun, Valeriy Onuchin

  c1 = new TCanvas("c1","The HSUM example",200,10,600,400);
  c1->SetGrid();

  gBenchmark->Start("hsum");

// Create some histograms.
  total  = new TH1F("total","This is the total distribution",100,-4,4);
  main   = new TH1F("main","Main contributor",100,-4,4);
  s1     = new TH1F("s1","This is the first signal",100,-4,4);
  s2     = new TH1F("s2","This is the second signal",100,-4,4);
  total->Sumw2();   // this makes sure that the sum of squares of weights will be stored
  total->SetMarkerStyle(21);
  total->SetMarkerSize(0.7);
  main->SetFillColor(16);
  s1->SetFillColor(42);
  s2->SetFillColor(46);
  TSlider *slider = 0;
  gSystem->Unlink("hsumanim.gif"); // delete old file

// Fill histograms randomly
  gRandom->SetSeed();
  const Int_t kUPDATE = 500;
  Float_t xs1, xs2, xmain;
  Int_t gifcnt = 0;
  for ( Int_t i=0; i<10000; i++) {
     xmain = gRandom->Gaus(-1,1.5);
     xs1   = gRandom->Gaus(-0.5,0.5);
     xs2   = gRandom->Landau(1,0.15);
     main->Fill(xmain);
     s1->Fill(xs1,0.3);
     s2->Fill(xs2,0.2);
     total->Fill(xmain);
     total->Fill(xs1,0.3);
     total->Fill(xs2,0.2);
     if (i && (i%kUPDATE) == 0) {
        if (i == kUPDATE) {
           total->Draw("e1p");
           main->Draw("same");
           s1->Draw("same");
           s2->Draw("same");
           c1->Update();
           slider = new TSlider("slider","test",4.2,0,4.6,total->GetMaximum(),38);
           slider->SetFillColor(46);
        }
        if (slider) slider->SetRange(0,Float_t(i)/10000.);
        c1->Modified();
        c1->Update();
        if (gROOT->IsBatch()) {
           c1->Print("hsumanim.gif+");
           printf("i = %d\n", i);
        } else {
           if (gSystem->ProcessEvents())
              break;
        }
     }
  }
  slider->SetRange(0,1);
  total->Draw("sameaxis"); // to redraw axis hidden by the fill area
  c1->Modified();
  // make infinite animation by adding "++" to the file name
  if (gROOT->IsBatch()) c1->Print("hsumanim.gif++");

  //You can view the animated file hsumanim.gif with Netscape/IE or mozilla

  gBenchmark->Show("hsum");
}
<|endoftext|>


<commit_before>#include "TPrincipal.h"
#include "iomanip.h"

void principal(Int_t n=10, Int_t m=10000)
{
  //
  // Principal Components Analysis (PCA) example
  //
  // Example of using TPrincipal as a stand alone class.
  //
  // We create n-dimensional data points, where c = trunc(n / 5) + 1
  // are  correlated with the rest n - c randomly distributed variables.
  //
  // Here's the plot of the eigenvalues Begin_Html
  //
  // End_Html
  //Authors: Rene Brun, Christian Holm Christensen

  Int_t c = n / 5 + 1;

  cout << "*************************************************" << endl;
  cout << "*         Principal Component Analysis          *" << endl;
  cout << "*                                               *" << endl;
  cout << "*  Number of variables:           " << setw(4) << n
       << "          *" << endl;
  cout << "*  Number of data points:         " << setw(8) << m
       << "      *" << endl;
  cout << "*  Number of dependent variables: " << setw(4) << c
       << "          *" << endl;
  cout << "*                                               *" << endl;
  cout << "*************************************************" << endl;

  // Initilase the TPrincipal object. Use the empty string for the
  // final argument, if you don't wan't the covariance
  // matrix. Normalising the covariance matrix is a good idea if your
  // variables have different orders of magnitude.
  TPrincipal* principal = new TPrincipal(n,"N");

  // Use a pseudo-random number generator
  TRandom* random = new TRandom;

  // Make the m data-points
  // Make a variable to hold our data
  // Allocate memory for the data point
  Double_t* data = new Double_t[n];
  for (Int_t i = 0; i < m; i++) {

    // First we create the un-correlated, random variables, according
    // to one of three distributions
    for (Int_t j = 0; j < n - c; j++) {
      if (j % 3 == 0)
	data[j] = random->Gaus(5,1);
      else if (j % 3 == 1)
	data[j] = random->Poisson(8);
      else
	data[j] = random->Exp(2);
    }

    // Then we create the correlated variables
    for (Int_t j = 0 ; j < c; j++) {
      data[n - c + j] = 0;
      for (Int_t k = 0; k < n - c - j; k++)
	data[n - c + j] += data[k];
    }

    // Finally we're ready to add this datapoint to the PCA
    principal->AddRow(data);
  }

  // We delete the data after use, since TPrincipal got it by now.
  delete [] data;

  // Do the actual analysis
  principal->MakePrincipals();

  // Print out the result on
  principal->Print();

  // Test the PCA
  principal->Test();

  // Make some histograms of the orginal, principal, residue, etc data
  principal->MakeHistograms();

  // Make two functions to map between feature and pattern space
  principal->MakeCode();

  // Start a browser, so that we may browse the histograms generated
  // above
  TBrowser* b = new TBrowser("principalBrowser", principal);

}
<commit_msg>Use option "D" when calling the TPrincipal constructor. In this way we get all the histograms described in TPrincipal::MakeHistograms.<commit_after>#include "TPrincipal.h"
#include "iomanip.h"

void principal(Int_t n=10, Int_t m=10000)
{
  //
  // Principal Components Analysis (PCA) example
  //
  // Example of using TPrincipal as a stand alone class.
  //
  // We create n-dimensional data points, where c = trunc(n / 5) + 1
  // are  correlated with the rest n - c randomly distributed variables.
  //
  // Here's the plot of the eigenvalues Begin_Html
  //
  // End_Html
  //Authors: Rene Brun, Christian Holm Christensen

  Int_t c = n / 5 + 1;

  cout << "*************************************************" << endl;
  cout << "*         Principal Component Analysis          *" << endl;
  cout << "*                                               *" << endl;
  cout << "*  Number of variables:           " << setw(4) << n
       << "          *" << endl;
  cout << "*  Number of data points:         " << setw(8) << m
       << "      *" << endl;
  cout << "*  Number of dependent variables: " << setw(4) << c
       << "          *" << endl;
  cout << "*                                               *" << endl;
  cout << "*************************************************" << endl;

  // Initilase the TPrincipal object. Use the empty string for the
  // final argument, if you don't wan't the covariance
  // matrix. Normalising the covariance matrix is a good idea if your
  // variables have different orders of magnitude.
  TPrincipal* principal = new TPrincipal(n,"ND");

  // Use a pseudo-random number generator
  TRandom* random = new TRandom;

  // Make the m data-points
  // Make a variable to hold our data
  // Allocate memory for the data point
  Double_t* data = new Double_t[n];
  for (Int_t i = 0; i < m; i++) {

    // First we create the un-correlated, random variables, according
    // to one of three distributions
    for (Int_t j = 0; j < n - c; j++) {
      if (j % 3 == 0)
	data[j] = random->Gaus(5,1);
      else if (j % 3 == 1)
	data[j] = random->Poisson(8);
      else
	data[j] = random->Exp(2);
    }

    // Then we create the correlated variables
    for (Int_t j = 0 ; j < c; j++) {
      data[n - c + j] = 0;
      for (Int_t k = 0; k < n - c - j; k++)
	data[n - c + j] += data[k];
    }

    // Finally we're ready to add this datapoint to the PCA
    principal->AddRow(data);
  }

  // We delete the data after use, since TPrincipal got it by now.
  delete [] data;

  // Do the actual analysis
  principal->MakePrincipals();

  // Print out the result on
  principal->Print();

  // Test the PCA
  principal->Test();

  // Make some histograms of the orginal, principal, residue, etc data
  principal->MakeHistograms();

  // Make two functions to map between feature and pattern space
  principal->MakeCode();

  // Start a browser, so that we may browse the histograms generated
  // above
  TBrowser* b = new TBrowser("principalBrowser", principal);

}
<|endoftext|>


<commit_before>#include <sstream>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>
#include <cstdlib>
#include <sys/wait.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

vector<string> inputs_G;
vector<string> outputs_G;
vector<string> output_append_G;
void fixing_spacing_command(char *org_prompt, int check_redir)
{
    char *fin_prompt = (char*)malloc(50000);
    char connect[4];
    connect[0] = ';';
    connect[1] = '&';
    connect[2] = '|';
    connect[3] = '#';
    connect[4] = '>';
    //x is passed in prompt
    //i is finished prompt after changing spaces
    for(int x = 0,i = 0; org_prompt[x] != '\0'; x++, i++)
    {
        if(org_prompt[x] == connect[3])
        {
            org_prompt[x] = '\0';
            fin_prompt[i] = '\0';
        }
        else if(org_prompt[x] == connect[0])
        {
            fin_prompt[i] = ' ';
            fin_prompt[++i] = ';';
            fin_prompt[++i] = ' ';
        }
        else if(org_prompt[x] == connect[1] && org_prompt[x + 1] == connect[1])
        {
            fin_prompt[i] = ' ';
            fin_prompt[++i] = '&';
            fin_prompt[++i] = '&';
            fin_prompt[++i] = ' ';
            ++x;
        }
        else if(org_prompt[x] == connect[3] && org_prompt[x + 1] == connect[3])
        {
            fin_prompt[i] = ' ';
            fin_prompt[++i] = '|';
            fin_prompt[++i] = '|';
            fin_prompt[++i] = ' ';
            ++x;
        }
        else if(org_prompt[x] == connect[4])
        {
            check_redir = 1;        //redir 1 means one output bracket
            fin_prompt[i] = ';';
            fin_prompt[++i] = ' ';
            fin_prompt[++i] = ' ';
            fin_prompt[++i] = ' ';
            ++x;
        }
        else
        {
            fin_prompt[i] = org_prompt[x];
        }
        if(org_prompt[x + 1] == '\0') fin_prompt[i + 1] = '\0';
    }
      strcpy(org_prompt, fin_prompt);        //copies altered version
}
int exec_status;
bool str_continue = true;
bool execute(char* command, char* command_list[], int conect_type, bool redir, string path_name)
{
    int status;
    int process_ID = fork();
    if(process_ID <= -1)
    {
        perror("Error occured during forking()");
        exit(1);
    }
    else if(process_ID == 0) //child process
    {
        if(redir)
        {
            cout << "does this enter" << endl;
            if(outputs_G.size() > 0)
            {
                //cout << "is this going in here" << endl;
                int fd;
                for(int x = 0; x < outputs_G.size(); x++)
                {
                    if(fd = (open(outputs_G.at(outputs_G.size() -1 - x).c_str(), O_RDWR | O_CREAT | O_TRUNC, 0744) == -1))
                    {
                        perror("open");
                    }
                }
                if(close(1) == -1)
                {
                    perror("close");
                }
                if(dup(fd) == -1)
                {
                    perror("dup");
                }
            }
            if(output_append_G.size() > 0)
            {
                cout << "does this enteir" << endl;
                if(close(1) == -1)
                {
                    perror("close");
                }
                int fd;
                for(int x = 0; x < output_append_G.size(); x++)
                {
                    cout << "outupt this stuff: " << output_append_G.at(output_append_G.size() - 1 - x) << endl;
                    if(fd = (open(output_append_G.at(output_append_G.size() -1 - x).c_str(), O_RDWR | O_CREAT | O_APPEND, 0744) == -1))
                    {
                        perror("open");
                    }
                }
            }
            if(inputs_G.size() > 0)
            {
                cout << "does this mess it up" << endl;
                int fd;
                for(int x = 0; x < inputs_G.size(); x++)
                {
                    if((fd = open(inputs_G.at(inputs_G.size() -1 - x).c_str(), O_RDONLY)) == -1)
                    {
                        perror("open");
                    }
                    if(close(0) == -1)
                    {
                        perror("close");
                    }
                    if(dup(fd) == -1)
                    {
                        perror("dup");
                    }
                }
            }
            exec_status = (execvp(command, command_list));
            cout << "output exec status////////////////: " << exec_status << endl;
            if(exec_status == -1)
            {
                perror("error with passed in argument list");
                return exec_status;
                exit(1);
            }

        }
        else
        {
            cout << "is this going in there" << endl;
            exec_status = (execvp(command, command_list));
            if(exec_status == -1)
            {
                perror("error with passed in argument list");
                return exec_status;
                exit(1);
            }
        }
    }
    else if(process_ID > 0) //parent process
    {
        if(waitpid(process_ID, &status,0) == -1)
        {
            perror("error with waitpid()");
        }
    }
    return(!(status == 0 && conect_type == -1) ||( status > 0 && conect_type == 2));
}

int check_connections(char* check)
{
    if(!strcmp(check, ";")) return 0;
    else if(!strcmp(check, "||")) return 1;
    else if(!strcmp(check, "&&")) return 2;
    else if(!strcmp(check, ">")) return 3;
    else return -1;
}
void check_exit(char *str)
{
    if(!strcmp(str, "exit"))
    {
        exit(0);
    }
}
string input_hold;
string out_hold;
string add_hold;
void check_redirection(string &s)
{
    for(int x = 0; x < s.size(); x++)
    {
        if(s.at(x) == '<' && x < s.size())
        {
            int g = x;
            if(g++ < s.size())
            {
                for(; s.at(g) != '>' && g < s.size(); g++)
                {
                    input_hold.push_back(s.at(g));
                }
            }
            inputs_G.push_back(input_hold);
            input_hold.clear();
        }
        if(s.at(x) == '>')
        {
            if(s.at(x + 1) == '>' && x < s.size())
            {
                cout << "is thsi workign t" << endl;
                s.at(x) = ' ';
                int i = x;
                i++;
                cout << "is this shit working" << endl;
                for(; i < s.size() && s.at(i) != '>' && s.at(i + 1) != '>'; i++)
                {
                    cout << s.at(i) << endl;
                    add_hold.push_back(s.at(i));
                    s.at(i) = ' ';
                }
                output_append_G.push_back(add_hold);
                out_hold.clear();
            }
            else
            {
                s.at(x) = ' ';
                int i = x;
                i++;
                for(; i < s.size() && s.at(i) != '>'; i++)
                {
                    out_hold.push_back(s.at(i));
                    s.at(i) = ' ';
                }
                outputs_G.push_back(out_hold);
                out_hold.clear();
            }
        }
    }
}
string final_file_name;
string fix_file_name(string s)
{
    final_file_name.clear();
    int sz = s.size();
    for(int x = 0; x < sz; x++)
    {
        if(s.at(x) != ' ')
        {
            final_file_name.push_back(s.at(x));
        }
    }
    return final_file_name;
}

bool redir_exist(string s)
{
    for(int x = 0; x < s.size(); x++)
    {
        if(s.at(x) == '>' || s.at(x) == '<')
        {
            return true;
        }
    }
}
int main(int argc, char **argv)
{
    outputs_G.clear();
    inputs_G.clear();
    int multi_redir_chk = 0;
    int check_redir = 0;
    ///////////////////////////////////////////////
    int sequence = 0; //sequence of which is executable and flags
    char* host = (char*)malloc(500);
    string userinfo;
    bool prompter = true;
    char* token; //will be bit of code strtok cuts off
    bool exec_result = true;
    //error checks the user
    if(getlogin() != NULL)
    {
        userinfo = getlogin();
    }
    else
    {
        perror("error getting user info");
    }
    if(gethostname(host, 500) == -1)
    {
        perror("Error getting host name");
    }
    //outputs the userinfo with login and host
    while(prompter)
    {
        inputs_G.clear();
        outputs_G.clear();
        //~ for(int x = 0; x < inputs_G.size(); x++)
        //~ {
            //~ inputs_G.at(x) = "";
        //~ }
        //~ for(int x = 0; x < outputs_G.size(); x++)
        //~ {
            //~ outputs_G.at(x) = "";
        //~ }
        cout << userinfo << "@" << host << " $ ";
        //////////////////////////////////////////////login part done, next is all shell commands
        char prompt_holder[50000];//orginal array to hold prompt
        char *comd_arr[50000];
        for(int x = 0; x < 50001; x++)
        {
            prompt_holder[x] = 0;
            comd_arr[x] = 0;
        }
        unsigned int comd_arr_cnt = 0;
        str_continue = true;
        //string converter; //converts all bits of string into one piece
        string to_be_tokenized;
        getline(cin, to_be_tokenized);
        bool redir_checker = redir_exist(to_be_tokenized);
        check_redirection(to_be_tokenized);
        if(redir_checker)
        {
            for(int x = 0; x < inputs_G.size(); x++)
            {
                string s = fix_file_name(inputs_G.at(x));
                inputs_G.at(x) = s;
                s.clear();
            }
            for(int x = 0; x < outputs_G.size(); x++)
            {
                string s = fix_file_name(outputs_G.at(x));
                outputs_G.at(x) = s;
                s.clear();
            }
            for(int x = 0; x < output_append_G.size(); x++)
            {
                string s = fix_file_name(outputs_G.at(x));
                output_append_G.at(x) = s;
                s.clear();
            }

        }

        cout << "after string: " << to_be_tokenized << endl;

        for(int x = 0; x < inputs_G.size(); x++)
        {
            cout << "first: " << inputs_G.at(x) << endl;
        }
        for(int x = 0; x < output_append_G.size(); x++)
        {
            cout << "second: " << output_append_G.at(x) << endl;
        }

        //cout << "after string: " << to_be_tokenized << endl;

        for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
        {
            prompt_holder[x] = to_be_tokenized.at(x);
        }
        fixing_spacing_command(prompt_holder, check_redir);
        int connect_check; //indicates which connection is in token
        token = strtok(prompt_holder, "\t ");
        //cout << "output token: " << token << endl;
        exec_result = true;
        while(token != NULL && exec_result && str_continue)
        {
            connect_check = check_connections(token);
            check_exit(token);
            if(connect_check == -1 && sequence < 1 && str_continue)
            {
                //cout << "does this come out on top" << endl;
                check_exit(token);
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;
                sequence++; //increment only once to see which is executable
            }
            else if(sequence > 0 && connect_check == -1 && str_continue)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;
            }
            else if(connect_check != -1)
            {
                check_exit(token);
                comd_arr[comd_arr_cnt] = '\0' ;
                sequence = 0;
                comd_arr_cnt = 0;
                //cout << "does it output second iteration " << endl;
                exec_result = execute(comd_arr[0], comd_arr, connect_check, redir_checker,final_file_name);
                //cout << "output exec_status: " << exec_status << endl;
                //cout << "output exec_result tho: " << exec_result << endl;
                //cout << "connect_check: " << connect_check << endl;
                //cout << "str_continue: " << str_continue << endl;
                if(exec_status == 0)
                {
                    if(connect_check == 2)
                    {
                        str_continue = false;
                        //cout << "str_continue: " << str_continue << endl;
                    }
                    if(connect_check == 1)
                    {
                        str_continue = false;
                    }
                }
                if(exec_result == 1)
                {
                    if(connect_check == 2)
                    {
                        str_continue = true;
                    }
                }

            }
            token = strtok(NULL, "\t ");
            if(connect_check == -1 && token == NULL && exec_result && str_continue)
            {
            //cout << "guess this executeisw ith this " << endl;
            comd_arr[comd_arr_cnt] = '\0';
            execute(comd_arr[0], comd_arr, connect_check, redir_checker,final_file_name);
            }
        }

    }
}
<commit_msg> got redir working finally<commit_after>#include <sstream>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>
#include <cstdlib>
#include <sys/wait.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

vector<string> inputs_G;
vector<string> outputs_G;
vector<string> output_append_G;
void fixing_spacing_command(char *org_prompt, int check_redir)
{
    char *fin_prompt = (char*)malloc(50000);
    char connect[4];
    connect[0] = ';';
    connect[1] = '&';
    connect[2] = '|';
    connect[3] = '#';
    connect[4] = '>';
    //x is passed in prompt
    //i is finished prompt after changing spaces
    for(int x = 0,i = 0; org_prompt[x] != '\0'; x++, i++)
    {
        if(org_prompt[x] == connect[3])
        {
            org_prompt[x] = '\0';
            fin_prompt[i] = '\0';
        }
        else if(org_prompt[x] == connect[0])
        {
            fin_prompt[i] = ' ';
            fin_prompt[++i] = ';';
            fin_prompt[++i] = ' ';
        }
        else if(org_prompt[x] == connect[1] && org_prompt[x + 1] == connect[1])
        {
            fin_prompt[i] = ' ';
            fin_prompt[++i] = '&';
            fin_prompt[++i] = '&';
            fin_prompt[++i] = ' ';
            ++x;
        }
        else if(org_prompt[x] == connect[3] && org_prompt[x + 1] == connect[3])
        {
            fin_prompt[i] = ' ';
            fin_prompt[++i] = '|';
            fin_prompt[++i] = '|';
            fin_prompt[++i] = ' ';
            ++x;
        }
        else if(org_prompt[x] == connect[4])
        {
            check_redir = 1;        //redir 1 means one output bracket
            fin_prompt[i] = ';';
            fin_prompt[++i] = ' ';
            fin_prompt[++i] = ' ';
            fin_prompt[++i] = ' ';
            ++x;
        }
        else
        {
            fin_prompt[i] = org_prompt[x];
        }
        if(org_prompt[x + 1] == '\0') fin_prompt[i + 1] = '\0';
    }
      strcpy(org_prompt, fin_prompt);        //copies altered version
}
bool in = false;
bool out = false;
bool add_out = false;
int exec_status;
bool str_continue = true;
bool execute(char* command, char* command_list[], int conect_type, bool redir, string path_name)
{
    int status;
    int process_ID = fork();
    if(process_ID <= -1)
    {
        perror("Error occured during forking()");
        exit(1);
    }
    else if(process_ID == 0) //child process
    {
        if(redir)
        {
            if(output_append_G.size() > 0 && add_out)
            {
                cout << "does this enteir" << endl;
                if(close(1) == -1)
                {
                    perror("close");
                }
                int fd;
                cout << "show appendation size: " << output_append_G.size() << endl;
                for(int x = 0; x < output_append_G.size(); x++)
                {
                    cout << "outupt this stuff: " << output_append_G.at(output_append_G.size() - 1 - x) << endl;
                    if(fd = (open(output_append_G.at(output_append_G.size() -1 - x).c_str(), O_APPEND | O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR) == -1))
                    {
                        perror("open");
                    }
                }
            }
            cout << "does this enter" << endl;
            if(outputs_G.size() > 0 && out)
            {
                cout << "is this going in here" << endl;
                if(close(1) == -1)
                {
                    perror("close");
                }
                cout << "is this going in here" << endl;
                int fd;
                for(int x = 0; x < outputs_G.size(); x++)
                {
                    if(fd = (open(outputs_G.at(outputs_G.size() -1 - x).c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR) == -1))
                    {
                        perror("open");
                    }
                }
            }
            if(inputs_G.size() > 0 && in)
            {
                cout << "does this enter here" << endl;
                if(close(0) == -1)
                {
                    perror("close");
                }
                cout << "does this mess it up" << endl;
                int fd;
                for(int x = 0; x < inputs_G.size(); x++)
                {
                    if((fd = open(inputs_G.at(inputs_G.size() -1 - x).c_str(), O_RDONLY)) == -1)
                    {
                        perror("open");
                    }
                }
            }
            cout << "output right before exec " << endl;
            exec_status = (execvp(command, command_list));
            cout << "output exec status////////////////: " << exec_status << endl;
            if(exec_status == -1)
            {
                perror("error with passed in argument list");
                return exec_status;
                exit(1);
            }

        }
        else
        {
            cout << "is this going in there" << endl;
            exec_status = (execvp(command, command_list));
            if(exec_status == -1)
            {
                perror("error with passed in argument list");
                return exec_status;
                exit(1);
            }
        }
    }
    else if(process_ID > 0) //parent process
    {
        if(waitpid(process_ID, &status,0) == -1)
        {
            perror("error with waitpid()");
        }
    }
    return(!(status == 0 && conect_type == -1) ||( status > 0 && conect_type == 2));
}

int check_connections(char* check)
{
    if(!strcmp(check, ";")) return 0;
    else if(!strcmp(check, "||")) return 1;
    else if(!strcmp(check, "&&")) return 2;
    else if(!strcmp(check, ">")) return 3;
    else return -1;
}
void check_exit(char *str)
{
    if(!strcmp(str, "exit"))
    {
        exit(0);
    }
}
string input_hold;
string out_hold;
string add_hold;
void check_redirection(string &s)
{
    input_hold.clear();
    out_hold.clear();
    add_hold.clear();
    for(int x = 0; x < s.size(); x++)
    {
        if(s.at(x) == '<' && x < s.size())
        {
            s.at(x) = ' ';
            int g = x;
            if(g++ < s.size())
            {
                for(; g < s.size() && s.at(g) != '>'; g++)
                {
                    input_hold.push_back(s.at(g));
                }
            }
            in = true;
            inputs_G.push_back(input_hold);
        }
        if(s.at(x) == '>')
        {
            if(s.at(x + 1) == '>' && x +1 < s.size())
            {
                cout << "is thsi workign t" << endl;
                s.at(x) = ' ';
                s.at(x + 1) = ' ';
                x+=2;
                int i = x;
                i++;
                cout << "is this shit working" << endl;
                cout << "s.at(i): " << s.at(i) << endl;
                for(; i < s.size() && s.at(i) != '>'; i++)
                {
                    cout << s.at(i) << endl;
                    add_hold.push_back(s.at(i));
                    s.at(i) = ' ';
                }
                cout << "add_hold: " << add_hold << endl;
                output_append_G.push_back(add_hold);
                cout << "first vecto space: " << output_append_G.at(0) << endl;
                add_hold.clear();
                add_out = true;
            }
            else if(s.at(x + 1) != '>')
            {
                cout << "string shows: " << s.at(x + 1) << endl;
                cout << "strings: " << s << endl;
                cout << "why are u mesing with me" << endl;
                s.at(x) = ' ';
                int i = x;
                i++;
                for(; i < s.size() && s.at(i) != '>'; i++)
                {
                    out_hold.push_back(s.at(i));
                    s.at(i) = ' ';
                }
                outputs_G.push_back(out_hold);
                out_hold.clear();
                out = true;
                cout << "check boolean: " << out << endl;
            }
        }
    }
}
string final_file_name;
string fix_file_name(string s)
{
    final_file_name.clear();
    int sz = s.size();
    for(int x = 0; x < sz; x++)
    {
        if(s.at(x) != ' ')
        {
            final_file_name.push_back(s.at(x));
        }
    }
    return final_file_name;
}

bool redir_exist(string s)
{
    for(int x = 0; x < s.size(); x++)
    {
        if(s.at(x) == '>' || s.at(x) == '<')
        {
            return true;
        }
    }
}
int main(int argc, char **argv)
{
    outputs_G.clear();
    inputs_G.clear();
    int multi_redir_chk = 0;
    int check_redir = 0;
    ///////////////////////////////////////////////
    int sequence = 0; //sequence of which is executable and flags
    char* host = (char*)malloc(500);
    string userinfo;
    bool prompter = true;
    char* token; //will be bit of code strtok cuts off
    bool exec_result = true;
    //error checks the user
    if(getlogin() != NULL)
    {
        userinfo = getlogin();
    }
    else
    {
        perror("error getting user info");
    }
    if(gethostname(host, 500) == -1)
    {
        perror("Error getting host name");
    }
    //outputs the userinfo with login and host
    while(prompter)
    {
        in = false;
        out = false;
        add_out = false;
        inputs_G.clear();
        outputs_G.clear();
        cout << userinfo << "@" << host << " $ ";
        //////////////////////////////////////////////login part done, next is all shell commands
        char prompt_holder[50000];//orginal array to hold prompt
        char *comd_arr[50000];
        for(int x = 0; x < 50001; x++)
        {
            prompt_holder[x] = 0;
            comd_arr[x] = 0;
        }
        unsigned int comd_arr_cnt = 0;
        str_continue = true;
        //string converter; //converts all bits of string into one piece
        string to_be_tokenized;
        getline(cin, to_be_tokenized);
        bool redir_checker = redir_exist(to_be_tokenized);
        check_redirection(to_be_tokenized);
        cout << "checkfasdfasdfboolean: " << add_out << endl;
        cout << "checkfasdfasdfboolean: " << out << endl;
        if(redir_checker)
        {
            for(int x = 0; x < inputs_G.size(); x++)
            {
                string s = fix_file_name(inputs_G.at(x));
                inputs_G.at(x) = s;
                s.clear();
            }
            for(int x = 0; x < outputs_G.size(); x++)
            {
                string s = fix_file_name(outputs_G.at(x));
                outputs_G.at(x) = s;
                s.clear();
            }
            cout << "outputssize: " << output_append_G.size() << endl;
            for(int x = 0; x < output_append_G.size(); x++)
            {
                string s = fix_file_name(output_append_G.at(x));
                output_append_G.at(x) = s;
            }

        }

        cout << "after string: " << to_be_tokenized << endl;

        for(int x = 0; x < inputs_G.size(); x++)
        {
            cout << "first: " << inputs_G.at(x) << endl;
        }
        for(int x = 0; x < output_append_G.size(); x++)
        {
            cout << "output_append: " << output_append_G.at(x) << endl;
        }

        //cout << "after string: " << to_be_tokenized << endl;

        for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
        {
            prompt_holder[x] = to_be_tokenized.at(x);
        }
        fixing_spacing_command(prompt_holder, check_redir);
        int connect_check; //indicates which connection is in token
        token = strtok(prompt_holder, "\t ");
        //cout << "output token: " << token << endl;
        exec_result = true;
        while(token != NULL && exec_result && str_continue)
        {
            connect_check = check_connections(token);
            check_exit(token);
            if(connect_check == -1 && sequence < 1 && str_continue)
            {
                //cout << "does this come out on top" << endl;
                check_exit(token);
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;
                sequence++; //increment only once to see which is executable
            }
            else if(sequence > 0 && connect_check == -1 && str_continue)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;
            }
            else if(connect_check != -1)
            {
                check_exit(token);
                comd_arr[comd_arr_cnt] = '\0' ;
                sequence = 0;
                comd_arr_cnt = 0;
                exec_result = execute(comd_arr[0], comd_arr, connect_check, redir_checker,final_file_name);
                if(exec_status == 0)
                {
                    if(connect_check == 2)
                    {
                        str_continue = false;
                        //cout << "str_continue: " << str_continue << endl;
                    }
                    if(connect_check == 1)
                    {
                        str_continue = false;
                    }
                }
                if(exec_result == 1)
                {
                    if(connect_check == 2)
                    {
                        str_continue = true;
                    }
                }

            }
            token = strtok(NULL, "\t ");
            if(connect_check == -1 && token == NULL && exec_result && str_continue)
            {
            //cout << "guess this executeisw ith this " << endl;
            comd_arr[comd_arr_cnt] = '\0';
            execute(comd_arr[0], comd_arr, connect_check, redir_checker,final_file_name);
            }
        }

    }
}
<|endoftext|>


<commit_before>{
   Int_t nx = hpxpy->GetXaxis()->GetNbins();
   Int_t ny = hpxpy->GetYaxis()->GetNbins();
   Int_t binxmin = nx*xslider->GetMinimum();
   Int_t binxmax = nx*xslider->GetMaximum();
   hpxpy->GetXaxis()->SetRange(binxmin,binxmax);
   Int_t binymin = ny*yslider->GetMinimum();
   Int_t binymax = ny*yslider->GetMaximum();
   hpxpy->GetYaxis()->SetRange(binymin,binymax);
   pad->cd();
   hpxpy->Draw("lego1");
   c1->Update();
}
<commit_msg>Minor change in the script to call pad->Modified() instead of redrawing the original histogram.<commit_after>{
   Int_t nx = hpxpy->GetXaxis()->GetNbins();
   Int_t ny = hpxpy->GetYaxis()->GetNbins();
   Int_t binxmin = nx*xslider->GetMinimum();
   Int_t binxmax = nx*xslider->GetMaximum();
   hpxpy->GetXaxis()->SetRange(binxmin,binxmax);
   Int_t binymin = ny*yslider->GetMinimum();
   Int_t binymax = ny*yslider->GetMaximum();
   hpxpy->GetYaxis()->SetRange(binymin,binymax);
   pad->cd();
   pad->Modified();
   //hpxpy->Draw(hpxpy->GetDrawOption());
   c1->Update();
}
<|endoftext|>


<commit_before>#include "engine.h"
#include "random.h"
#include "gameEntity.h"
#include "Updatable.h"
#include "collisionable.h"

#ifdef DEBUG
#include <typeinfo>
int DEBUG_PobjCount;
PObject* DEBUG_PobjListStart;
#endif

#ifdef ENABLE_CRASH_LOGGER
#ifdef _WIN32
//Exception handler for mingw, from https://github.com/jrfonseca/drmingw
#include <exchndl.h>
#endif//_WIN32
#endif//ENABLE_CRASH_LOGGER

Engine* engine;

Engine::Engine()
{
    engine = this;
#ifdef ENABLE_CRASH_LOGGER
#ifdef _WIN32
    ExcHndlInit();
#endif//_WIN32
#endif//ENABLE_CRASH_LOGGER
    initRandom();
    windowManager = nullptr;
    CollisionManager::initialize();
    InputHandler::initialize();
    gameSpeed = 1.0;
    running = true;
    elapsedTime = 0.0;

    soundManager = new SoundManager();
}
Engine::~Engine()
{
    if (windowManager)
        windowManager->close();
    delete soundManager;
    soundManager = nullptr;
}

void Engine::registerObject(string name, P<PObject> obj)
{
    objectMap[name] = obj;
}

P<PObject> Engine::getObject(string name)
{
    if (!objectMap[name])
        return NULL;
    return objectMap[name];
}

void Engine::runMainLoop()
{
    windowManager = dynamic_cast<WindowManager*>(*getObject("windowManager"));
    if (!windowManager)
    {
        sf::Clock frameTimeClock;
        while(running)
        {
            float delta = frameTimeClock.getElapsedTime().asSeconds();
            frameTimeClock.restart();
            if (delta > 0.5)
                delta = 0.5;
            if (delta < 0.001)
                delta = 0.001;
            delta *= gameSpeed;

            entityList.update();
            foreach(Updatable, u, updatableList)
                u->update(delta);
            elapsedTime += delta;
            CollisionManager::handleCollisions(delta);
            ScriptObject::clearDestroyedObjects();
            soundManager->updateTick();

            sf::sleep(sf::seconds(1.0/60.0 - delta));
            //if (elapsedTime > 2.0)
            //    break;
        }
    }else{
        sf::Clock frameTimeClock;
#ifdef DEBUG
        sf::Clock debugOutputClock;
#endif
        while(running && windowManager->window.isOpen())
        {
            InputHandler::preEventsUpdate();
            // Handle events
            sf::Event event;
            while (windowManager->window.pollEvent(event))
            {
                handleEvent(event);
            }
            InputHandler::postEventsUpdate();

#ifdef DEBUG
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) && windowManager->hasFocus())
                running = false;

            if (debugOutputClock.getElapsedTime().asSeconds() > 1.0)
            {
                printf("Object count: %4d %4zd %4zd\n", DEBUG_PobjCount, updatableList.size(), entityList.size());
                debugOutputClock.restart();
            }
#endif

            float delta = frameTimeClock.restart().asSeconds();
            if (delta > 0.5)
                delta = 0.5;
            if (delta < 0.001)
                delta = 0.001;
            delta *= gameSpeed;
#ifdef DEBUG
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab))
                delta /= 5.0;
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde))
                delta *= 5.0;
#endif
            EngineTiming engine_timing;

            sf::Clock engine_timing_clock;
            entityList.update();
            foreach(Updatable, u, updatableList)
                u->update(delta);
            elapsedTime += delta;
            engine_timing.update = engine_timing_clock.restart().asSeconds();
            CollisionManager::handleCollisions(delta);
            engine_timing.collision = engine_timing_clock.restart().asSeconds();
            ScriptObject::clearDestroyedObjects();
            soundManager->updateTick();

            // Clear the window
            windowManager->render();
            engine_timing.render = engine_timing_clock.restart().asSeconds();
            engine_timing.server_update = 0.0f;
            if (game_server)
                engine_timing.server_update = game_server->getUpdateTime();

            last_engine_timing = engine_timing;
        }
        soundManager->stopMusic();
    }
}

void Engine::handleEvent(sf::Event& event)
{
    // Window closed: exit
    if (event.type == sf::Event::Closed)
        running = false;
    if (event.type == sf::Event::GainedFocus)
        windowManager->windowHasFocus = true;
    if (event.type == sf::Event::LostFocus)
        windowManager->windowHasFocus = false;
#ifdef DEBUG
    if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::L))
    {
        int n = 0;
        printf("------------------------\n");
        std::unordered_map<string,int> totals;
        for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext)
        {
            printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name());
            if (!obj->isDestroyed())
            {
                totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1;
            }
        }
        printf("--non-destroyed totals--\n");
        int grand_total=0;
        for (auto entry : totals)
        {
            printf("%4d %s\n", entry.second, entry.first.c_str());
            grand_total+=entry.second;
        }
        printf("%4d %s\n",grand_total,"All PObjects");
        printf("------------------------\n");
    }
#endif
    InputHandler::handleEvent(event);
    if (event.type == sf::Event::Resized)
        windowManager->setupView();
#ifdef __ANDROID__
    //Focus lost and focus gained events are used when the application window is created and destroyed.
    if (event.type == sf::Event::LostFocus)
        running = false;

    //The MouseEntered and MouseLeft events are received when the activity needs to pause or resume.
    if (event.type == sf::Event::MouseLeft)
    {
        //Pause is when a small popup is on top of the window. So keep running.
        while(windowManager->window.isOpen() && windowManager->window.waitEvent(event))
        {
            if (event.type != sf::Event::MouseLeft)
                handleEvent(event);
            if (event.type == sf::Event::MouseEntered)
                break;
        }
    }
#endif//__ANDROID__
}

void Engine::setGameSpeed(float speed)
{
    gameSpeed = speed;
}

float Engine::getGameSpeed()
{
    return gameSpeed;
}

float Engine::getElapsedTime()
{
    return elapsedTime;
}

Engine::EngineTiming Engine::getEngineTiming()
{
    return last_engine_timing;
}

void Engine::shutdown()
{
    running = false;
}
<commit_msg>Dynamically loading Dr MinGW (#69)<commit_after>#include "engine.h"
#include "random.h"
#include "gameEntity.h"
#include "Updatable.h"
#include "collisionable.h"

#ifdef DEBUG
#include <typeinfo>
int DEBUG_PobjCount;
PObject* DEBUG_PobjListStart;
#endif

#ifdef WIN32
#include <windows.h>

namespace
{
    HINSTANCE exchndl = nullptr;
}
#endif

Engine* engine;

Engine::Engine()
{
    engine = this;

#ifdef WIN32
    // Setup crash reporter (Dr. MinGW) if available.
    exchndl = LoadLibrary(TEXT("exchndl.dll"));

    if (exchndl)
    {
        auto pfnExcHndlInit = GetProcAddress(exchndl, "ExcHndlInit");

        if (pfnExcHndlInit)
        {
            pfnExcHndlInit();
            LOG(INFO) << "Crash Reporter ON";
        }
        else
        {
            LOG(WARNING) << "Failed to initialize Crash Reporter";
            FreeLibrary(exchndl);
            exchndl = nullptr;
        }
    }
#endif // WIN32

    initRandom();
    windowManager = nullptr;
    CollisionManager::initialize();
    InputHandler::initialize();
    gameSpeed = 1.0;
    running = true;
    elapsedTime = 0.0;
    soundManager = new SoundManager();
}
Engine::~Engine()
{
    if (windowManager)
        windowManager->close();
    delete soundManager;
    soundManager = nullptr;

#ifdef WIN32
    if (exchndl)
    {
        FreeLibrary(exchndl);
        exchndl = nullptr;
    }
#endif // WIN32
}

void Engine::registerObject(string name, P<PObject> obj)
{
    objectMap[name] = obj;
}

P<PObject> Engine::getObject(string name)
{
    if (!objectMap[name])
        return NULL;
    return objectMap[name];
}

void Engine::runMainLoop()
{
    windowManager = dynamic_cast<WindowManager*>(*getObject("windowManager"));
    if (!windowManager)
    {
        sf::Clock frameTimeClock;
        while(running)
        {
            float delta = frameTimeClock.getElapsedTime().asSeconds();
            frameTimeClock.restart();
            if (delta > 0.5)
                delta = 0.5;
            if (delta < 0.001)
                delta = 0.001;
            delta *= gameSpeed;

            entityList.update();
            foreach(Updatable, u, updatableList)
                u->update(delta);
            elapsedTime += delta;
            CollisionManager::handleCollisions(delta);
            ScriptObject::clearDestroyedObjects();
            soundManager->updateTick();

            sf::sleep(sf::seconds(1.0/60.0 - delta));
            //if (elapsedTime > 2.0)
            //    break;
        }
    }else{
        sf::Clock frameTimeClock;
#ifdef DEBUG
        sf::Clock debugOutputClock;
#endif
        while(running && windowManager->window.isOpen())
        {
            InputHandler::preEventsUpdate();
            // Handle events
            sf::Event event;
            while (windowManager->window.pollEvent(event))
            {
                handleEvent(event);
            }
            InputHandler::postEventsUpdate();

#ifdef DEBUG
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) && windowManager->hasFocus())
                running = false;

            if (debugOutputClock.getElapsedTime().asSeconds() > 1.0)
            {
                printf("Object count: %4d %4zd %4zd\n", DEBUG_PobjCount, updatableList.size(), entityList.size());
                debugOutputClock.restart();
            }
#endif

            float delta = frameTimeClock.restart().asSeconds();
            if (delta > 0.5)
                delta = 0.5;
            if (delta < 0.001)
                delta = 0.001;
            delta *= gameSpeed;
#ifdef DEBUG
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab))
                delta /= 5.0;
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde))
                delta *= 5.0;
#endif
            EngineTiming engine_timing;

            sf::Clock engine_timing_clock;
            entityList.update();
            foreach(Updatable, u, updatableList)
                u->update(delta);
            elapsedTime += delta;
            engine_timing.update = engine_timing_clock.restart().asSeconds();
            CollisionManager::handleCollisions(delta);
            engine_timing.collision = engine_timing_clock.restart().asSeconds();
            ScriptObject::clearDestroyedObjects();
            soundManager->updateTick();

            // Clear the window
            windowManager->render();
            engine_timing.render = engine_timing_clock.restart().asSeconds();
            engine_timing.server_update = 0.0f;
            if (game_server)
                engine_timing.server_update = game_server->getUpdateTime();

            last_engine_timing = engine_timing;
        }
        soundManager->stopMusic();
    }
}

void Engine::handleEvent(sf::Event& event)
{
    // Window closed: exit
    if (event.type == sf::Event::Closed)
        running = false;
    if (event.type == sf::Event::GainedFocus)
        windowManager->windowHasFocus = true;
    if (event.type == sf::Event::LostFocus)
        windowManager->windowHasFocus = false;
#ifdef DEBUG
    if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::L))
    {
        int n = 0;
        printf("------------------------\n");
        std::unordered_map<string,int> totals;
        for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext)
        {
            printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name());
            if (!obj->isDestroyed())
            {
                totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1;
            }
        }
        printf("--non-destroyed totals--\n");
        int grand_total=0;
        for (auto entry : totals)
        {
            printf("%4d %s\n", entry.second, entry.first.c_str());
            grand_total+=entry.second;
        }
        printf("%4d %s\n",grand_total,"All PObjects");
        printf("------------------------\n");
    }
#endif
    InputHandler::handleEvent(event);
    if (event.type == sf::Event::Resized)
        windowManager->setupView();
#ifdef __ANDROID__
    //Focus lost and focus gained events are used when the application window is created and destroyed.
    if (event.type == sf::Event::LostFocus)
        running = false;

    //The MouseEntered and MouseLeft events are received when the activity needs to pause or resume.
    if (event.type == sf::Event::MouseLeft)
    {
        //Pause is when a small popup is on top of the window. So keep running.
        while(windowManager->window.isOpen() && windowManager->window.waitEvent(event))
        {
            if (event.type != sf::Event::MouseLeft)
                handleEvent(event);
            if (event.type == sf::Event::MouseEntered)
                break;
        }
    }
#endif//__ANDROID__
}

void Engine::setGameSpeed(float speed)
{
    gameSpeed = speed;
}

float Engine::getGameSpeed()
{
    return gameSpeed;
}

float Engine::getElapsedTime()
{
    return elapsedTime;
}

Engine::EngineTiming Engine::getEngineTiming()
{
    return last_engine_timing;
}

void Engine::shutdown()
{
    running = false;
}
<|endoftext|>


<commit_before>#include "engine.h"
#include "random.h"
#include "gameEntity.h"
#include "Updatable.h"
#include "collisionable.h"
#include "audio/source.h"

#include <SDL.h>

#ifdef DEBUG
#include <typeinfo>
int DEBUG_PobjCount;
PObject* DEBUG_PobjListStart;
#endif

#ifdef WIN32
#include <windows.h>

namespace
{
    HINSTANCE exchndl = nullptr;
}
#endif

Engine* engine;

Engine::Engine()
{
    engine = this;

#ifdef WIN32
    // Setup crash reporter (Dr. MinGW) if available.
    exchndl = LoadLibrary(TEXT("exchndl.dll"));

    if (exchndl)
    {
        auto pfnExcHndlInit = GetProcAddress(exchndl, "ExcHndlInit");

        if (pfnExcHndlInit)
        {
            pfnExcHndlInit();
            LOG(INFO) << "Crash Reporter ON";
        }
        else
        {
            LOG(WARNING) << "Failed to initialize Crash Reporter";
            FreeLibrary(exchndl);
            exchndl = nullptr;
        }
    }
#endif // WIN32

    SDL_Init(SDL_INIT_EVERYTHING);
    atexit(SDL_Quit);

    initRandom();
    windowManager = nullptr;
    CollisionManager::initialize();
    InputHandler::initialize();
    gameSpeed = 1.0;
    running = true;
    elapsedTime = 0.0;
    soundManager = new SoundManager();
}

Engine::~Engine()
{
    if (windowManager)
        windowManager->close();
    delete soundManager;
    soundManager = nullptr;

#ifdef WIN32
    if (exchndl)
    {
        FreeLibrary(exchndl);
        exchndl = nullptr;
    }
#endif // WIN32
}

void Engine::registerObject(string name, P<PObject> obj)
{
    objectMap[name] = obj;
}

P<PObject> Engine::getObject(string name)
{
    if (!objectMap[name])
        return NULL;
    return objectMap[name];
}

void Engine::runMainLoop()
{
    windowManager = dynamic_cast<WindowManager*>(*getObject("windowManager"));
    if (!windowManager)
    {
        sp::SystemStopwatch frame_timer;
        while(running)
        {
            float delta = frame_timer.restart();
            if (delta > 0.5f)
                delta = 0.5f;
            if (delta < 0.001f)
                delta = 0.001f;
            delta *= gameSpeed;

            foreach(Updatable, u, updatableList)
                u->update(delta);
            elapsedTime += delta;
            CollisionManager::handleCollisions(delta);
            ScriptObject::clearDestroyedObjects();
            soundManager->updateTick();

            std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta));
        }
    }else{
        sp::audio::Source::startAudioSystem();
        sp::SystemStopwatch frame_timer;
#ifdef DEBUG
        sp::SystemTimer debug_output_timer;
        debug_output_timer.repeat(5);
#endif
        while(running)
        {
            InputHandler::preEventsUpdate();
            // Handle events
            SDL_Event event;
            while (SDL_PollEvent(&event))
            {
                handleEvent(event);
            }
            InputHandler::postEventsUpdate();

#ifdef DEBUG
            if (debug_output_timer.isExpired())
                printf("Object count: %4d %4zd\n", DEBUG_PobjCount, updatableList.size());
#endif

            float delta = frame_timer.restart();
            if (delta > 0.5f)
                delta = 0.5f;
            if (delta < 0.001f)
                delta = 0.001f;
            delta *= gameSpeed;
#ifdef DEBUG
#warning TODO SDL2
/*
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab))
                delta /= 5.f;
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde))
                delta *= 5.f;
*/
#endif
            EngineTiming engine_timing;

            sp::SystemStopwatch engine_timing_stopwatch;
            foreach(Updatable, u, updatableList) {
                u->update(delta);
            }
            elapsedTime += delta;
            engine_timing.update = engine_timing_stopwatch.restart();
            CollisionManager::handleCollisions(delta);
            engine_timing.collision = engine_timing_stopwatch.restart();
            ScriptObject::clearDestroyedObjects();
            soundManager->updateTick();

            // Clear the window
            windowManager->render();
            engine_timing.render = engine_timing_stopwatch.restart();
            engine_timing.server_update = 0.0f;
            if (game_server)
                engine_timing.server_update = game_server->getUpdateTime();

            last_engine_timing = engine_timing;
        }
        soundManager->stopMusic();
    }
}

void Engine::handleEvent(SDL_Event& event)
{
    // Window closed: exit
    if (event.type == SDL_QUIT)
        running = false;
    if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED)
        windowManager->windowHasFocus = true;
    if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)
        windowManager->windowHasFocus = false;
#ifdef DEBUG
    if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)
        running = false;
    if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l)
    {
        int n = 0;
        printf("------------------------\n");
        std::unordered_map<string,int> totals;
        for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext)
        {
            printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name());
            if (!obj->isDestroyed())
            {
                totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1;
            }
        }
        printf("--non-destroyed totals--\n");
        int grand_total=0;
        for (auto entry : totals)
        {
            printf("%4d %s\n", entry.second, entry.first.c_str());
            grand_total+=entry.second;
        }
        printf("%4d %s\n",grand_total,"All PObjects");
        printf("------------------------\n");
    }
#endif
    InputHandler::handleEvent(event);
    if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED)
        windowManager->setupView();
#ifdef __ANDROID__
    //Focus lost and focus gained events are used when the application window is created and destroyed.
    if (event.type == sf::Event::LostFocus)
        running = false;

    //The MouseEntered and MouseLeft events are received when the activity needs to pause or resume.
    if (event.type == sf::Event::MouseLeft)
    {
        //Pause is when a small popup is on top of the window. So keep running.
        while(windowManager->window.isOpen() && windowManager->window.waitEvent(event))
        {
            if (event.type != sf::Event::MouseLeft)
                handleEvent(event);
            if (event.type == sf::Event::MouseEntered)
                break;
        }
    }
#endif//__ANDROID__
}

void Engine::setGameSpeed(float speed)
{
    gameSpeed = speed;
}

float Engine::getGameSpeed()
{
    return gameSpeed;
}

float Engine::getElapsedTime()
{
    return elapsedTime;
}

Engine::EngineTiming Engine::getEngineTiming()
{
    return last_engine_timing;
}

void Engine::shutdown()
{
    running = false;
}
<commit_msg>Remove unneeded android code<commit_after>#include "engine.h"
#include "random.h"
#include "gameEntity.h"
#include "Updatable.h"
#include "collisionable.h"
#include "audio/source.h"

#include <SDL.h>

#ifdef DEBUG
#include <typeinfo>
int DEBUG_PobjCount;
PObject* DEBUG_PobjListStart;
#endif

#ifdef WIN32
#include <windows.h>

namespace
{
    HINSTANCE exchndl = nullptr;
}
#endif

Engine* engine;

Engine::Engine()
{
    engine = this;

#ifdef WIN32
    // Setup crash reporter (Dr. MinGW) if available.
    exchndl = LoadLibrary(TEXT("exchndl.dll"));

    if (exchndl)
    {
        auto pfnExcHndlInit = GetProcAddress(exchndl, "ExcHndlInit");

        if (pfnExcHndlInit)
        {
            pfnExcHndlInit();
            LOG(INFO) << "Crash Reporter ON";
        }
        else
        {
            LOG(WARNING) << "Failed to initialize Crash Reporter";
            FreeLibrary(exchndl);
            exchndl = nullptr;
        }
    }
#endif // WIN32

    SDL_Init(SDL_INIT_EVERYTHING);
    atexit(SDL_Quit);

    initRandom();
    windowManager = nullptr;
    CollisionManager::initialize();
    InputHandler::initialize();
    gameSpeed = 1.0;
    running = true;
    elapsedTime = 0.0;
    soundManager = new SoundManager();
}

Engine::~Engine()
{
    if (windowManager)
        windowManager->close();
    delete soundManager;
    soundManager = nullptr;

#ifdef WIN32
    if (exchndl)
    {
        FreeLibrary(exchndl);
        exchndl = nullptr;
    }
#endif // WIN32
}

void Engine::registerObject(string name, P<PObject> obj)
{
    objectMap[name] = obj;
}

P<PObject> Engine::getObject(string name)
{
    if (!objectMap[name])
        return NULL;
    return objectMap[name];
}

void Engine::runMainLoop()
{
    windowManager = dynamic_cast<WindowManager*>(*getObject("windowManager"));
    if (!windowManager)
    {
        sp::SystemStopwatch frame_timer;
        while(running)
        {
            float delta = frame_timer.restart();
            if (delta > 0.5f)
                delta = 0.5f;
            if (delta < 0.001f)
                delta = 0.001f;
            delta *= gameSpeed;

            foreach(Updatable, u, updatableList)
                u->update(delta);
            elapsedTime += delta;
            CollisionManager::handleCollisions(delta);
            ScriptObject::clearDestroyedObjects();
            soundManager->updateTick();

            std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta));
        }
    }else{
        sp::audio::Source::startAudioSystem();
        sp::SystemStopwatch frame_timer;
#ifdef DEBUG
        sp::SystemTimer debug_output_timer;
        debug_output_timer.repeat(5);
#endif
        while(running)
        {
            InputHandler::preEventsUpdate();
            // Handle events
            SDL_Event event;
            while (SDL_PollEvent(&event))
            {
                handleEvent(event);
            }
            InputHandler::postEventsUpdate();

#ifdef DEBUG
            if (debug_output_timer.isExpired())
                printf("Object count: %4d %4zd\n", DEBUG_PobjCount, updatableList.size());
#endif

            float delta = frame_timer.restart();
            if (delta > 0.5f)
                delta = 0.5f;
            if (delta < 0.001f)
                delta = 0.001f;
            delta *= gameSpeed;
#ifdef DEBUG
#warning TODO SDL2
/*
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab))
                delta /= 5.f;
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde))
                delta *= 5.f;
*/
#endif
            EngineTiming engine_timing;

            sp::SystemStopwatch engine_timing_stopwatch;
            foreach(Updatable, u, updatableList) {
                u->update(delta);
            }
            elapsedTime += delta;
            engine_timing.update = engine_timing_stopwatch.restart();
            CollisionManager::handleCollisions(delta);
            engine_timing.collision = engine_timing_stopwatch.restart();
            ScriptObject::clearDestroyedObjects();
            soundManager->updateTick();

            // Clear the window
            windowManager->render();
            engine_timing.render = engine_timing_stopwatch.restart();
            engine_timing.server_update = 0.0f;
            if (game_server)
                engine_timing.server_update = game_server->getUpdateTime();

            last_engine_timing = engine_timing;
        }
        soundManager->stopMusic();
    }
}

void Engine::handleEvent(SDL_Event& event)
{
    // Window closed: exit
    if (event.type == SDL_QUIT)
        running = false;
    if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED)
        windowManager->windowHasFocus = true;
    if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)
        windowManager->windowHasFocus = false;
#ifdef DEBUG
    if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)
        running = false;
    if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l)
    {
        int n = 0;
        printf("------------------------\n");
        std::unordered_map<string,int> totals;
        for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext)
        {
            printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name());
            if (!obj->isDestroyed())
            {
                totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1;
            }
        }
        printf("--non-destroyed totals--\n");
        int grand_total=0;
        for (auto entry : totals)
        {
            printf("%4d %s\n", entry.second, entry.first.c_str());
            grand_total+=entry.second;
        }
        printf("%4d %s\n",grand_total,"All PObjects");
        printf("------------------------\n");
    }
#endif
    InputHandler::handleEvent(event);
    if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED)
        windowManager->setupView();
}

void Engine::setGameSpeed(float speed)
{
    gameSpeed = speed;
}

float Engine::getGameSpeed()
{
    return gameSpeed;
}

float Engine::getElapsedTime()
{
    return elapsedTime;
}

Engine::EngineTiming Engine::getEngineTiming()
{
    return last_engine_timing;
}

void Engine::shutdown()
{
    running = false;
}
<|endoftext|>