<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/logging.h"
#include "base/task.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/sync/glue/data_type_manager_impl.h"

static const int kStartOrderStart = -1;

namespace {

static const syncable::ModelType kStartOrder[] = {
  syncable::BOOKMARKS,
  syncable::PREFERENCES
};

}  // namespace

namespace browser_sync {

DataTypeManagerImpl::DataTypeManagerImpl(
    const DataTypeController::TypeMap& controllers)
    : controllers_(controllers),
      state_(DataTypeManager::STOPPED),
      current_type_(kStartOrderStart) {
  DCHECK(arraysize(kStartOrder) > 0);
  // Ensure all data type controllers are stopped.
  for (DataTypeController::TypeMap::const_iterator it = controllers_.begin();
       it != controllers_.end(); ++it) {
    DCHECK_EQ(DataTypeController::NOT_RUNNING, (*it).second->state());
  }
}

void DataTypeManagerImpl::Start(StartCallback* start_callback) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  if (state_ != STOPPED) {
    start_callback->Run(BUSY);
    delete start_callback;
    return;
  }

  state_ = STARTING;
  start_callback_.reset(start_callback);
  current_type_ = kStartOrderStart;
  StartNextType();
}

void DataTypeManagerImpl::StartNextType() {
  // Ensure that the current type has indeed started.
  DCHECK(current_type_ == kStartOrderStart ||
         controllers_[kStartOrder[current_type_]]->state() ==
           DataTypeController::RUNNING);

  // Find the next startable type.
  while (current_type_ < static_cast<int>(arraysize(kStartOrder)) - 1) {
    current_type_++;
    syncable::ModelType type = kStartOrder[current_type_];
    if (IsEnabled(type)) {
      LOG(INFO) << "Starting " << controllers_[type]->name();
      controllers_[type]->Start(
          true,
          NewCallback(this, &DataTypeManagerImpl::TypeStartCallback));
      return;
    }
  }

  // No more startable types found, we must be done.
  DCHECK_EQ(state_, STARTING);
  state_ = STARTED;
  start_callback_->Run(OK);
  start_callback_.reset();
}

void DataTypeManagerImpl::TypeStartCallback(
    DataTypeController::StartResult result) {
  // When the data type controller invokes this callback, it must be
  // on the UI thread.
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));

  // If we reach this callback while stopping, this means that the
  // current data type was stopped while still starting up.  Now that
  // the data type is aborted, we can finish stop.
  if (state_ == STOPPING) {
    FinishStop();
    start_callback_->Run(DataTypeManager::ABORTED);
    start_callback_.reset();
    return;
  }

  // If the type started normally, continue to the next type.
  syncable::ModelType type = kStartOrder[current_type_];
  if (result == DataTypeController::OK ||
      result == DataTypeController::OK_FIRST_RUN) {
    LOG(INFO) << "Started " << controllers_[type]->name();
    StartNextType();
    return;
  }

  // Any other result is a fatal error.  Shut down any types we've
  // managed to start up to this point and pass the result to the
  // callback.
  LOG(INFO) << "Failed " << controllers_[type]->name();
  FinishStop();
  StartResult start_result;
  switch(result) {
    case DataTypeController::ABORTED:
      start_result = DataTypeManager::ABORTED;
      break;
    case DataTypeController::ASSOCIATION_FAILED:
      start_result = DataTypeManager::ASSOCIATION_FAILED;
      break;
    default:
      NOTREACHED();
      break;
  }
  start_callback_->Run(start_result);
  start_callback_.reset();
}

void DataTypeManagerImpl::Stop() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  if (state_ == STOPPED)
    return;

  // If we are currently starting, then the current type is in a
  // partially started state.  Abort the startup of the current type
  // and continue shutdown when the abort completes.
  if (state_ == STARTING) {
    state_ = STOPPING;
    syncable::ModelType type = kStartOrder[current_type_];
    controllers_[type]->Stop();
    return;
  }

  state_ = STOPPING;
  FinishStop();
}

void DataTypeManagerImpl::FinishStop() {
  DCHECK(state_== STARTING || state_ == STOPPING);
  // Simply call the Stop() method on all running data types.
  for (unsigned int i = 0; i < arraysize(kStartOrder); ++i) {
    syncable::ModelType type = kStartOrder[i];
    if (IsRegistered(type) &&
        controllers_[type]->state() == DataTypeController::RUNNING) {
      controllers_[type]->Stop();
      LOG(INFO) << "Stopped " << controllers_[type]->name();
    }
  }
  state_ = STOPPED;
}

bool DataTypeManagerImpl::IsRegistered(syncable::ModelType type) {
  return controllers_.count(type) == 1;
}

bool DataTypeManagerImpl::IsEnabled(syncable::ModelType type) {
  return IsRegistered(type) && controllers_[type]->enabled();
}

}  // namespace browser_sync
<commit_msg>Fix mac build bustage<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/logging.h"
#include "base/task.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/sync/glue/data_type_manager_impl.h"

static const int kStartOrderStart = -1;

namespace {

static const syncable::ModelType kStartOrder[] = {
  syncable::BOOKMARKS,
  syncable::PREFERENCES
};

}  // namespace

namespace browser_sync {

DataTypeManagerImpl::DataTypeManagerImpl(
    const DataTypeController::TypeMap& controllers)
    : controllers_(controllers),
      state_(DataTypeManager::STOPPED),
      current_type_(kStartOrderStart) {
  DCHECK(arraysize(kStartOrder) > 0);
  // Ensure all data type controllers are stopped.
  for (DataTypeController::TypeMap::const_iterator it = controllers_.begin();
       it != controllers_.end(); ++it) {
    DCHECK_EQ(DataTypeController::NOT_RUNNING, (*it).second->state());
  }
}

void DataTypeManagerImpl::Start(StartCallback* start_callback) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  if (state_ != STOPPED) {
    start_callback->Run(BUSY);
    delete start_callback;
    return;
  }

  state_ = STARTING;
  start_callback_.reset(start_callback);
  current_type_ = kStartOrderStart;
  StartNextType();
}

void DataTypeManagerImpl::StartNextType() {
  // Ensure that the current type has indeed started.
  DCHECK(current_type_ == kStartOrderStart ||
         controllers_[kStartOrder[current_type_]]->state() ==
           DataTypeController::RUNNING);

  // Find the next startable type.
  while (current_type_ < static_cast<int>(arraysize(kStartOrder)) - 1) {
    current_type_++;
    syncable::ModelType type = kStartOrder[current_type_];
    if (IsEnabled(type)) {
      LOG(INFO) << "Starting " << controllers_[type]->name();
      controllers_[type]->Start(
          true,
          NewCallback(this, &DataTypeManagerImpl::TypeStartCallback));
      return;
    }
  }

  // No more startable types found, we must be done.
  DCHECK_EQ(state_, STARTING);
  state_ = STARTED;
  start_callback_->Run(OK);
  start_callback_.reset();
}

void DataTypeManagerImpl::TypeStartCallback(
    DataTypeController::StartResult result) {
  // When the data type controller invokes this callback, it must be
  // on the UI thread.
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));

  // If we reach this callback while stopping, this means that the
  // current data type was stopped while still starting up.  Now that
  // the data type is aborted, we can finish stop.
  if (state_ == STOPPING) {
    FinishStop();
    start_callback_->Run(DataTypeManager::ABORTED);
    start_callback_.reset();
    return;
  }

  // If the type started normally, continue to the next type.
  syncable::ModelType type = kStartOrder[current_type_];
  if (result == DataTypeController::OK ||
      result == DataTypeController::OK_FIRST_RUN) {
    LOG(INFO) << "Started " << controllers_[type]->name();
    StartNextType();
    return;
  }

  // Any other result is a fatal error.  Shut down any types we've
  // managed to start up to this point and pass the result to the
  // callback.
  LOG(INFO) << "Failed " << controllers_[type]->name();
  FinishStop();
  StartResult start_result = DataTypeManager::ABORTED;
  switch(result) {
    case DataTypeController::ABORTED:
      start_result = DataTypeManager::ABORTED;
      break;
    case DataTypeController::ASSOCIATION_FAILED:
      start_result = DataTypeManager::ASSOCIATION_FAILED;
      break;
    default:
      NOTREACHED();
      break;
  }
  start_callback_->Run(start_result);
  start_callback_.reset();
}

void DataTypeManagerImpl::Stop() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  if (state_ == STOPPED)
    return;

  // If we are currently starting, then the current type is in a
  // partially started state.  Abort the startup of the current type
  // and continue shutdown when the abort completes.
  if (state_ == STARTING) {
    state_ = STOPPING;
    syncable::ModelType type = kStartOrder[current_type_];
    controllers_[type]->Stop();
    return;
  }

  state_ = STOPPING;
  FinishStop();
}

void DataTypeManagerImpl::FinishStop() {
  DCHECK(state_== STARTING || state_ == STOPPING);
  // Simply call the Stop() method on all running data types.
  for (unsigned int i = 0; i < arraysize(kStartOrder); ++i) {
    syncable::ModelType type = kStartOrder[i];
    if (IsRegistered(type) &&
        controllers_[type]->state() == DataTypeController::RUNNING) {
      controllers_[type]->Stop();
      LOG(INFO) << "Stopped " << controllers_[type]->name();
    }
  }
  state_ = STOPPED;
}

bool DataTypeManagerImpl::IsRegistered(syncable::ModelType type) {
  return controllers_.count(type) == 1;
}

bool DataTypeManagerImpl::IsEnabled(syncable::ModelType type) {
  return IsRegistered(type) && controllers_[type]->enabled();
}

}  // namespace browser_sync
<|endoftext|>


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

#ifndef DATABLOCK_H
#define DATABLOCK_H

#include "mem/ruby/common/Global.hh"
#include "mem/ruby/system/System.hh"
#include "mem/gems_common/Vector.hh"

class DataBlock {
 public:
  // Constructors
  DataBlock() {alloc();}
  DataBlock(const DataBlock & cp) {
    m_data = new uint8[RubySystem::getBlockSizeBytes()];
    memcpy(m_data, cp.m_data, RubySystem::getBlockSizeBytes());
    m_alloc = true;
  }

  // Destructor
  ~DataBlock() { if(m_alloc) delete [] m_data;}

  DataBlock& operator=(const DataBlock& obj);

  // Public Methods
  void assign(uint8* data);

  void clear();
  uint8 getByte(int whichByte) const;
  const uint8* getData(int offset, int len) const;
  void setByte(int whichByte, uint8 data);
  void setData(uint8* data, int offset, int len);
  void copyPartial(const DataBlock & dblk, int offset, int len);
  bool equal(const DataBlock& obj) const;
  void print(ostream& out) const;

private:
  void alloc();
  // Data Members (m_ prefix)
  uint8* m_data;
  bool m_alloc;
};

// Output operator declaration
ostream& operator<<(ostream& out, const DataBlock& obj);

bool operator==(const DataBlock& obj1, const DataBlock& obj2);

// inline functions for speed

inline
void DataBlock::assign(uint8* data)
{
  delete [] m_data;
  m_data = data;
  m_alloc = false;
}

inline
void DataBlock::alloc()
{
  m_data = new uint8[RubySystem::getBlockSizeBytes()];
  m_alloc = true;
  clear();
}

inline
void DataBlock::clear()
{
  memset(m_data, 0, RubySystem::getBlockSizeBytes());
}

inline
bool DataBlock::equal(const DataBlock& obj) const
{
  return !memcmp(m_data, obj.m_data, RubySystem::getBlockSizeBytes());
}

inline
void DataBlock::print(ostream& out) const
{
  int size = RubySystem::getBlockSizeBytes();
  out << "[ ";
  for (int i = 0; i < size; i+=4) {
    out << hex << *((uint32*)(&(m_data[i]))) << " ";
  }
  out << dec << "]" << flush;
}

inline
uint8 DataBlock::getByte(int whichByte) const
{
  return m_data[whichByte];
}

inline
const uint8* DataBlock::getData(int offset, int len) const
{
  assert(offset + len <= RubySystem::getBlockSizeBytes());
  return &m_data[offset];
}

inline
void DataBlock::setByte(int whichByte, uint8 data)
{
    m_data[whichByte] = data;
}

inline
void DataBlock::setData(uint8* data, int offset, int len)
{
  assert(offset + len <= RubySystem::getBlockSizeBytes());
  memcpy(&m_data[offset], data, len);
}

inline
void DataBlock::copyPartial(const DataBlock & dblk, int offset, int len)
{
  setData(&dblk.m_data[offset], offset, len);
}

// ******************* Definitions *******************

// Output operator definition
extern inline
ostream& operator<<(ostream& out, const DataBlock& obj)
{
  obj.print(out);
  out << flush;
  return out;
}

extern inline
bool operator==(const DataBlock& obj1,const DataBlock& obj2)
{
  return (obj1.equal(obj2));
}

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

#ifndef DATABLOCK_H
#define DATABLOCK_H

#include "mem/ruby/common/Global.hh"
#include "mem/ruby/system/System.hh"
#include "mem/gems_common/Vector.hh"

class DataBlock {
 public:
  // Constructors
  DataBlock() {alloc();}
  DataBlock(const DataBlock & cp) {
    m_data = new uint8[RubySystem::getBlockSizeBytes()];
    memcpy(m_data, cp.m_data, RubySystem::getBlockSizeBytes());
    m_alloc = true;
  }

  // Destructor
  ~DataBlock() { if(m_alloc) delete [] m_data;}

  DataBlock& operator=(const DataBlock& obj);

  // Public Methods
  void assign(uint8* data);

  void clear();
  uint8 getByte(int whichByte) const;
  const uint8* getData(int offset, int len) const;
  void setByte(int whichByte, uint8 data);
  void setData(uint8* data, int offset, int len);
  void copyPartial(const DataBlock & dblk, int offset, int len);
  bool equal(const DataBlock& obj) const;
  void print(ostream& out) const;

private:
  void alloc();
  // Data Members (m_ prefix)
  uint8* m_data;
  bool m_alloc;
};

// Output operator declaration
ostream& operator<<(ostream& out, const DataBlock& obj);

bool operator==(const DataBlock& obj1, const DataBlock& obj2);

// inline functions for speed

inline
void DataBlock::assign(uint8* data)
{
  delete [] m_data;
  m_data = data;
  m_alloc = false;
}

inline
void DataBlock::alloc()
{
  m_data = new uint8[RubySystem::getBlockSizeBytes()];
  m_alloc = true;
  clear();
}

inline
void DataBlock::clear()
{
  memset(m_data, 0, RubySystem::getBlockSizeBytes());
}

inline
bool DataBlock::equal(const DataBlock& obj) const
{
  return !memcmp(m_data, obj.m_data, RubySystem::getBlockSizeBytes());
}

inline
void DataBlock::print(ostream& out) const
{
  int size = RubySystem::getBlockSizeBytes();
  out << "[ ";
  for (int i = 0; i < size; i++) {
    out << setw(2) << setfill('0') << hex << "0x" << (int)m_data[i] << " ";
  }
  out << dec << "]" << flush;
}

inline
uint8 DataBlock::getByte(int whichByte) const
{
  return m_data[whichByte];
}

inline
const uint8* DataBlock::getData(int offset, int len) const
{
  assert(offset + len <= RubySystem::getBlockSizeBytes());
  return &m_data[offset];
}

inline
void DataBlock::setByte(int whichByte, uint8 data)
{
    m_data[whichByte] = data;
}

inline
void DataBlock::setData(uint8* data, int offset, int len)
{
  assert(offset + len <= RubySystem::getBlockSizeBytes());
  memcpy(&m_data[offset], data, len);
}

inline
void DataBlock::copyPartial(const DataBlock & dblk, int offset, int len)
{
  setData(&dblk.m_data[offset], offset, len);
}

// ******************* Definitions *******************

// Output operator definition
extern inline
ostream& operator<<(ostream& out, const DataBlock& obj)
{
  obj.print(out);
  out << flush;
  return out;
}

extern inline
bool operator==(const DataBlock& obj1,const DataBlock& obj2)
{
  return (obj1.equal(obj2));
}

#endif //DATABLOCK_H
<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "TransitionToInteriorPointStage.h"
#include "InteriorsExplorerModel.h"
#include "InteriorsCameraController.h"
#include "InteriorInteractionModel.h"
#include "InteriorSelectionModel.h"
#include "InteriorTransitionModel.h"

namespace ExampleApp
{
    namespace CameraTransitions
    {
        namespace SdkModel
        {
            TransitionToInteriorPointStage::TransitionToInteriorPointStage(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
                                                                           Eegeo::Resources::Interiors::InteriorSelectionModel& interiorSelectionModel,
                                                                           const Eegeo::Resources::Interiors::InteriorTransitionModel& interiorTransitionModel,
                                                                           InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorsExplorerModel,
                                                                           Eegeo::Resources::Interiors::InteriorsCameraController& cameraController,
                                                                           const Eegeo::dv3& newInterestPoint,
                                                                           float newDistanceToInterest,
                                                                           const Eegeo::Resources::Interiors::InteriorId &interiorId,
                                                                           int targetFloorIndex,
                                                                           bool jumpIfFar)
            : m_interiorInteractionModel(interiorInteractionModel)
            , m_interiorSelectionModel(interiorSelectionModel)
            , m_interiorTransitionModel(interiorTransitionModel)
            , m_interiorsExplorerModel(interiorsExplorerModel)
            , m_cameraController(cameraController)
            , m_newInterestPoint(newInterestPoint)
            , m_targetDistanceToInterest(newDistanceToInterest)
            , m_transitionDuration(0.5f)
            , m_transitionTime(0.0f)
            , m_interiorId(interiorId)
            , m_targetFloorIndex(targetFloorIndex)
            , m_failed(false)
            , m_jumpIfFar(jumpIfFar)
            , m_startCameraInterestAltitude(0.0f)
            , m_endCameraInterestAltitude(0.0f)
            , m_initialisedNextInterior(false)
            , m_cameraInterestAltitudeStartTime(0.0f)
            {
            }

            void TransitionToInteriorPointStage::Start()
            {
                Eegeo_ASSERT(m_interiorInteractionModel.HasInteriorModel(), "Must be inside interior to start this transition");
                m_startCameraInterestAltitude = m_cameraController.GetFloorOffsetHeight();
                m_endCameraInterestAltitude = m_startCameraInterestAltitude;
                m_interiorSelectionModel.ClearSelection();
                m_interiorSelectionModel.SelectInteriorId(m_interiorId);
                m_interiorsExplorerModel.HideInteriorExplorer();
                m_transitionTime = 0.0f;
                m_startInterestPoint = m_cameraController.GetInterestLocation();
                m_startDistanceToInterest = m_cameraController.GetDistanceToInterest();
                m_cameraController.SetApplyRestrictions(false);
                m_cameraController.SetApplyFloorOffset(false);
                m_initialisedNextInterior = false;
                m_cameraInterestAltitudeStartTime = 0.0f;
            }

            void TransitionToInteriorPointStage::Update(float dt)
            {
                if(m_failed)
                {
                    return;
                }

                if(!m_initialisedNextInterior && m_interiorInteractionModel.HasInteriorModel())
                {
                    m_interiorInteractionModel.SetSelectedFloorIndex(m_targetFloorIndex);
                    m_endCameraInterestAltitude = m_cameraController.GetFloorOffsetHeight();
                    m_cameraInterestAltitudeStartTime = m_transitionTime;
                    m_initialisedNextInterior = true;
                }

                if(m_jumpIfFar && ShouldJumpTo(m_newInterestPoint))
                {
                    m_transitionTime = 1.01f;
                }
                else
                {
                    m_transitionTime += dt/m_transitionDuration;
                    float t = Eegeo::Math::Clamp01(m_transitionTime);
                    float smoothT = Eegeo::Math::SmoothStep(t);
                    Eegeo::dv3 lerpInterestPoint = Eegeo::dv3::Lerp(m_startInterestPoint, m_newInterestPoint, smoothT);
                    m_cameraController.SetInterestLocation(lerpInterestPoint);

                    float lerpDistance = Eegeo::Math::Lerp(m_startDistanceToInterest, m_targetDistanceToInterest, smoothT);
                    m_cameraController.SetDistanceToInterest(lerpDistance);

                    if(m_initialisedNextInterior)
                    {
                        float t2 = m_cameraInterestAltitudeStartTime >= 1.0f ? 1.0f : Eegeo::Math::Clamp01((m_transitionTime - m_cameraInterestAltitudeStartTime)/(1.0f-m_cameraInterestAltitudeStartTime));
                        float smoothT2 = Eegeo::Math::SmoothStep(t2);
                        float lerpAltitude = Eegeo::Math::Lerp(m_startCameraInterestAltitude, m_endCameraInterestAltitude, smoothT2);
                        m_cameraController.SetCameraInterestAltitude(lerpAltitude);
                    }
                }

                // Check fail condition and clean up on fail
                if(!m_interiorSelectionModel.IsInteriorSelected())
                {
                    m_failed = true;
                    m_cameraController.SetApplyRestrictions(true);
                    m_cameraController.SetApplyFloorOffset(true);
                }

            }

            void TransitionToInteriorPointStage::End()
            {
                m_cameraController.SetInterestLocation(m_newInterestPoint);
                m_cameraController.SetDistanceToInterest(m_targetDistanceToInterest);
                m_cameraController.SetCameraInterestAltitude(m_endCameraInterestAltitude);
                m_cameraController.SetApplyRestrictions(true);
                m_cameraController.SetApplyFloorOffset(true);
                m_interiorInteractionModel.SetSelectedFloorIndex(m_targetFloorIndex);
                m_interiorsExplorerModel.ShowInteriorExplorer(true);
            }

            const bool TransitionToInteriorPointStage::StageIsComplete() const
            {
                return m_transitionTime >= 1.0f && m_interiorTransitionModel.InteriorIsVisible();
            }

            bool TransitionToInteriorPointStage::ShouldJumpTo(Eegeo::dv3& newInterestPoint)
            {
                const double MAX_CAMERA_TRANSITION_DISTANCE = 500;
                const Eegeo::dv3& currentCameraLocation = m_cameraController.GetCameraState().LocationEcef();
                double distance = (newInterestPoint - currentCameraLocation).Length();
                return distance > MAX_CAMERA_TRANSITION_DISTANCE;
            }

            const bool TransitionToInteriorPointStage::StageHasFailed() const
            {
                return m_failed;
            }
        }
    }
}<commit_msg>Build fix - CameraState header had been present on windows via PCH, but wasn't included for Android & iOS.  Buddy: Paul Harris<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "TransitionToInteriorPointStage.h"
#include "InteriorsExplorerModel.h"
#include "InteriorsCameraController.h"
#include "InteriorInteractionModel.h"
#include "InteriorSelectionModel.h"
#include "InteriorTransitionModel.h"
#include "CameraState.h"

namespace ExampleApp
{
    namespace CameraTransitions
    {
        namespace SdkModel
        {
            TransitionToInteriorPointStage::TransitionToInteriorPointStage(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
                                                                           Eegeo::Resources::Interiors::InteriorSelectionModel& interiorSelectionModel,
                                                                           const Eegeo::Resources::Interiors::InteriorTransitionModel& interiorTransitionModel,
                                                                           InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorsExplorerModel,
                                                                           Eegeo::Resources::Interiors::InteriorsCameraController& cameraController,
                                                                           const Eegeo::dv3& newInterestPoint,
                                                                           float newDistanceToInterest,
                                                                           const Eegeo::Resources::Interiors::InteriorId &interiorId,
                                                                           int targetFloorIndex,
                                                                           bool jumpIfFar)
            : m_interiorInteractionModel(interiorInteractionModel)
            , m_interiorSelectionModel(interiorSelectionModel)
            , m_interiorTransitionModel(interiorTransitionModel)
            , m_interiorsExplorerModel(interiorsExplorerModel)
            , m_cameraController(cameraController)
            , m_newInterestPoint(newInterestPoint)
            , m_targetDistanceToInterest(newDistanceToInterest)
            , m_transitionDuration(0.5f)
            , m_transitionTime(0.0f)
            , m_interiorId(interiorId)
            , m_targetFloorIndex(targetFloorIndex)
            , m_failed(false)
            , m_jumpIfFar(jumpIfFar)
            , m_startCameraInterestAltitude(0.0f)
            , m_endCameraInterestAltitude(0.0f)
            , m_initialisedNextInterior(false)
            , m_cameraInterestAltitudeStartTime(0.0f)
            {
            }

            void TransitionToInteriorPointStage::Start()
            {
                Eegeo_ASSERT(m_interiorInteractionModel.HasInteriorModel(), "Must be inside interior to start this transition");
                m_startCameraInterestAltitude = m_cameraController.GetFloorOffsetHeight();
                m_endCameraInterestAltitude = m_startCameraInterestAltitude;
                m_interiorSelectionModel.ClearSelection();
                m_interiorSelectionModel.SelectInteriorId(m_interiorId);
                m_interiorsExplorerModel.HideInteriorExplorer();
                m_transitionTime = 0.0f;
                m_startInterestPoint = m_cameraController.GetInterestLocation();
                m_startDistanceToInterest = m_cameraController.GetDistanceToInterest();
                m_cameraController.SetApplyRestrictions(false);
                m_cameraController.SetApplyFloorOffset(false);
                m_initialisedNextInterior = false;
                m_cameraInterestAltitudeStartTime = 0.0f;
            }

            void TransitionToInteriorPointStage::Update(float dt)
            {
                if(m_failed)
                {
                    return;
                }

                if(!m_initialisedNextInterior && m_interiorInteractionModel.HasInteriorModel())
                {
                    m_interiorInteractionModel.SetSelectedFloorIndex(m_targetFloorIndex);
                    m_endCameraInterestAltitude = m_cameraController.GetFloorOffsetHeight();
                    m_cameraInterestAltitudeStartTime = m_transitionTime;
                    m_initialisedNextInterior = true;
                }

                if(m_jumpIfFar && ShouldJumpTo(m_newInterestPoint))
                {
                    m_transitionTime = 1.01f;
                }
                else
                {
                    m_transitionTime += dt/m_transitionDuration;
                    float t = Eegeo::Math::Clamp01(m_transitionTime);
                    float smoothT = Eegeo::Math::SmoothStep(t);
                    Eegeo::dv3 lerpInterestPoint = Eegeo::dv3::Lerp(m_startInterestPoint, m_newInterestPoint, smoothT);
                    m_cameraController.SetInterestLocation(lerpInterestPoint);

                    float lerpDistance = Eegeo::Math::Lerp(m_startDistanceToInterest, m_targetDistanceToInterest, smoothT);
                    m_cameraController.SetDistanceToInterest(lerpDistance);

                    if(m_initialisedNextInterior)
                    {
                        float t2 = m_cameraInterestAltitudeStartTime >= 1.0f ? 1.0f : Eegeo::Math::Clamp01((m_transitionTime - m_cameraInterestAltitudeStartTime)/(1.0f-m_cameraInterestAltitudeStartTime));
                        float smoothT2 = Eegeo::Math::SmoothStep(t2);
                        float lerpAltitude = Eegeo::Math::Lerp(m_startCameraInterestAltitude, m_endCameraInterestAltitude, smoothT2);
                        m_cameraController.SetCameraInterestAltitude(lerpAltitude);
                    }
                }

                // Check fail condition and clean up on fail
                if(!m_interiorSelectionModel.IsInteriorSelected())
                {
                    m_failed = true;
                    m_cameraController.SetApplyRestrictions(true);
                    m_cameraController.SetApplyFloorOffset(true);
                }

            }

            void TransitionToInteriorPointStage::End()
            {
                m_cameraController.SetInterestLocation(m_newInterestPoint);
                m_cameraController.SetDistanceToInterest(m_targetDistanceToInterest);
                m_cameraController.SetCameraInterestAltitude(m_endCameraInterestAltitude);
                m_cameraController.SetApplyRestrictions(true);
                m_cameraController.SetApplyFloorOffset(true);
                m_interiorInteractionModel.SetSelectedFloorIndex(m_targetFloorIndex);
                m_interiorsExplorerModel.ShowInteriorExplorer(true);
            }

            const bool TransitionToInteriorPointStage::StageIsComplete() const
            {
                return m_transitionTime >= 1.0f && m_interiorTransitionModel.InteriorIsVisible();
            }

            bool TransitionToInteriorPointStage::ShouldJumpTo(Eegeo::dv3& newInterestPoint)
            {
                const double MAX_CAMERA_TRANSITION_DISTANCE = 500;
                const Eegeo::dv3& currentCameraLocation = m_cameraController.GetCameraState().LocationEcef();
                double distance = (newInterestPoint - currentCameraLocation).Length();
                return distance > MAX_CAMERA_TRANSITION_DISTANCE;
            }

            const bool TransitionToInteriorPointStage::StageHasFailed() const
            {
                return m_failed;
            }
        }
    }
}<|endoftext|>


<commit_before>#define CYBOZU_TEST_DISABLE_AUTO_RUN
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <cybozu/option.hpp>
#include <cybozu/xorshift.hpp>
#include <mcl/bn384.hpp>
#include <mcl/bn.hpp>

using namespace mcl::bn384;

mcl::fp::Mode g_mode;

#include "bench.hpp"

void testCurve(const mcl::CurveParam& cp)
{
	initPairing(cp, g_mode);
	G1 P;
	G2 Q;
	mapToG1(P, 1);
	mapToG2(Q, 1);
	GT e1, e2;
	pairing(e1, P, Q);
	cybozu::XorShift rg;
	mpz_class a, b;
	Fr r;
	r.setRand(rg); a = r.getMpz();
	r.setRand(rg); b = r.getMpz();
	G1 aP;
	G2 bQ;
	G1::mul(aP, P, a);
	G2::mul(bQ, Q, b);
	pairing(e2, aP, bQ);
	GT::pow(e1, e1, a * b);
	CYBOZU_TEST_EQUAL(e1, e2);
	testBench(P, Q);
}

CYBOZU_TEST_AUTO(pairing)
{
	puts("BN254");
	// support 256-bit pairing
	testCurve(mcl::BN254);
	puts("BN381_1");
	testCurve(mcl::BN381_1);
	puts("BN381_2");
	testCurve(mcl::BN381_2);
	puts("BLS12_381");
	testCurve(mcl::BLS12_381);
	// Q is not on EcT, but bad order
	{
		const char *s = "1 18d3d8c085a5a5e7553c3a4eb628e88b8465bf4de2612e35a0a4eb018fb0c82e9698896031e62fd7633ffd824a859474 1dc6edfcf33e29575d4791faed8e7203832217423bf7f7fbf1f6b36625b12e7132c15fbc15562ce93362a322fb83dd0d 65836963b1f7b6959030ddfa15ab38ce056097e91dedffd996c1808624fa7e2644a77be606290aa555cda8481cfb3cb 1b77b708d3d4f65aeedf54b58393463a42f0dc5856baadb5ce608036baeca398c5d9e6b169473a8838098fd72fd28b50";
		G2 Q;
		CYBOZU_TEST_EXCEPTION(Q.setStr(s, 16), std::exception);
	}
}

int main(int argc, char *argv[])
	try
{
	cybozu::Option opt;
	std::string mode;
	opt.appendOpt(&mode, "auto", "m", ": mode(gmp/gmp_mont/llvm/llvm_mont/xbyak)");
	if (!opt.parse(argc, argv)) {
		opt.usage();
		return 1;
	}
	g_mode = mcl::fp::StrToMode(mode);
	return cybozu::test::autoRun.run(argc, argv);
} catch (std::exception& e) {
	printf("ERR %s\n", e.what());
	return 1;
}
<commit_msg>add lagrange test<commit_after>#define CYBOZU_TEST_DISABLE_AUTO_RUN
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <cybozu/option.hpp>
#include <cybozu/xorshift.hpp>
#include <mcl/bn384.hpp>
#include <mcl/bn.hpp>
#include <mcl/lagrange.hpp>

using namespace mcl::bn384;

mcl::fp::Mode g_mode;

#include "bench.hpp"

void testLagrange()
{
	puts("testLagrange");
	const int k = 7;
	Fr c[k], x[k], y[k];
	for (size_t i = 0; i < k; i++) {
		c[i].setByCSPRNG();
		x[i].setByCSPRNG();
	}
	for (size_t i = 0; i < k; i++) {
		mcl::evaluatePolynomial(y[i], c, k, x[i]);
	}
	Fr s;
	mcl::LagrangeInterpolation(s, x, y, k);
	CYBOZU_TEST_EQUAL(s, c[0]);
}

void testCurve(const mcl::CurveParam& cp)
{
	initPairing(cp, g_mode);
	G1 P;
	G2 Q;
	mapToG1(P, 1);
	mapToG2(Q, 1);
	GT e1, e2;
	pairing(e1, P, Q);
	cybozu::XorShift rg;
	mpz_class a, b;
	Fr r;
	r.setRand(rg); a = r.getMpz();
	r.setRand(rg); b = r.getMpz();
	G1 aP;
	G2 bQ;
	G1::mul(aP, P, a);
	G2::mul(bQ, Q, b);
	pairing(e2, aP, bQ);
	GT::pow(e1, e1, a * b);
	CYBOZU_TEST_EQUAL(e1, e2);
	testBench(P, Q);
	testLagrange();
}

CYBOZU_TEST_AUTO(pairing)
{
	puts("BN254");
	// support 256-bit pairing
	testCurve(mcl::BN254);
	puts("BN381_1");
	testCurve(mcl::BN381_1);
	puts("BN381_2");
	testCurve(mcl::BN381_2);
	puts("BLS12_381");
	testCurve(mcl::BLS12_381);
	// Q is not on EcT, but bad order
	{
		const char *s = "1 18d3d8c085a5a5e7553c3a4eb628e88b8465bf4de2612e35a0a4eb018fb0c82e9698896031e62fd7633ffd824a859474 1dc6edfcf33e29575d4791faed8e7203832217423bf7f7fbf1f6b36625b12e7132c15fbc15562ce93362a322fb83dd0d 65836963b1f7b6959030ddfa15ab38ce056097e91dedffd996c1808624fa7e2644a77be606290aa555cda8481cfb3cb 1b77b708d3d4f65aeedf54b58393463a42f0dc5856baadb5ce608036baeca398c5d9e6b169473a8838098fd72fd28b50";
		G2 Q;
		CYBOZU_TEST_EXCEPTION(Q.setStr(s, 16), std::exception);
	}
}

int main(int argc, char *argv[])
	try
{
	cybozu::Option opt;
	std::string mode;
	opt.appendOpt(&mode, "auto", "m", ": mode(gmp/gmp_mont/llvm/llvm_mont/xbyak)");
	if (!opt.parse(argc, argv)) {
		opt.usage();
		return 1;
	}
	g_mode = mcl::fp::StrToMode(mode);
	return cybozu::test::autoRun.run(argc, argv);
} catch (std::exception& e) {
	printf("ERR %s\n", e.what());
	return 1;
}
<|endoftext|>


<commit_before>#include "Globals.h"
#include "Application.h"
#include "ModulePhysics3D.h"
#include "PhysBody3D.h"
#include "PhysVehicle3D.h"
#include "Primitive.h"
#include "ModuleCamera3D.h"
#include "ModuleInput.h"

#ifdef _DEBUG
#pragma comment (lib, "Bullet/libx86/Debug/BulletDynamics_debug.lib")
#pragma comment (lib, "Bullet/libx86/Debug/BulletCollision_debug.lib")
#pragma comment (lib, "Bullet/libx86/Debug/LinearMath_debug.lib")
#else
#pragma comment (lib, "Bullet/libx86/Release/BulletDynamics.lib")
#pragma comment (lib, "Bullet/libx86/Release/BulletCollision.lib")
#pragma comment (lib, "Bullet/libx86/Release/LinearMath.lib")
#endif

using namespace std;

ModulePhysics3D::ModulePhysics3D(Application* app, const char* name, bool start_enabled) : Module(app, name, start_enabled)
{
	debug = true;

	collision_conf = new btDefaultCollisionConfiguration();
	dispatcher = new btCollisionDispatcher(collision_conf);
	broad_phase = new btDbvtBroadphase();
	solver = new btSequentialImpulseConstraintSolver();
	debug_draw = new DebugDrawer();
}

// Destructor
ModulePhysics3D::~ModulePhysics3D()
{
	delete debug_draw;
	delete solver;
	delete broad_phase;
	delete dispatcher;
	delete collision_conf;
}

// Render not available yet----------------------------------
bool ModulePhysics3D::Init(cJSON* node)
{
	LOG("Creating 3D Physics simulation");
	bool ret = true;

	return ret;
}

// ---------------------------------------------------------
bool ModulePhysics3D::Start()
{
	LOG("Creating Physics environment");

	world = new btDiscreteDynamicsWorld(dispatcher, broad_phase, solver, collision_conf);
	//world->setDebugDrawer(debug_draw);
	world->setGravity(GRAVITY);
	vehicle_raycaster = new btDefaultVehicleRaycaster(world);

	// Big plane as ground
	{
		btCollisionShape* colShape = new btStaticPlaneShape(btVector3(0, 1, 0), 0);

		btDefaultMotionState* myMotionState = new btDefaultMotionState();
		btRigidBody::btRigidBodyConstructionInfo rbInfo(0.0f, myMotionState, colShape);

		//btRigidBody* body = new btRigidBody(rbInfo);
		//world->addRigidBody(body);
	}

	return true;
}

// ---------------------------------------------------------
update_status ModulePhysics3D::PreUpdate(float dt)
{
	world->stepSimulation(dt, 15);

	int numManifolds = world->getDispatcher()->getNumManifolds();
	for (int i = 0; i<numManifolds; i++)
	{
		btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i);
		btCollisionObject* obA = (btCollisionObject*)(contactManifold->getBody0());
		btCollisionObject* obB = (btCollisionObject*)(contactManifold->getBody1());

		int numContacts = contactManifold->getNumContacts();
		if (numContacts > 0)
		{
			PhysBody3D* pbodyA = (PhysBody3D*)obA->getUserPointer();
			PhysBody3D* pbodyB = (PhysBody3D*)obB->getUserPointer();

			if (pbodyA && pbodyB)
			{

				list<Module*>::iterator item = pbodyA->collision_listeners.begin();
				while (item != pbodyA->collision_listeners.end())
				{
					(*item)->OnCollision(pbodyA, pbodyB);
					item++;
				}

				item = pbodyB->collision_listeners.begin();
				while (item != pbodyB->collision_listeners.end())
				{
					(*item)->OnCollision(pbodyB, pbodyA);
					item++;
				}
			}
		}
	}

	return UPDATE_CONTINUE;
}

// ---------------------------------------------------------
update_status ModulePhysics3D::Update(float dt)
{
	if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
		debug = !debug;

	if (debug == true)
	{
		world->debugDrawWorld();

		// Render vehicles
		list<PhysVehicle3D*>::iterator item = vehicles.begin();
		while (item != vehicles.end())
		{
			(*item)->Render();
			item++;
		}

		if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN)
		{
			PSphere s(1);
			s.SetPos(App->camera->Position.x, App->camera->Position.y, App->camera->Position.z);
			float force = 30.0f;
			AddBody(s)->Push(-(App->camera->Z.x * force), -(App->camera->Z.y * force), -(App->camera->Z.z * force));
		}
	}

	return UPDATE_CONTINUE;
}

// ---------------------------------------------------------
update_status ModulePhysics3D::PostUpdate(float dt)
{
	return UPDATE_CONTINUE;
}

// Called before quitting
bool ModulePhysics3D::CleanUp()
{
	LOG("Destroying 3D Physics simulation");

	// Remove from the world all collision bodies
	for (int i = world->getNumCollisionObjects() - 1; i >= 0; i--)
	{
		btCollisionObject* obj = world->getCollisionObjectArray()[i];
		world->removeCollisionObject(obj);
	}

	for (list<btTypedConstraint*>::iterator item = constraints.begin(); item != constraints.end(); item++)
	{
		world->removeConstraint(*item);
		delete (*item);
	}

	constraints.clear();

	for (list<btDefaultMotionState*>::iterator item = motions.begin(); item != motions.end(); item++)
		delete (*item);

	motions.clear();

	for (list<btCollisionShape*>::iterator item = shapes.begin(); item != shapes.end(); item++)
		delete (*item);

	shapes.clear();

	for (list<PhysBody3D*>::iterator item = bodies.begin(); item != bodies.end(); item++)
		delete (*item);

	bodies.clear();

	for (list<PhysVehicle3D*>::iterator item = vehicles.begin(); item != vehicles.end(); item++)
		delete (*item);

	vehicles.clear();

	delete vehicle_raycaster;
	delete world;

	return true;
}

// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PSphere& sphere, float mass)
{
	btCollisionShape* colShape = new btSphereShape(sphere.radius);
	shapes.push_back(colShape);

	btTransform startTransform;
	startTransform.setFromOpenGLMatrix(&sphere.transform);

	btVector3 localInertia(0, 0, 0);
	if (mass != 0.f)
		colShape->calculateLocalInertia(mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
	motions.push_back(myMotionState);
	btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);

	btRigidBody* body = new btRigidBody(rbInfo);
	PhysBody3D* pbody = new PhysBody3D(body);

	world->addRigidBody(body);
	bodies.push_back(pbody);

	return pbody;
}

// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PCube& cube, float mass)
{
	btCollisionShape* colShape = new btBoxShape(btVector3(cube.size.x*0.5f, cube.size.y*0.5f, cube.size.z*0.5f));
	shapes.push_back(colShape);

	btTransform startTransform;
	startTransform.setFromOpenGLMatrix(&cube.transform);

	btVector3 localInertia(0, 0, 0);
	if (mass != 0.f)
		colShape->calculateLocalInertia(mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
	motions.push_back(myMotionState);
	btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);

	btRigidBody* body = new btRigidBody(rbInfo);
	PhysBody3D* pbody = new PhysBody3D(body);

	world->addRigidBody(body);
	bodies.push_back(pbody);

	return pbody;
}

// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PCylinder& cylinder, float mass)
{
	btCollisionShape* colShape = new btCylinderShapeX(btVector3(cylinder.height*0.5f, cylinder.radius, 0.0f));
	shapes.push_back(colShape);

	btTransform startTransform;
	startTransform.setFromOpenGLMatrix(&cylinder.transform);

	btVector3 localInertia(0, 0, 0);
	if (mass != 0.f)
		colShape->calculateLocalInertia(mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
	motions.push_back(myMotionState);
	btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);

	btRigidBody* body = new btRigidBody(rbInfo);
	PhysBody3D* pbody = new PhysBody3D(body);

	world->addRigidBody(body);
	bodies.push_back(pbody);

	return pbody;
}

// ---------------------------------------------------------
PhysVehicle3D* ModulePhysics3D::AddVehicle(const VehicleInfo& info)
{
	btCompoundShape* comShape = new btCompoundShape();
	shapes.push_back(comShape);

	btCollisionShape* colShape = new btBoxShape(btVector3(info.chassis_size.x*0.5f, info.chassis_size.y*0.5f, info.chassis_size.z*0.5f));
	shapes.push_back(colShape);

	btTransform trans;
	trans.setIdentity();
	trans.setOrigin(btVector3(info.chassis_offset.x, info.chassis_offset.y, info.chassis_offset.z));

	comShape->addChildShape(trans, colShape);

	btTransform startTransform;
	startTransform.setIdentity();

	btVector3 localInertia(0, 0, 0);
	comShape->calculateLocalInertia(info.mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
	btRigidBody::btRigidBodyConstructionInfo rbInfo(info.mass, myMotionState, comShape, localInertia);

	btRigidBody* body = new btRigidBody(rbInfo);
	body->setContactProcessingThreshold(BT_LARGE_FLOAT);
	body->setActivationState(DISABLE_DEACTIVATION);

	world->addRigidBody(body);

	btRaycastVehicle::btVehicleTuning tuning;
	tuning.m_frictionSlip = info.frictionSlip;
	tuning.m_maxSuspensionForce = info.maxSuspensionForce;
	tuning.m_maxSuspensionTravelCm = info.maxSuspensionTravelCm;
	tuning.m_suspensionCompression = info.suspensionCompression;
	tuning.m_suspensionDamping = info.suspensionDamping;
	tuning.m_suspensionStiffness = info.suspensionStiffness;

	btRaycastVehicle* vehicle = new btRaycastVehicle(tuning, body, vehicle_raycaster);

	vehicle->setCoordinateSystem(0, 1, 2);

	for (int i = 0; i < info.num_wheels; ++i)
	{
		btVector3 conn(info.wheels[i].connection.x, info.wheels[i].connection.y, info.wheels[i].connection.z);
		btVector3 dir(info.wheels[i].direction.x, info.wheels[i].direction.y, info.wheels[i].direction.z);
		btVector3 axis(info.wheels[i].axis.x, info.wheels[i].axis.y, info.wheels[i].axis.z);

		vehicle->addWheel(conn, dir, axis, info.wheels[i].suspensionRestLength, info.wheels[i].radius, tuning, info.wheels[i].front);
	}
	// ---------------------

	PhysVehicle3D* pvehicle = new PhysVehicle3D(body, vehicle, info);
	world->addVehicle(vehicle);
	vehicles.push_back(pvehicle);

	return pvehicle;
}

// ---------------------------------------------------------
void ModulePhysics3D::AddConstraintP2P(PhysBody3D& bodyA, PhysBody3D& bodyB, const vec3& anchorA, const vec3& anchorB)
{
	btTypedConstraint* p2p = new btPoint2PointConstraint(
		*(bodyA.body),
		*(bodyB.body),
		btVector3(anchorA.x, anchorA.y, anchorA.z),
		btVector3(anchorB.x, anchorB.y, anchorB.z));
	world->addConstraint(p2p);
	constraints.push_back(p2p);
	p2p->setDbgDrawSize(2.0f);
}

void ModulePhysics3D::AddConstraintHinge(PhysBody3D& bodyA, PhysBody3D& bodyB, const vec3& anchorA, const vec3& anchorB, const vec3& axisA, const vec3& axisB, bool disable_collision)
{
	btHingeConstraint* hinge = new btHingeConstraint(
		*(bodyA.body),
		*(bodyB.body),
		btVector3(anchorA.x, anchorA.y, anchorA.z),
		btVector3(anchorB.x, anchorB.y, anchorB.z),
		btVector3(axisA.x, axisA.y, axisA.z),
		btVector3(axisB.x, axisB.y, axisB.z));

	world->addConstraint(hinge, disable_collision);
	constraints.push_back(hinge);
	hinge->setDbgDrawSize(2.0f);
}

// =============================================
void DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
{
	line.origin.Set(from.getX(), from.getY(), from.getZ());
	line.destination.Set(to.getX(), to.getY(), to.getZ());
	line.color.Set(color.getX(), color.getY(), color.getZ());
	line.Render();
}

void DebugDrawer::drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
{
	point.transform.translate(PointOnB.getX(), PointOnB.getY(), PointOnB.getZ());
	point.color.Set(color.getX(), color.getY(), color.getZ());
	point.Render();
}

void DebugDrawer::reportErrorWarning(const char* warningString)
{
	LOG("Bullet warning: %s", warningString);
}

void DebugDrawer::draw3dText(const btVector3& location, const char* textString)
{
	LOG("Bullet draw text: %s", textString);
}

void DebugDrawer::setDebugMode(int debugMode)
{
	mode = (DebugDrawModes)debugMode;
}

int	 DebugDrawer::getDebugMode() const
{
	return mode;
}
<commit_msg>Cleaning leaks<commit_after>#include "Globals.h"
#include "Application.h"
#include "ModulePhysics3D.h"
#include "PhysBody3D.h"
#include "PhysVehicle3D.h"
#include "Primitive.h"
#include "ModuleCamera3D.h"
#include "ModuleInput.h"

#ifdef _DEBUG
#pragma comment (lib, "Bullet/libx86/Debug/BulletDynamics_debug.lib")
#pragma comment (lib, "Bullet/libx86/Debug/BulletCollision_debug.lib")
#pragma comment (lib, "Bullet/libx86/Debug/LinearMath_debug.lib")
#else
#pragma comment (lib, "Bullet/libx86/Release/BulletDynamics.lib")
#pragma comment (lib, "Bullet/libx86/Release/BulletCollision.lib")
#pragma comment (lib, "Bullet/libx86/Release/LinearMath.lib")
#endif

using namespace std;

ModulePhysics3D::ModulePhysics3D(Application* app, const char* name, bool start_enabled) : Module(app, name, start_enabled)
{
	debug = true;

	collision_conf = new btDefaultCollisionConfiguration();
	dispatcher = new btCollisionDispatcher(collision_conf);
	broad_phase = new btDbvtBroadphase();
	solver = new btSequentialImpulseConstraintSolver();
	debug_draw = new DebugDrawer();
}

// Destructor
ModulePhysics3D::~ModulePhysics3D()
{
	delete debug_draw;
	delete solver;
	delete broad_phase;
	delete dispatcher;
	delete collision_conf;
}

// Render not available yet----------------------------------
bool ModulePhysics3D::Init(cJSON* node)
{
	LOG("Creating 3D Physics simulation");
	bool ret = true;

	return ret;
}

// ---------------------------------------------------------
bool ModulePhysics3D::Start()
{
	LOG("Creating Physics environment");
/*
	world = new btDiscreteDynamicsWorld(dispatcher, broad_phase, solver, collision_conf);
	//world->setDebugDrawer(debug_draw);
	world->setGravity(GRAVITY);
	vehicle_raycaster = new btDefaultVehicleRaycaster(world);

	// Big plane as ground
	{
		btCollisionShape* colShape = new btStaticPlaneShape(btVector3(0, 1, 0), 0);

		btDefaultMotionState* myMotionState = new btDefaultMotionState();
		btRigidBody::btRigidBodyConstructionInfo rbInfo(0.0f, myMotionState, colShape);

		//btRigidBody* body = new btRigidBody(rbInfo);
		//world->addRigidBody(body);
	}
	*/
	return true;
}

// ---------------------------------------------------------
update_status ModulePhysics3D::PreUpdate(float dt)
{
	/*world->stepSimulation(dt, 15);

	int numManifolds = world->getDispatcher()->getNumManifolds();
	for (int i = 0; i<numManifolds; i++)
	{
		btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i);
		btCollisionObject* obA = (btCollisionObject*)(contactManifold->getBody0());
		btCollisionObject* obB = (btCollisionObject*)(contactManifold->getBody1());

		int numContacts = contactManifold->getNumContacts();
		if (numContacts > 0)
		{
			PhysBody3D* pbodyA = (PhysBody3D*)obA->getUserPointer();
			PhysBody3D* pbodyB = (PhysBody3D*)obB->getUserPointer();

			if (pbodyA && pbodyB)
			{

				list<Module*>::iterator item = pbodyA->collision_listeners.begin();
				while (item != pbodyA->collision_listeners.end())
				{
					(*item)->OnCollision(pbodyA, pbodyB);
					item++;
				}

				item = pbodyB->collision_listeners.begin();
				while (item != pbodyB->collision_listeners.end())
				{
					(*item)->OnCollision(pbodyB, pbodyA);
					item++;
				}
			}
		}
	}*/

	return UPDATE_CONTINUE;
}

// ---------------------------------------------------------
update_status ModulePhysics3D::Update(float dt)
{
	/*if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
		debug = !debug;

	if (debug == true)
	{
		world->debugDrawWorld();

		// Render vehicles
		list<PhysVehicle3D*>::iterator item = vehicles.begin();
		while (item != vehicles.end())
		{
			(*item)->Render();
			item++;
		}

		if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN)
		{
			PSphere s(1);
			s.SetPos(App->camera->Position.x, App->camera->Position.y, App->camera->Position.z);
			float force = 30.0f;
			AddBody(s)->Push(-(App->camera->Z.x * force), -(App->camera->Z.y * force), -(App->camera->Z.z * force));
		}
	}*/

	return UPDATE_CONTINUE;
}

// ---------------------------------------------------------
update_status ModulePhysics3D::PostUpdate(float dt)
{
	return UPDATE_CONTINUE;
}

// Called before quitting
bool ModulePhysics3D::CleanUp()
{
	LOG("Destroying 3D Physics simulation");

	// Remove from the world all collision bodies
	/*for (int i = world->getNumCollisionObjects() - 1; i >= 0; i--)
	{
		btCollisionObject* obj = world->getCollisionObjectArray()[i];
		world->removeCollisionObject(obj);
	}

	for (list<btTypedConstraint*>::iterator item = constraints.begin(); item != constraints.end(); item++)
	{
		world->removeConstraint(*item);
		delete (*item);
	}

	constraints.clear();

	for (list<btDefaultMotionState*>::iterator item = motions.begin(); item != motions.end(); item++)
		delete (*item);

	motions.clear();

	for (list<btCollisionShape*>::iterator item = shapes.begin(); item != shapes.end(); item++)
		delete (*item);

	shapes.clear();

	for (list<PhysBody3D*>::iterator item = bodies.begin(); item != bodies.end(); item++)
		delete (*item);

	bodies.clear();

	for (list<PhysVehicle3D*>::iterator item = vehicles.begin(); item != vehicles.end(); item++)
		delete (*item);

	vehicles.clear();

	delete vehicle_raycaster;
	delete world;*/

	return true;
}

// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PSphere& sphere, float mass)
{
	btCollisionShape* colShape = new btSphereShape(sphere.radius);
	shapes.push_back(colShape);

	btTransform startTransform;
	startTransform.setFromOpenGLMatrix(&sphere.transform);

	btVector3 localInertia(0, 0, 0);
	if (mass != 0.f)
		colShape->calculateLocalInertia(mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
	motions.push_back(myMotionState);
	btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);

	btRigidBody* body = new btRigidBody(rbInfo);
	PhysBody3D* pbody = new PhysBody3D(body);

	world->addRigidBody(body);
	bodies.push_back(pbody);

	return pbody;
}

// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PCube& cube, float mass)
{
	btCollisionShape* colShape = new btBoxShape(btVector3(cube.size.x*0.5f, cube.size.y*0.5f, cube.size.z*0.5f));
	shapes.push_back(colShape);

	btTransform startTransform;
	startTransform.setFromOpenGLMatrix(&cube.transform);

	btVector3 localInertia(0, 0, 0);
	if (mass != 0.f)
		colShape->calculateLocalInertia(mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
	motions.push_back(myMotionState);
	btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);

	btRigidBody* body = new btRigidBody(rbInfo);
	PhysBody3D* pbody = new PhysBody3D(body);

	world->addRigidBody(body);
	bodies.push_back(pbody);

	return pbody;
}

// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PCylinder& cylinder, float mass)
{
	btCollisionShape* colShape = new btCylinderShapeX(btVector3(cylinder.height*0.5f, cylinder.radius, 0.0f));
	shapes.push_back(colShape);

	btTransform startTransform;
	startTransform.setFromOpenGLMatrix(&cylinder.transform);

	btVector3 localInertia(0, 0, 0);
	if (mass != 0.f)
		colShape->calculateLocalInertia(mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
	motions.push_back(myMotionState);
	btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);

	btRigidBody* body = new btRigidBody(rbInfo);
	PhysBody3D* pbody = new PhysBody3D(body);

	world->addRigidBody(body);
	bodies.push_back(pbody);

	return pbody;
}

// ---------------------------------------------------------
PhysVehicle3D* ModulePhysics3D::AddVehicle(const VehicleInfo& info)
{
	btCompoundShape* comShape = new btCompoundShape();
	shapes.push_back(comShape);

	btCollisionShape* colShape = new btBoxShape(btVector3(info.chassis_size.x*0.5f, info.chassis_size.y*0.5f, info.chassis_size.z*0.5f));
	shapes.push_back(colShape);

	btTransform trans;
	trans.setIdentity();
	trans.setOrigin(btVector3(info.chassis_offset.x, info.chassis_offset.y, info.chassis_offset.z));

	comShape->addChildShape(trans, colShape);

	btTransform startTransform;
	startTransform.setIdentity();

	btVector3 localInertia(0, 0, 0);
	comShape->calculateLocalInertia(info.mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
	btRigidBody::btRigidBodyConstructionInfo rbInfo(info.mass, myMotionState, comShape, localInertia);

	btRigidBody* body = new btRigidBody(rbInfo);
	body->setContactProcessingThreshold(BT_LARGE_FLOAT);
	body->setActivationState(DISABLE_DEACTIVATION);

	world->addRigidBody(body);

	btRaycastVehicle::btVehicleTuning tuning;
	tuning.m_frictionSlip = info.frictionSlip;
	tuning.m_maxSuspensionForce = info.maxSuspensionForce;
	tuning.m_maxSuspensionTravelCm = info.maxSuspensionTravelCm;
	tuning.m_suspensionCompression = info.suspensionCompression;
	tuning.m_suspensionDamping = info.suspensionDamping;
	tuning.m_suspensionStiffness = info.suspensionStiffness;

	btRaycastVehicle* vehicle = new btRaycastVehicle(tuning, body, vehicle_raycaster);

	vehicle->setCoordinateSystem(0, 1, 2);

	for (int i = 0; i < info.num_wheels; ++i)
	{
		btVector3 conn(info.wheels[i].connection.x, info.wheels[i].connection.y, info.wheels[i].connection.z);
		btVector3 dir(info.wheels[i].direction.x, info.wheels[i].direction.y, info.wheels[i].direction.z);
		btVector3 axis(info.wheels[i].axis.x, info.wheels[i].axis.y, info.wheels[i].axis.z);

		vehicle->addWheel(conn, dir, axis, info.wheels[i].suspensionRestLength, info.wheels[i].radius, tuning, info.wheels[i].front);
	}
	// ---------------------

	PhysVehicle3D* pvehicle = new PhysVehicle3D(body, vehicle, info);
	world->addVehicle(vehicle);
	vehicles.push_back(pvehicle);

	return pvehicle;
}

// ---------------------------------------------------------
void ModulePhysics3D::AddConstraintP2P(PhysBody3D& bodyA, PhysBody3D& bodyB, const vec3& anchorA, const vec3& anchorB)
{
	btTypedConstraint* p2p = new btPoint2PointConstraint(
		*(bodyA.body),
		*(bodyB.body),
		btVector3(anchorA.x, anchorA.y, anchorA.z),
		btVector3(anchorB.x, anchorB.y, anchorB.z));
	world->addConstraint(p2p);
	constraints.push_back(p2p);
	p2p->setDbgDrawSize(2.0f);
}

void ModulePhysics3D::AddConstraintHinge(PhysBody3D& bodyA, PhysBody3D& bodyB, const vec3& anchorA, const vec3& anchorB, const vec3& axisA, const vec3& axisB, bool disable_collision)
{
	btHingeConstraint* hinge = new btHingeConstraint(
		*(bodyA.body),
		*(bodyB.body),
		btVector3(anchorA.x, anchorA.y, anchorA.z),
		btVector3(anchorB.x, anchorB.y, anchorB.z),
		btVector3(axisA.x, axisA.y, axisA.z),
		btVector3(axisB.x, axisB.y, axisB.z));

	world->addConstraint(hinge, disable_collision);
	constraints.push_back(hinge);
	hinge->setDbgDrawSize(2.0f);
}

// =============================================
void DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
{
	line.origin.Set(from.getX(), from.getY(), from.getZ());
	line.destination.Set(to.getX(), to.getY(), to.getZ());
	line.color.Set(color.getX(), color.getY(), color.getZ());
	line.Render();
}

void DebugDrawer::drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
{
	point.transform.translate(PointOnB.getX(), PointOnB.getY(), PointOnB.getZ());
	point.color.Set(color.getX(), color.getY(), color.getZ());
	point.Render();
}

void DebugDrawer::reportErrorWarning(const char* warningString)
{
	LOG("Bullet warning: %s", warningString);
}

void DebugDrawer::draw3dText(const btVector3& location, const char* textString)
{
	LOG("Bullet draw text: %s", textString);
}

void DebugDrawer::setDebugMode(int debugMode)
{
	mode = (DebugDrawModes)debugMode;
}

int	 DebugDrawer::getDebugMode() const
{
	return mode;
}
<|endoftext|>


<commit_before>/**
 * @file lars.hpp
 * @author Nishant Mehta (niche)
 *
 * Definition of the LARS class, which performs Least Angle Regression and the
 * LASSO.
 */
#ifndef __MLPACK_METHODS_LARS_LARS_HPP
#define __MLPACK_METHODS_LARS_LARS_HPP

#include <armadillo>
#include <mlpack/core.hpp>

#define EPS 1e-16

namespace mlpack {
namespace lars {

// beta is the estimator
// yHat is the prediction from the current estimator

/**
 * An implementation of LARS, a stage-wise homotopy-based algorithm for
 * l1 regularized linear regression (LASSO) and l1+l2 regularized linear
 * regression (Elastic Net).
 * Let X be a matrix where each row is a point and each column is a dimension,
 * and let y be a vector of targets.
 * The Elastic Net problem is to solve
 * min_beta ||X beta - y||_2^2 + lambda_1 ||beta||_1 + 0.5 lambda_2 ||beta||_2^2
 * If lambda_1 > 0, lambda_2 = 0, the problem is the LASSO.
 * If lambda_1 > 0, lambda_2 > 0, the problem is the Elastic Net.
 * If lambda_1 = 0, lambda_2 > 0, the problem is Ridge Regression.
 * If lambda_1 = 0, lambda_2 = 0, the problem is unregularized linear regression.
 *
 * Note: This algorithm is not recommended for use (in terms of efficiency)
 * when lambda_1 = 0.
 *
 * Only minor modifications are necessary to handle the constrained version of
 * the problem:
 *   min_beta ||X beta - y||_2^2 + 0.5 lambda_2 ||beta||_2^2
 *   subject to ||beta||_1 <= tau
 * Although this option currently is not implemented, it will be implemented
 * very soon.
 *
 * For more details, see the following papers:
 *
 * @article{efron2004least,
 *   title={Least angle regression},
 *   author={Efron, B. and Hastie, T. and Johnstone, I. and Tibshirani, R.},
 *   journal={The Annals of statistics},
 *   volume={32},
 *   number={2},
 *   pages={407--499},
 *   year={2004},
 *   publisher={Institute of Mathematical Statistics}
 * }
 *
 * @article{zou2005regularization,
 *   title={Regularization and variable selection via the elastic net},
 *   author={Zou, H. and Hastie, T.},
 *   journal={Journal of the Royal Statistical Society Series B},
 *   volume={67},
 *   number={2},
 *   pages={301--320},
 *   year={2005},
 *   publisher={Royal Statistical Society}
 * }
 */
class LARS {

 public:

  LARS(const bool useCholesky);

  LARS(const bool useCholesky,
       const double lambda1);

  LARS(const bool useCholesky,
       const double lambda1,
       const double lambda2);

  ~LARS() { }

  void SetGram(const arma::mat& matGram);

  void ComputeGram(const arma::mat& matX);

  const std::vector<arma::u32> ActiveSet();

  const std::vector<arma::vec> BetaPath();

  const std::vector<double> LambdaPath();

  const arma::mat MatUtriCholFactor();

  void DoLARS(const arma::mat& matX, const arma::vec& y);

  void Solution(arma::vec& beta);

private:
  arma::mat matGram;

  // Upper triangular cholesky factor; initially 0x0 arma::matrix.
  arma::mat matUtriCholFactor;

  bool useCholesky;

  bool lasso;
  double lambda1;

  bool elasticNet;
  double lambda2;

  std::vector<arma::vec> betaPath;
  std::vector<double> lambdaPath;

  arma::u32 nActive;
  std::vector<arma::u32> activeSet;
  std::vector<bool> isActive;

  void Deactivate(arma::u32 activeVarInd);

  void Activate(arma::u32 varInd);

  void ComputeYHatDirection(const arma::mat& matX,
			    const arma::vec& betaDirection,
                            arma::vec& yHatDirection);

  void InterpolateBeta();

  void CholeskyInsert(const arma::vec& newX, const arma::mat& X);

  void CholeskyInsert(const arma::vec& newX, const arma::vec& newGramCol);

  void GivensRotate(const arma::vec& x, arma::vec& rotatedX, arma::mat& G);

  void CholeskyDelete(arma::u32 colToKill);

};

}; // namespace lars
}; // namespace mlpack

#endif
<commit_msg>added some comments to LARS<commit_after>/**
 * @file lars.hpp
 * @author Nishant Mehta (niche)
 *
 * Definition of the LARS class, which performs Least Angle Regression and the
 * LASSO.
 */
#ifndef __MLPACK_METHODS_LARS_LARS_HPP
#define __MLPACK_METHODS_LARS_LARS_HPP

#include <armadillo>
#include <mlpack/core.hpp>

#define EPS 1e-16

namespace mlpack {
namespace lars {

// beta is the estimator
// yHat is the prediction from the current estimator

/**
 * An implementation of LARS, a stage-wise homotopy-based algorithm for
 * l1 regularized linear regression (LASSO) and l1+l2 regularized linear
 * regression (Elastic Net).
 * Let X be a matrix where each row is a point and each column is a dimension,
 * and let y be a vector of targets.
 * The Elastic Net problem is to solve
 * min_beta ||X beta - y||_2^2 + lambda_1 ||beta||_1 + 0.5 lambda_2 ||beta||_2^2
 * If lambda_1 > 0, lambda_2 = 0, the problem is the LASSO.
 * If lambda_1 > 0, lambda_2 > 0, the problem is the Elastic Net.
 * If lambda_1 = 0, lambda_2 > 0, the problem is Ridge Regression.
 * If lambda_1 = 0, lambda_2 = 0, the problem is unregularized linear regression.
 *
 * Note: This algorithm is not recommended for use (in terms of efficiency)
 * when lambda_1 = 0.
 *
 * Only minor modifications are necessary to handle the constrained version of
 * the problem:
 *   min_beta ||X beta - y||_2^2 + 0.5 lambda_2 ||beta||_2^2
 *   subject to ||beta||_1 <= tau
 * Although this option currently is not implemented, it will be implemented
 * very soon.
 *
 * For more details, see the following papers:
 *
 * @article{efron2004least,
 *   title={Least angle regression},
 *   author={Efron, B. and Hastie, T. and Johnstone, I. and Tibshirani, R.},
 *   journal={The Annals of statistics},
 *   volume={32},
 *   number={2},
 *   pages={407--499},
 *   year={2004},
 *   publisher={Institute of Mathematical Statistics}
 * }
 *
 * @article{zou2005regularization,
 *   title={Regularization and variable selection via the elastic net},
 *   author={Zou, H. and Hastie, T.},
 *   journal={Journal of the Royal Statistical Society Series B},
 *   volume={67},
 *   number={2},
 *   pages={301--320},
 *   year={2005},
 *   publisher={Royal Statistical Society}
 * }
 */
class LARS {

 public:

  /**
   * Set the parameters to LARS
   * Both lambda1 and lambda2 default to 0
   *
   * @param useCholesky Whether or not to use Cholesky decomposition when
   *    solving linear system. If no, compute full Gram matrix at beginning.
   * @param lambda1 Regularization parameter for l_1-norm penalty
   */
  LARS(const bool useCholesky);

  /**
   * Set the parameters to LARS
   * lambda2 defaults to 0
   *
   * @param useCholesky Whether or not to use Cholesky decomposition when
   *    solving linear system. If no, compute full Gram matrix at beginning.
   * @param lambda1 Regularization parameter for l_1-norm penalty
   */
  LARS(const bool useCholesky,
       const double lambda1);

  /**
   * Set the parameters to LARS
   *
   * @param useCholesky Whether or not to use Cholesky decomposition when
   *    solving linear system. If no, compute full Gram matrix at beginning.
   * @param lambda1 Regularization parameter for l_1-norm penalty
   * @param lambda2 Regularization parameter for l_2-norm penalty
   */
  LARS(const bool useCholesky,
       const double lambda1,
       const double lambda2);

  ~LARS() { }

  /*
   * Set the Gram matrix (done before calling DoLars)
   *
   * @param matGram Matrix to which to set Gram matrix
   */
  void SetGram(const arma::mat& matGram);

  /*
   * Compute Gram matrix. If elastic net, add lambda2 * identity to diagonal.
   *
   * @param matX Data matrix to use for computing Gram matrix
   */
  void ComputeGram(const arma::mat& matX);

  /*
   * Accessor for activeSet
   */
  const std::vector<arma::u32> ActiveSet();

  /*
   * Accessor for betaPath
   */
  const std::vector<arma::vec> BetaPath();

  /*
   * Accessor for lambdaPath
   */
  const std::vector<double> LambdaPath();

  /*
   * Accessor for matUtriCholFactor
   */
  const arma::mat MatUtriCholFactor();

  /*
   * Do LARS
   */
  void DoLARS(const arma::mat& matX, const arma::vec& y);

  /*
   * Load the solution vector, which is the last vector from the solution path
   */
  void Solution(arma::vec& beta);

private:
  arma::mat matGram;

  // Upper triangular cholesky factor; initially 0x0 arma::matrix.
  arma::mat matUtriCholFactor;

  bool useCholesky;

  bool lasso;
  double lambda1;

  bool elasticNet;
  double lambda2;

  std::vector<arma::vec> betaPath;
  std::vector<double> lambdaPath;

  arma::u32 nActive;
  std::vector<arma::u32> activeSet;
  std::vector<bool> isActive;

  void Deactivate(arma::u32 activeVarInd);

  void Activate(arma::u32 varInd);

  void ComputeYHatDirection(const arma::mat& matX,
			    const arma::vec& betaDirection,
                            arma::vec& yHatDirection);

  void InterpolateBeta();

  void CholeskyInsert(const arma::vec& newX, const arma::mat& X);

  void CholeskyInsert(const arma::vec& newX, const arma::vec& newGramCol);

  void GivensRotate(const arma::vec& x, arma::vec& rotatedX, arma::mat& G);

  void CholeskyDelete(arma::u32 colToKill);

};

}; // namespace lars
}; // namespace mlpack

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX
#define INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX

#include <vcl/dialog.hxx>
#include <svtools/editsyntaxhighlighter.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
#include <deque>

#include <com/sun/star/sdbc/XConnection.hpp>
#include <unotools/eventlisteneradapter.hxx>
#include "moduledbu.hxx"
#include <osl/mutex.hxx>

#include <svtools/editbrowsebox.hxx>

namespace dbaui
{

    // DirectSQLDialog
    class DirectSQLDialog
            :public ModalDialog
            ,public ::utl::OEventListenerAdapter
    {
    protected:
        OModuleClient m_aModuleClient;
        ::osl::Mutex    m_aMutex;

        MultiLineEditSyntaxHighlight*    m_pSQL;
        PushButton*       m_pExecute;
        ListBox*          m_pSQLHistory;
        VclMultiLineEdit* m_pStatus;
        CheckBox*         m_pShowOutput;
        VclMultiLineEdit* m_pOutput;
        HelpButton*       m_pHelp;
        PushButton*       m_pClose;

        typedef ::std::deque< OUString >  StringQueue;
        StringQueue     m_aStatementHistory;    // previous statements
        StringQueue     m_aNormalizedHistory;   // previous statements, normalized to be used in the list box

        sal_Int32       m_nHistoryLimit;
        sal_Int32       m_nStatusCount;

        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
                        m_xConnection;

    public:
        DirectSQLDialog(
            Window* _pParent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
        virtual ~DirectSQLDialog();

        /// number of history entries
        sal_Int32 getHistorySize() const;

    protected:
        void executeCurrent();
        void switchToHistory(sal_Int32 _nHistoryPos, bool _bUpdateListBox = true);

        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource ) SAL_OVERRIDE;

    protected:
        DECL_LINK( OnExecute, void* );
        DECL_LINK( OnClose, void* );
        DECL_LINK( OnListEntrySelected, void* );
        DECL_LINK( OnStatementModified, void* );

    private:
        /// adds a statement to the statement history
        void implAddToStatementHistory(const OUString& _rStatement);

        /// ensures that our history has at most m_nHistoryLimit entries
        void implEnsureHistoryLimit();

        /// executes the statement given, adds the status to the status list
        void implExecuteStatement(const OUString& _rStatement);

        /// adds a status text to the status list
        void addStatusText(const OUString& _rMessage);

        /// adds a status text to the output list
        void addOutputText(const OUString& _rMessage);

#ifdef DBG_UTIL
        const sal_Char* impl_CheckInvariants() const;
#endif
    };

#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname)    \
    {   \
        const sal_Char* pError = impl_CheckInvariants();    \
        if (pError) \
            SAL_WARN("dbaccess.ui", methodname << ": " << pError);   \
    }
#else
#define CHECK_INVARIANTS(methodname)
#endif

}   // namespace dbaui

#endif // INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1210197 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX
#define INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX

#include <vcl/dialog.hxx>
#include <svtools/editsyntaxhighlighter.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
#include <deque>

#include <com/sun/star/sdbc/XConnection.hpp>
#include <unotools/eventlisteneradapter.hxx>
#include "moduledbu.hxx"
#include <osl/mutex.hxx>

#include <svtools/editbrowsebox.hxx>

namespace dbaui
{

    // DirectSQLDialog
    class DirectSQLDialog
            :public ModalDialog
            ,public ::utl::OEventListenerAdapter
    {
    protected:
        OModuleClient m_aModuleClient;
        ::osl::Mutex    m_aMutex;

        MultiLineEditSyntaxHighlight*    m_pSQL;
        PushButton*       m_pExecute;
        ListBox*          m_pSQLHistory;
        VclMultiLineEdit* m_pStatus;
        CheckBox*         m_pShowOutput;
        VclMultiLineEdit* m_pOutput;
        PushButton*       m_pClose;

        typedef ::std::deque< OUString >  StringQueue;
        StringQueue     m_aStatementHistory;    // previous statements
        StringQueue     m_aNormalizedHistory;   // previous statements, normalized to be used in the list box

        sal_Int32       m_nHistoryLimit;
        sal_Int32       m_nStatusCount;

        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
                        m_xConnection;

    public:
        DirectSQLDialog(
            Window* _pParent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
        virtual ~DirectSQLDialog();

        /// number of history entries
        sal_Int32 getHistorySize() const;

    protected:
        void executeCurrent();
        void switchToHistory(sal_Int32 _nHistoryPos, bool _bUpdateListBox = true);

        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource ) SAL_OVERRIDE;

    protected:
        DECL_LINK( OnExecute, void* );
        DECL_LINK( OnClose, void* );
        DECL_LINK( OnListEntrySelected, void* );
        DECL_LINK( OnStatementModified, void* );

    private:
        /// adds a statement to the statement history
        void implAddToStatementHistory(const OUString& _rStatement);

        /// ensures that our history has at most m_nHistoryLimit entries
        void implEnsureHistoryLimit();

        /// executes the statement given, adds the status to the status list
        void implExecuteStatement(const OUString& _rStatement);

        /// adds a status text to the status list
        void addStatusText(const OUString& _rMessage);

        /// adds a status text to the output list
        void addOutputText(const OUString& _rMessage);

#ifdef DBG_UTIL
        const sal_Char* impl_CheckInvariants() const;
#endif
    };

#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname)    \
    {   \
        const sal_Char* pError = impl_CheckInvariants();    \
        if (pError) \
            SAL_WARN("dbaccess.ui", methodname << ": " << pError);   \
    }
#else
#define CHECK_INVARIANTS(methodname)
#endif

}   // namespace dbaui

#endif // INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>