<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file CanonControlLuaBindings.hpp Lua bindings for the CanonControl library
//
#pragma once

// includes
#include "Lua.hpp"
#include "Instance.hpp"
#include "RecursiveMutex.hpp"
#include "Event.hpp"
#include "Asio.hpp"
#include "ShutterReleaseSettings.hpp"
#include "RemoteReleaseControl.hpp"

// forward references
class SourceDevice;
class SourceInfo;
class DeviceProperty;
class ImageProperty;
class Viewfinder;
class BulbReleaseControl;

/// \brief Lua bindings for CanonControl library
/// \details Provides bindings for all classes and functions in the CanonControl
/// library. As soon as the object is destroyed, the bindings are deregistered. All
/// callback handlers registered are reset and won't be called anymore.
class CanonControlLuaBindings : public std::enable_shared_from_this<CanonControlLuaBindings>
{
public:
   /// function type to output debug strings
   typedef std::function<void(const CString&)> T_fnOutputDebugString;

   /// ctor; inits bindings
   CanonControlLuaBindings(Lua::State& state, boost::asio::io_service::strand& strand);

   /// dtor; cleans up bindings
   virtual ~CanonControlLuaBindings() throw();

   /// sets output debug string handler
   void SetOutputDebugStringHandler(T_fnOutputDebugString fnOutputDebugString)
   {
      m_fnOutputDebugString = fnOutputDebugString;
   }

   /// inits bindings to CanonControl; since the this parameter is needed in
   /// the bindings, call this immediately after the ctor
   void InitBindings();

   /// cancels all handlers of async operations
   void CancelHandlers();

   /// stops internal timer
   void StopTimer();

private:
   /// returns Lua state object
   Lua::State& GetState() throw() { return m_state; }

   /// inits constants used in various calls
   void InitConstants();

   /// inits constants for SourceDevice table
   void InitSourceDeviceConstants(Lua::Table& constants);

   /// inits constants for ImageProperty table
   void InitImagePropertyConstants(Lua::Table& constants);

   /// inits constants for ShootingMode table
   void InitShootingModeConstants(Lua::Table& constants);

   /// inits constants for ShutterReleaseSettings table
   void InitShutterReleaseSettingsConstants(Lua::Table& constants);

   /// inits constants for RemoteReleaseControl
   void InitRemoteReleaseControlConstants(Lua::Table& constants);

   /// inits constants for Viewfinder
   void InitViewfinderConstants(Lua::Table& constants);

   /// restarts timer for event handling
   void RestartEventTimer();

   /// cleans up all bindings
   void CleanupBindings();

   /// handler for timer used for event handling
   void OnTimerEventHandling(const boost::system::error_code& error);

   // Sys functions

   /// local instance = Sys:getInstance()
   std::vector<Lua::Value> SysGetInstance(Lua::State& state);

   // Instance functions

   /// local version = Instance:getVersion()
   std::vector<Lua::Value> InstanceGetVersion();

   /// local sourceInfoArray = instance:enumerateDevices()
   std::vector<Lua::Value> InstanceEnumerateDevices(Lua::State& state);

   /// instance:asyncWaitForCamera(callbackFunction)
   std::vector<Lua::Value> InstanceAsyncWaitForCamera(Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// method called when a camera has been connected
   void AsyncWaitForCamera_OnCameraConnected();

   // SourceInfo functions

   /// adds a source info table to given table
   /// { name = "camera name", function open() ... end }
   void AddSourceInfo(Lua::State& state, Lua::Table& table, size_t uiIndex, std::shared_ptr<SourceInfo> spSourceInfo);

   /// local sourceDevice = sourceInfo:open()
   std::vector<Lua::Value> SourceInfoOpen(std::shared_ptr<SourceInfo> spSourceInfo,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   // SourceDevice functions

   /// initializes SourceDevice table
   void InitSourceDeviceTable(std::shared_ptr<SourceDevice> spSourceDevice, Lua::Table& sourceDevice);

   /// local isCapable = sourceDevice:getDeviceCapability(Constants.SourceDevice.capXxx)
   std::vector<Lua::Value> SourceDeviceGetDeviceCapability(std::shared_ptr<SourceDevice> spSourceDevice,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// local arrayDeviceProps = sourceDevice:enumDeviceProperties()
   std::vector<Lua::Value> SourceDeviceEnumDeviceProperties(std::shared_ptr<SourceDevice> spSourceDevice,
      Lua::State& state);

   /// local deviceProperty = sourceDevice:getDeviceProperty()
   std::vector<Lua::Value> SourceDeviceGetDeviceProperty(std::shared_ptr<SourceDevice> spSourceDevice,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// adds a device property values to given table
   /// { id = "property id", name = "name", asString = "value", isReadOnly = true/false end }
   void AddDeviceProperty(Lua::Table& table, const DeviceProperty& deviceProperty, std::shared_ptr<SourceDevice> spSourceDevice);

   /// enters release control and returns RemoteReleaseControl table
   std::vector<Lua::Value> SourceDeviceEnterReleaseControl(std::shared_ptr<SourceDevice> spSourceDevice,
      Lua::State& state);

   // RemoteReleaseControl functions

   /// initializes RemoteReleaseControl table
   void InitRemoteReleaseControlTable(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, Lua::Table& remoteReleaseControl);

   /// local isCapable = remoteReleaseControl:getCapability(Constants.RemoteReleaseControl.capXxx)
   std::vector<Lua::Value> RemoteReleaseControlGetCapability(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// local releaseSettings = remoteReleaseControl:getReleaseSettings()
   std::vector<Lua::Value> RemoteReleaseControlGetReleaseSettings(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// initializes ReleaseSettings table
   void InitReleaseSettingsTable(Lua::State& state, const ShutterReleaseSettings& releaseSettings,
      Lua::Table& tableReleaseSettings);

   /// sets new release settings
   std::vector<Lua::Value> RemoteReleaseControlSetReleaseSettings(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// callback that is called when image has been transferred
   void SetReleaseSettings_OnFinishedTransfer(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      const ShutterReleaseSettings& releaseSettings);

   /// event handler for property change events
   void RemoteReleaseControl_PropertyEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      std::shared_ptr<int> spHandlerId,
      RemoteReleaseControl::T_enPropertyEvent,
      unsigned int eventData);

   /// local handlerId = remoteReleaseControl:addPropertyEventHandler(callbackFunction)
   std::vector<Lua::Value> RemoteReleaseControlAddPropertyEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// remoteReleaseControl:removePropertyEventHandler(handlerId)
   std::vector<Lua::Value> RemoteReleaseControlRemovePropertyEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// event handler for state events
   void RemoteReleaseControl_StateEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      std::shared_ptr<int> spHandlerId,
      RemoteReleaseControl::T_enStateEvent,
      unsigned int eventData);

   /// local handlerId = remoteReleaseControl:addStateEventHandler(callbackFunction)
   std::vector<Lua::Value> RemoteReleaseControlAddStateEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// remoteReleaseControl:removeStateEventHandler(handlerId)
   std::vector<Lua::Value> RemoteReleaseControlRemoveStateEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// event handler for download events
   void RemoteReleaseControl_DownloadEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      std::shared_ptr<int> spHandlerId,
      RemoteReleaseControl::T_enDownloadEvent,
      unsigned int eventData);

   /// local handlerId = remoteReleaseControl:addDownloadEventHandler(callbackFunction)
   std::vector<Lua::Value> RemoteReleaseControlAddDownloadEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// remoteReleaseControl:removeDownloadEventHandler(handlerId)
   std::vector<Lua::Value> RemoteReleaseControlRemoveDownloadEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// local imagePropertiesList = remoteReleaseControl:enumImageProperties()
   std::vector<Lua::Value> RemoteReleaseControlEnumImageProperties(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, Lua::State& state);

   /// local imageProperty = remoteReleaseControl:getImageProperty()
   std::vector<Lua::Value> RemoteReleaseControlGetImageProperty(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// local imageProperty = remoteReleaseControl:getImagePropertyByType(imagePropertyType)
   std::vector<Lua::Value> RemoteReleaseControlGetImagePropertyByType(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// local imageProperty = remoteReleaseControl:getShootingModeImageProperty(shootingMode)
   std::vector<Lua::Value> RemoteReleaseControlGetShootingModeImageProperty(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// adds ImageProperty table
   void AddImageProperty(Lua::Table& table, const ImageProperty& imageProperty,
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl);

   /// local viewfinder = remoteReleaseControl:startViewfinder()
   std::vector<Lua::Value> RemoteReleaseControlStartViewfinder(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, Lua::State& state);

   /// local numShots = remoteReleaseControl:numAvailableShots()
   std::vector<Lua::Value> RemoteReleaseControlNumAvailableShots(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl);

   /// remoteReleaseControl:sendCommand()
   std::vector<Lua::Value> RemoteReleaseControlSendCommand(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// remoteReleaseControl:release()
   std::vector<Lua::Value> RemoteReleaseControlRelease(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl);

   /// local bulbReleaseControl = remoteReleaseControl:startBulb()
   std::vector<Lua::Value> RemoteReleaseControlStartBulb(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, Lua::State& state);

   /// local remoteReleaseControl:close()
   std::vector<Lua::Value> RemoteReleaseControlClose(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl);

   // Viewfinder functions

   /// initializes viewfinder table
   void InitViewfinderTable(std::shared_ptr<Viewfinder> spViewfinder, Lua::Table& viewfinder);

   /// local isCapable = viewfinder:getCapability(Constants.Viewfinder.capXxx)
   std::vector<Lua::Value> ViewfinderGetCapability(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// viewfinder:setOutputType(outputType)
   std::vector<Lua::Value> ViewfinderSetOutputType(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// viewfinder:setAvailImageHandler(callbackFunction)
   std::vector<Lua::Value> ViewfinderSetAvailImageHandler(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// called when a new viewfinder image is available
   void SetAvailImageHandler_OnAvailImageHandler(std::shared_ptr<Viewfinder> spViewfinder,
      const std::vector<BYTE>& vecImage);

   // local histogram viewfinder:getHistogram(Constants.Viewfinder.historyXxx);
   std::vector<Lua::Value> ViewfinderGetHistogram(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// called to close viewfinder
   std::vector<Lua::Value> ViewfinderClose(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   // BulbReleaseControl functions

   /// initizalizes BulbReleaseControl table
   void InitBulbReleaseControlTable(std::shared_ptr<BulbReleaseControl> spBulbReleaseControl, Lua::Table& bulbReleaseControl);

   /// local elapsedTime = bulbReleaseControl:elapsedTime()
   std::vector<Lua::Value> BulbReleaseControlElapsedTime(std::shared_ptr<BulbReleaseControl> spBulbReleaseControl);

   /// bulbReleaseControl:stop()
   std::vector<Lua::Value> BulbReleaseControlStop(std::shared_ptr<BulbReleaseControl> spBulbReleaseControl);

private:
   /// Lua state
   Lua::State& m_state;

   /// CanonControl instance
   std::unique_ptr<Instance> m_upInstance;

   /// release settings stored for the script
   ShutterReleaseSettings m_releaseSettings;

   /// once Lua has connected to remote release control, a pointer is stored here
   std::shared_ptr<RemoteReleaseControl> m_spRemoteRelaseControl;

   /// set of all registered property handler ids
   std::set<int> m_setAllPropertyHandlerIds;

   /// set of all registered state handler ids
   std::set<int> m_setAllStateHandlerIds;

   /// set of all registered download handler ids
   std::set<int> m_setAllDownloadHandlerIds;

   /// once Lua script started viewfinder, a pointer is stored here
   std::shared_ptr<Viewfinder> m_spViewfinder;

   /// strand to execute all Lua calls on
   boost::asio::io_service::strand& m_strand;

   /// output debug string handler
   T_fnOutputDebugString m_fnOutputDebugString;

   /// mutex to protect AsyncWaitForCamera() handler to call Lua script multiple times
   RecursiveMutex m_mtxAsyncWaitForCamera_InScript;

   /// timer for event handling
   boost::asio::deadline_timer m_timerEventHandling;

   /// event that is set when the event handling timer has stopped
   Event m_evtTimerStopped;
};
<commit_msg>added doxygen comment for getHistory()<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file CanonControlLuaBindings.hpp Lua bindings for the CanonControl library
//
#pragma once

// includes
#include "Lua.hpp"
#include "Instance.hpp"
#include "RecursiveMutex.hpp"
#include "Event.hpp"
#include "Asio.hpp"
#include "ShutterReleaseSettings.hpp"
#include "RemoteReleaseControl.hpp"

// forward references
class SourceDevice;
class SourceInfo;
class DeviceProperty;
class ImageProperty;
class Viewfinder;
class BulbReleaseControl;

/// \brief Lua bindings for CanonControl library
/// \details Provides bindings for all classes and functions in the CanonControl
/// library. As soon as the object is destroyed, the bindings are deregistered. All
/// callback handlers registered are reset and won't be called anymore.
class CanonControlLuaBindings : public std::enable_shared_from_this<CanonControlLuaBindings>
{
public:
   /// function type to output debug strings
   typedef std::function<void(const CString&)> T_fnOutputDebugString;

   /// ctor; inits bindings
   CanonControlLuaBindings(Lua::State& state, boost::asio::io_service::strand& strand);

   /// dtor; cleans up bindings
   virtual ~CanonControlLuaBindings() throw();

   /// sets output debug string handler
   void SetOutputDebugStringHandler(T_fnOutputDebugString fnOutputDebugString)
   {
      m_fnOutputDebugString = fnOutputDebugString;
   }

   /// inits bindings to CanonControl; since the this parameter is needed in
   /// the bindings, call this immediately after the ctor
   void InitBindings();

   /// cancels all handlers of async operations
   void CancelHandlers();

   /// stops internal timer
   void StopTimer();

private:
   /// returns Lua state object
   Lua::State& GetState() throw() { return m_state; }

   /// inits constants used in various calls
   void InitConstants();

   /// inits constants for SourceDevice table
   void InitSourceDeviceConstants(Lua::Table& constants);

   /// inits constants for ImageProperty table
   void InitImagePropertyConstants(Lua::Table& constants);

   /// inits constants for ShootingMode table
   void InitShootingModeConstants(Lua::Table& constants);

   /// inits constants for ShutterReleaseSettings table
   void InitShutterReleaseSettingsConstants(Lua::Table& constants);

   /// inits constants for RemoteReleaseControl
   void InitRemoteReleaseControlConstants(Lua::Table& constants);

   /// inits constants for Viewfinder
   void InitViewfinderConstants(Lua::Table& constants);

   /// restarts timer for event handling
   void RestartEventTimer();

   /// cleans up all bindings
   void CleanupBindings();

   /// handler for timer used for event handling
   void OnTimerEventHandling(const boost::system::error_code& error);

   // Sys functions

   /// local instance = Sys:getInstance()
   std::vector<Lua::Value> SysGetInstance(Lua::State& state);

   // Instance functions

   /// local version = Instance:getVersion()
   std::vector<Lua::Value> InstanceGetVersion();

   /// local sourceInfoArray = instance:enumerateDevices()
   std::vector<Lua::Value> InstanceEnumerateDevices(Lua::State& state);

   /// instance:asyncWaitForCamera(callbackFunction)
   std::vector<Lua::Value> InstanceAsyncWaitForCamera(Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// method called when a camera has been connected
   void AsyncWaitForCamera_OnCameraConnected();

   // SourceInfo functions

   /// adds a source info table to given table
   /// { name = "camera name", function open() ... end }
   void AddSourceInfo(Lua::State& state, Lua::Table& table, size_t uiIndex, std::shared_ptr<SourceInfo> spSourceInfo);

   /// local sourceDevice = sourceInfo:open()
   std::vector<Lua::Value> SourceInfoOpen(std::shared_ptr<SourceInfo> spSourceInfo,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   // SourceDevice functions

   /// initializes SourceDevice table
   void InitSourceDeviceTable(std::shared_ptr<SourceDevice> spSourceDevice, Lua::Table& sourceDevice);

   /// local isCapable = sourceDevice:getDeviceCapability(Constants.SourceDevice.capXxx)
   std::vector<Lua::Value> SourceDeviceGetDeviceCapability(std::shared_ptr<SourceDevice> spSourceDevice,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// local arrayDeviceProps = sourceDevice:enumDeviceProperties()
   std::vector<Lua::Value> SourceDeviceEnumDeviceProperties(std::shared_ptr<SourceDevice> spSourceDevice,
      Lua::State& state);

   /// local deviceProperty = sourceDevice:getDeviceProperty()
   std::vector<Lua::Value> SourceDeviceGetDeviceProperty(std::shared_ptr<SourceDevice> spSourceDevice,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// adds a device property values to given table
   /// { id = "property id", name = "name", asString = "value", isReadOnly = true/false end }
   void AddDeviceProperty(Lua::Table& table, const DeviceProperty& deviceProperty, std::shared_ptr<SourceDevice> spSourceDevice);

   /// enters release control and returns RemoteReleaseControl table
   std::vector<Lua::Value> SourceDeviceEnterReleaseControl(std::shared_ptr<SourceDevice> spSourceDevice,
      Lua::State& state);

   // RemoteReleaseControl functions

   /// initializes RemoteReleaseControl table
   void InitRemoteReleaseControlTable(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, Lua::Table& remoteReleaseControl);

   /// local isCapable = remoteReleaseControl:getCapability(Constants.RemoteReleaseControl.capXxx)
   std::vector<Lua::Value> RemoteReleaseControlGetCapability(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// local releaseSettings = remoteReleaseControl:getReleaseSettings()
   std::vector<Lua::Value> RemoteReleaseControlGetReleaseSettings(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// initializes ReleaseSettings table
   void InitReleaseSettingsTable(Lua::State& state, const ShutterReleaseSettings& releaseSettings,
      Lua::Table& tableReleaseSettings);

   /// sets new release settings
   std::vector<Lua::Value> RemoteReleaseControlSetReleaseSettings(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// callback that is called when image has been transferred
   void SetReleaseSettings_OnFinishedTransfer(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      const ShutterReleaseSettings& releaseSettings);

   /// event handler for property change events
   void RemoteReleaseControl_PropertyEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      std::shared_ptr<int> spHandlerId,
      RemoteReleaseControl::T_enPropertyEvent,
      unsigned int eventData);

   /// local handlerId = remoteReleaseControl:addPropertyEventHandler(callbackFunction)
   std::vector<Lua::Value> RemoteReleaseControlAddPropertyEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// remoteReleaseControl:removePropertyEventHandler(handlerId)
   std::vector<Lua::Value> RemoteReleaseControlRemovePropertyEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// event handler for state events
   void RemoteReleaseControl_StateEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      std::shared_ptr<int> spHandlerId,
      RemoteReleaseControl::T_enStateEvent,
      unsigned int eventData);

   /// local handlerId = remoteReleaseControl:addStateEventHandler(callbackFunction)
   std::vector<Lua::Value> RemoteReleaseControlAddStateEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// remoteReleaseControl:removeStateEventHandler(handlerId)
   std::vector<Lua::Value> RemoteReleaseControlRemoveStateEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// event handler for download events
   void RemoteReleaseControl_DownloadEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      std::shared_ptr<int> spHandlerId,
      RemoteReleaseControl::T_enDownloadEvent,
      unsigned int eventData);

   /// local handlerId = remoteReleaseControl:addDownloadEventHandler(callbackFunction)
   std::vector<Lua::Value> RemoteReleaseControlAddDownloadEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// remoteReleaseControl:removeDownloadEventHandler(handlerId)
   std::vector<Lua::Value> RemoteReleaseControlRemoveDownloadEventHandler(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// local imagePropertiesList = remoteReleaseControl:enumImageProperties()
   std::vector<Lua::Value> RemoteReleaseControlEnumImageProperties(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, Lua::State& state);

   /// local imageProperty = remoteReleaseControl:getImageProperty()
   std::vector<Lua::Value> RemoteReleaseControlGetImageProperty(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// local imageProperty = remoteReleaseControl:getImagePropertyByType(imagePropertyType)
   std::vector<Lua::Value> RemoteReleaseControlGetImagePropertyByType(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// local imageProperty = remoteReleaseControl:getShootingModeImageProperty(shootingMode)
   std::vector<Lua::Value> RemoteReleaseControlGetShootingModeImageProperty(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state,
      const std::vector<Lua::Value>& vecParams);

   /// adds ImageProperty table
   void AddImageProperty(Lua::Table& table, const ImageProperty& imageProperty,
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl);

   /// local viewfinder = remoteReleaseControl:startViewfinder()
   std::vector<Lua::Value> RemoteReleaseControlStartViewfinder(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, Lua::State& state);

   /// local numShots = remoteReleaseControl:numAvailableShots()
   std::vector<Lua::Value> RemoteReleaseControlNumAvailableShots(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl);

   /// remoteReleaseControl:sendCommand()
   std::vector<Lua::Value> RemoteReleaseControlSendCommand(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// remoteReleaseControl:release()
   std::vector<Lua::Value> RemoteReleaseControlRelease(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl);

   /// local bulbReleaseControl = remoteReleaseControl:startBulb()
   std::vector<Lua::Value> RemoteReleaseControlStartBulb(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, Lua::State& state);

   /// local remoteReleaseControl:close()
   std::vector<Lua::Value> RemoteReleaseControlClose(
      std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl);

   // Viewfinder functions

   /// initializes viewfinder table
   void InitViewfinderTable(std::shared_ptr<Viewfinder> spViewfinder, Lua::Table& viewfinder);

   /// local isCapable = viewfinder:getCapability(Constants.Viewfinder.capXxx)
   std::vector<Lua::Value> ViewfinderGetCapability(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// viewfinder:setOutputType(outputType)
   std::vector<Lua::Value> ViewfinderSetOutputType(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// viewfinder:setAvailImageHandler(callbackFunction)
   std::vector<Lua::Value> ViewfinderSetAvailImageHandler(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// called when a new viewfinder image is available
   void SetAvailImageHandler_OnAvailImageHandler(std::shared_ptr<Viewfinder> spViewfinder,
      const std::vector<BYTE>& vecImage);

   /// local histogram viewfinder:getHistogram(Constants.Viewfinder.historyXxx);
   std::vector<Lua::Value> ViewfinderGetHistogram(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   /// called to close viewfinder
   std::vector<Lua::Value> ViewfinderClose(std::shared_ptr<Viewfinder> spViewfinder,
      Lua::State& state, const std::vector<Lua::Value>& vecParams);

   // BulbReleaseControl functions

   /// initizalizes BulbReleaseControl table
   void InitBulbReleaseControlTable(std::shared_ptr<BulbReleaseControl> spBulbReleaseControl, Lua::Table& bulbReleaseControl);

   /// local elapsedTime = bulbReleaseControl:elapsedTime()
   std::vector<Lua::Value> BulbReleaseControlElapsedTime(std::shared_ptr<BulbReleaseControl> spBulbReleaseControl);

   /// bulbReleaseControl:stop()
   std::vector<Lua::Value> BulbReleaseControlStop(std::shared_ptr<BulbReleaseControl> spBulbReleaseControl);

private:
   /// Lua state
   Lua::State& m_state;

   /// CanonControl instance
   std::unique_ptr<Instance> m_upInstance;

   /// release settings stored for the script
   ShutterReleaseSettings m_releaseSettings;

   /// once Lua has connected to remote release control, a pointer is stored here
   std::shared_ptr<RemoteReleaseControl> m_spRemoteRelaseControl;

   /// set of all registered property handler ids
   std::set<int> m_setAllPropertyHandlerIds;

   /// set of all registered state handler ids
   std::set<int> m_setAllStateHandlerIds;

   /// set of all registered download handler ids
   std::set<int> m_setAllDownloadHandlerIds;

   /// once Lua script started viewfinder, a pointer is stored here
   std::shared_ptr<Viewfinder> m_spViewfinder;

   /// strand to execute all Lua calls on
   boost::asio::io_service::strand& m_strand;

   /// output debug string handler
   T_fnOutputDebugString m_fnOutputDebugString;

   /// mutex to protect AsyncWaitForCamera() handler to call Lua script multiple times
   RecursiveMutex m_mtxAsyncWaitForCamera_InScript;

   /// timer for event handling
   boost::asio::deadline_timer m_timerEventHandling;

   /// event that is set when the event handling timer has stopped
   Event m_evtTimerStopped;
};
<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// library configuration
#include "libmesh/libmesh_config.h"

// C++ includes
#include <algorithm> // for std::min
#include <map>       // for std::multimap
#include <sstream>   // for std::ostringstream

// Local includes
#include "libmesh/boundary_info.h"
#include "libmesh/elem.h"
#include "libmesh/mesh_base.h"
#include "libmesh/parallel.h"
#include "libmesh/partitioner.h"
#include "libmesh/point_locator_base.h"
#include "libmesh/threads.h"

namespace libMesh
{

// ------------------------------------------------------------
// MeshBase class member functions
MeshBase::MeshBase (const Parallel::Communicator &comm_in,
                    unsigned char d) :
  ParallelObject (comm_in),
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (1),
  _dim           (d),
  _is_prepared   (false),
  _point_locator (NULL),
  _partitioner   (NULL),
#ifdef LIBMESH_ENABLE_UNIQUE_ID
  _next_unique_id(DofObject::invalid_unique_id),
#endif
  _skip_partitioning(false),
  _skip_renumber_nodes_and_elements(false)
{
  libmesh_assert_less_equal (LIBMESH_DIM, 3);
  libmesh_assert_greater_equal (LIBMESH_DIM, _dim);
  libmesh_assert (libMesh::initialized());
}

#ifndef LIBMESH_DISABLE_COMMWORLD
MeshBase::MeshBase (unsigned char d) :
  ParallelObject (CommWorld),
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (1),
  _dim           (d),
  _is_prepared   (false),
  _point_locator (NULL),
  _partitioner   (NULL),
#ifdef LIBMESH_ENABLE_UNIQUE_ID
  _next_unique_id(DofObject::invalid_unique_id),
#endif
  _skip_partitioning(false),
  _skip_renumber_nodes_and_elements(false)
{
  libmesh_assert_less_equal (LIBMESH_DIM, 3);
  libmesh_assert_greater_equal (LIBMESH_DIM, _dim);
  libmesh_assert (libMesh::initialized());
}
#endif // !LIBMESH_DISABLE_COMMWORLD

MeshBase::MeshBase (const MeshBase& other_mesh) :
  ParallelObject (other_mesh),
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (other_mesh._n_parts),
  _dim           (other_mesh._dim),
  _is_prepared   (other_mesh._is_prepared),
  _point_locator (NULL),
  _partitioner   (NULL),
#ifdef LIBMESH_ENABLE_UNIQUE_ID
  _next_unique_id(other_mesh._next_unique_id),
#endif
  _skip_partitioning(other_mesh._skip_partitioning),
  _skip_renumber_nodes_and_elements(false)
{
  if(other_mesh._partitioner.get())
    {
      _partitioner = other_mesh._partitioner->clone();
    }
}

MeshBase::~MeshBase()
{
  this->clear();

  libmesh_exceptionless_assert (!libMesh::closed());
}

void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements, const bool skip_find_neighbors)
{
  parallel_object_only();

  // A distributed mesh may have processors with no elements (or
  // processors with no elements of higher dimension, if we ever
  // support mixed-dimension meshes), but we want consistent
  // mesh_dimension anyways.
  libmesh_assert(this->comm().verify(this->is_serial()));

  if (!this->is_serial())
    {
      unsigned char dim = this->mesh_dimension();
      this->comm().max(dim);
      this->set_mesh_dimension(dim);
    }

  // Renumber the nodes and elements so that they in contiguous
  // blocks.  By default, _skip_renumber_nodes_and_elements is false.
  //
  // We may currently change that by passing
  // skip_renumber_nodes_and_elements==true to this function, but we
  // should use the allow_renumbering() accessor instead.
  //
  // Instances where you if prepare_for_use() should not renumber the nodes
  // and elements include reading in e.g. an xda/r or gmv file. In
  // this case, the ordering of the nodes may depend on an accompanying
  // solution, and the node ordering cannot be changed.

  if (skip_renumber_nodes_and_elements)
    {
      libmesh_deprecated();
      this->allow_renumbering(false);
    }

  // Mesh modification operations might not leave us with consistent
  // id counts, but our partitioner might need that consistency.
  if(!_skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();
  else
    this->update_parallel_id_counts();

  // Let all the elements find their neighbors
  if(!skip_find_neighbors)
    this->find_neighbors();

  // Partition the mesh.
  this->partition();

  // If we're using ParallelMesh, we'll want it parallelized.
  this->delete_remote_elements();

#ifdef LIBMESH_ENABLE_UNIQUE_ID
  // Assign DOF object unique ids
  this->assign_unique_ids();
#endif

  if(!_skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Search the mesh for all the dimensions of the elements
  // and cache them.
  this->cache_elem_dims();

  // Reset our PointLocator.  This needs to happen any time the elements
  // in the underlying elements in the mesh have changed, so we do it here.
  this->clear_point_locator();

  // The mesh is now prepared for use.
  _is_prepared = true;
}

void MeshBase::clear ()
{
  // Reset the number of partitions
  _n_parts = 1;

  // Reset the _is_prepared flag
  _is_prepared = false;

  // Clear boundary information
  this->get_boundary_info().clear();

  // Clear element dimensions
  _elem_dims.clear();

  // Clear our point locator.
  this->clear_point_locator();
}

void MeshBase::subdomain_ids (std::set<subdomain_id_type> &ids) const
{
  // This requires an inspection on every processor
  parallel_object_only();

  ids.clear();

  const_element_iterator el  = this->active_local_elements_begin();
  const_element_iterator end = this->active_local_elements_end();

  for (; el!=end; ++el)
    ids.insert((*el)->subdomain_id());

  // Some subdomains may only live on other processors
  this->comm().set_union(ids);
}

subdomain_id_type MeshBase::n_subdomains() const
{
  // This requires an inspection on every processor
  parallel_object_only();

  std::set<subdomain_id_type> ids;

  this->subdomain_ids (ids);

  return cast_int<subdomain_id_type>(ids.size());
}

dof_id_type MeshBase::n_nodes_on_proc (const processor_id_type proc_id) const
{
  // We're either counting a processor's nodes or unpartitioned
  // nodes
  libmesh_assert (proc_id < this->n_processors() ||
                  proc_id == DofObject::invalid_processor_id);

  return static_cast<dof_id_type>(std::distance (this->pid_nodes_begin(proc_id),
                                                 this->pid_nodes_end  (proc_id)));
}

dof_id_type MeshBase::n_elem_on_proc (const processor_id_type proc_id) const
{
  // We're either counting a processor's elements or unpartitioned
  // elements
  libmesh_assert (proc_id < this->n_processors() ||
                  proc_id == DofObject::invalid_processor_id);

  return static_cast<dof_id_type>(std::distance (this->pid_elements_begin(proc_id),
                                                 this->pid_elements_end  (proc_id)));
}

dof_id_type MeshBase::n_active_elem_on_proc (const processor_id_type proc_id) const
{
  libmesh_assert_less (proc_id, this->n_processors());
  return static_cast<dof_id_type>(std::distance (this->active_pid_elements_begin(proc_id),
                                                 this->active_pid_elements_end  (proc_id)));
}

dof_id_type MeshBase::n_sub_elem () const
{
  dof_id_type ne=0;

  const_element_iterator       el  = this->elements_begin();
  const const_element_iterator end = this->elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

dof_id_type MeshBase::n_active_sub_elem () const
{
  dof_id_type ne=0;

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

std::string MeshBase::get_info() const
{
  std::ostringstream oss;

  oss << " Mesh Information:"                                  << '\n'
      << "  mesh_dimension()="    << this->mesh_dimension()    << '\n'
      << "  spatial_dimension()=" << this->spatial_dimension() << '\n'
      << "  n_nodes()="           << this->n_nodes()           << '\n'
      << "    n_local_nodes()="   << this->n_local_nodes()     << '\n'
      << "  n_elem()="            << this->n_elem()            << '\n'
      << "    n_local_elem()="    << this->n_local_elem()      << '\n'
#ifdef LIBMESH_ENABLE_AMR
      << "    n_active_elem()="   << this->n_active_elem()     << '\n'
#endif
      << "  n_subdomains()="      << static_cast<std::size_t>(this->n_subdomains()) << '\n'
      << "  n_partitions()="      << static_cast<std::size_t>(this->n_partitions()) << '\n'
      << "  n_processors()="      << static_cast<std::size_t>(this->n_processors()) << '\n'
      << "  n_threads()="         << static_cast<std::size_t>(libMesh::n_threads()) << '\n'
      << "  processor_id()="      << static_cast<std::size_t>(this->processor_id()) << '\n';

  return oss.str();
}

void MeshBase::print_info(std::ostream& os) const
{
  os << this->get_info()
     << std::endl;
}

std::ostream& operator << (std::ostream& os, const MeshBase& m)
{
  m.print_info(os);
  return os;
}

void MeshBase::partition (const unsigned int n_parts)
{
  // NULL partitioner means don't partition
  // Non-serial meshes aren't ready for partitioning yet.
  if(!skip_partitioning() &&
     partitioner().get() &&
     this->is_serial())
    {
      partitioner()->partition (*this, n_parts);
    }
  else
    {
      // Make sure locally cached partition count
      this->recalculate_n_partitions();

      // Make sure any other locally cached data is correct
      this->update_post_partitioning();
    }
}

unsigned int MeshBase::recalculate_n_partitions()
{
  // This requires an inspection on every processor
  parallel_object_only();

  const_element_iterator el  = this->active_local_elements_begin();
  const_element_iterator end = this->active_local_elements_end();

  unsigned int max_proc_id=0;

  for (; el!=end; ++el)
    max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));

  // The number of partitions is one more than the max processor ID.
  _n_parts = max_proc_id+1;

  this->comm().max(_n_parts);

  return _n_parts;
}

const PointLocatorBase& MeshBase::point_locator () const
{
  libmesh_deprecated();

  if (_point_locator.get() == NULL)
    {
      // PointLocator construction may not be safe within threads
      libmesh_assert(!Threads::in_threads);

      _point_locator.reset (PointLocatorBase::build(TREE, *this).release());
    }

  return *_point_locator;
}

AutoPtr<PointLocatorBase> MeshBase::sub_point_locator () const
{
  if (_point_locator.get() == NULL)
    {
      // PointLocator construction may not be safe within threads
      libmesh_assert(!Threads::in_threads);

      _point_locator.reset (PointLocatorBase::build(TREE, *this).release());
    }

  return PointLocatorBase::build(TREE, *this, _point_locator.get());
}

void MeshBase::clear_point_locator ()
{
  _point_locator.reset(NULL);
}

std::string& MeshBase::subdomain_name(subdomain_id_type id)
{
  return _block_id_to_name[id];
}

const std::string& MeshBase::subdomain_name(subdomain_id_type id) const
{
  // An empty string to return when no matching subdomain name is found
  static const std::string empty;

  std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.find(id);
  if (iter == _block_id_to_name.end())
    return empty;
  else
    return iter->second;
}

subdomain_id_type MeshBase::get_id_by_name(const std::string& name) const
{
  // This function is searching the *values* of the map (linear search)
  // We might want to make this more efficient...
  std::map<subdomain_id_type, std::string>::const_iterator
    iter = _block_id_to_name.begin(),
    end_iter = _block_id_to_name.end();

  for ( ; iter != end_iter; ++iter)
    {
      if (iter->second == name)
        return iter->first;
    }

  libmesh_error_msg("Block '" << name << "' does not exist in mesh");
}

void MeshBase::cache_elem_dims()
{
  // This requires an inspection on every processor
  parallel_object_only();

  const_element_iterator el  = this->active_local_elements_begin();
  const_element_iterator end = this->active_local_elements_end();

  for (; el!=end; ++el)
    _elem_dims.insert((*el)->dim());

  // Some different dimension elements may only live on other processors
  this->comm().set_union(_elem_dims);
}

} // namespace libMesh
<commit_msg>Initialize MeshBase::_elem_dims in the constructor<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// library configuration
#include "libmesh/libmesh_config.h"

// C++ includes
#include <algorithm> // for std::min
#include <map>       // for std::multimap
#include <sstream>   // for std::ostringstream

// Local includes
#include "libmesh/boundary_info.h"
#include "libmesh/elem.h"
#include "libmesh/mesh_base.h"
#include "libmesh/parallel.h"
#include "libmesh/partitioner.h"
#include "libmesh/point_locator_base.h"
#include "libmesh/threads.h"

namespace libMesh
{

// ------------------------------------------------------------
// MeshBase class member functions
MeshBase::MeshBase (const Parallel::Communicator &comm_in,
                    unsigned char d) :
  ParallelObject (comm_in),
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (1),
  _dim           (d),
  _is_prepared   (false),
  _point_locator (NULL),
  _partitioner   (NULL),
#ifdef LIBMESH_ENABLE_UNIQUE_ID
  _next_unique_id(DofObject::invalid_unique_id),
#endif
  _skip_partitioning(false),
  _skip_renumber_nodes_and_elements(false)
{
  _elem_dims.insert(d);
  libmesh_assert_less_equal (LIBMESH_DIM, 3);
  libmesh_assert_greater_equal (LIBMESH_DIM, _dim);
  libmesh_assert (libMesh::initialized());
}

#ifndef LIBMESH_DISABLE_COMMWORLD
MeshBase::MeshBase (unsigned char d) :
  ParallelObject (CommWorld),
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (1),
  _dim           (d),
  _is_prepared   (false),
  _point_locator (NULL),
  _partitioner   (NULL),
#ifdef LIBMESH_ENABLE_UNIQUE_ID
  _next_unique_id(DofObject::invalid_unique_id),
#endif
  _skip_partitioning(false),
  _skip_renumber_nodes_and_elements(false)
{
  _elem_dims.insert(d);
  libmesh_assert_less_equal (LIBMESH_DIM, 3);
  libmesh_assert_greater_equal (LIBMESH_DIM, _dim);
  libmesh_assert (libMesh::initialized());
}
#endif // !LIBMESH_DISABLE_COMMWORLD

MeshBase::MeshBase (const MeshBase& other_mesh) :
  ParallelObject (other_mesh),
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (other_mesh._n_parts),
  _dim           (other_mesh._dim),
  _is_prepared   (other_mesh._is_prepared),
  _point_locator (NULL),
  _partitioner   (NULL),
#ifdef LIBMESH_ENABLE_UNIQUE_ID
  _next_unique_id(other_mesh._next_unique_id),
#endif
  _skip_partitioning(other_mesh._skip_partitioning),
  _skip_renumber_nodes_and_elements(false),
  _elem_dims(other_mesh._elem_dims)
{
  if(other_mesh._partitioner.get())
    {
      _partitioner = other_mesh._partitioner->clone();
    }
}

MeshBase::~MeshBase()
{
  this->clear();

  libmesh_exceptionless_assert (!libMesh::closed());
}

void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements, const bool skip_find_neighbors)
{
  parallel_object_only();

  // A distributed mesh may have processors with no elements (or
  // processors with no elements of higher dimension, if we ever
  // support mixed-dimension meshes), but we want consistent
  // mesh_dimension anyways.
  libmesh_assert(this->comm().verify(this->is_serial()));

  if (!this->is_serial())
    {
      unsigned char dim = this->mesh_dimension();
      this->comm().max(dim);
      this->set_mesh_dimension(dim);
    }

  // Renumber the nodes and elements so that they in contiguous
  // blocks.  By default, _skip_renumber_nodes_and_elements is false.
  //
  // We may currently change that by passing
  // skip_renumber_nodes_and_elements==true to this function, but we
  // should use the allow_renumbering() accessor instead.
  //
  // Instances where you if prepare_for_use() should not renumber the nodes
  // and elements include reading in e.g. an xda/r or gmv file. In
  // this case, the ordering of the nodes may depend on an accompanying
  // solution, and the node ordering cannot be changed.

  if (skip_renumber_nodes_and_elements)
    {
      libmesh_deprecated();
      this->allow_renumbering(false);
    }

  // Mesh modification operations might not leave us with consistent
  // id counts, but our partitioner might need that consistency.
  if(!_skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();
  else
    this->update_parallel_id_counts();

  // Let all the elements find their neighbors
  if(!skip_find_neighbors)
    this->find_neighbors();

  // Partition the mesh.
  this->partition();

  // If we're using ParallelMesh, we'll want it parallelized.
  this->delete_remote_elements();

#ifdef LIBMESH_ENABLE_UNIQUE_ID
  // Assign DOF object unique ids
  this->assign_unique_ids();
#endif

  if(!_skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Search the mesh for all the dimensions of the elements
  // and cache them.
  this->cache_elem_dims();

  // Reset our PointLocator.  This needs to happen any time the elements
  // in the underlying elements in the mesh have changed, so we do it here.
  this->clear_point_locator();

  // The mesh is now prepared for use.
  _is_prepared = true;
}

void MeshBase::clear ()
{
  // Reset the number of partitions
  _n_parts = 1;

  // Reset the _is_prepared flag
  _is_prepared = false;

  // Clear boundary information
  this->get_boundary_info().clear();

  // Clear element dimensions
  _elem_dims.clear();

  // Clear our point locator.
  this->clear_point_locator();
}

void MeshBase::subdomain_ids (std::set<subdomain_id_type> &ids) const
{
  // This requires an inspection on every processor
  parallel_object_only();

  ids.clear();

  const_element_iterator el  = this->active_local_elements_begin();
  const_element_iterator end = this->active_local_elements_end();

  for (; el!=end; ++el)
    ids.insert((*el)->subdomain_id());

  // Some subdomains may only live on other processors
  this->comm().set_union(ids);
}

subdomain_id_type MeshBase::n_subdomains() const
{
  // This requires an inspection on every processor
  parallel_object_only();

  std::set<subdomain_id_type> ids;

  this->subdomain_ids (ids);

  return cast_int<subdomain_id_type>(ids.size());
}

dof_id_type MeshBase::n_nodes_on_proc (const processor_id_type proc_id) const
{
  // We're either counting a processor's nodes or unpartitioned
  // nodes
  libmesh_assert (proc_id < this->n_processors() ||
                  proc_id == DofObject::invalid_processor_id);

  return static_cast<dof_id_type>(std::distance (this->pid_nodes_begin(proc_id),
                                                 this->pid_nodes_end  (proc_id)));
}

dof_id_type MeshBase::n_elem_on_proc (const processor_id_type proc_id) const
{
  // We're either counting a processor's elements or unpartitioned
  // elements
  libmesh_assert (proc_id < this->n_processors() ||
                  proc_id == DofObject::invalid_processor_id);

  return static_cast<dof_id_type>(std::distance (this->pid_elements_begin(proc_id),
                                                 this->pid_elements_end  (proc_id)));
}

dof_id_type MeshBase::n_active_elem_on_proc (const processor_id_type proc_id) const
{
  libmesh_assert_less (proc_id, this->n_processors());
  return static_cast<dof_id_type>(std::distance (this->active_pid_elements_begin(proc_id),
                                                 this->active_pid_elements_end  (proc_id)));
}

dof_id_type MeshBase::n_sub_elem () const
{
  dof_id_type ne=0;

  const_element_iterator       el  = this->elements_begin();
  const const_element_iterator end = this->elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

dof_id_type MeshBase::n_active_sub_elem () const
{
  dof_id_type ne=0;

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

std::string MeshBase::get_info() const
{
  std::ostringstream oss;

  oss << " Mesh Information:"                                  << '\n'
      << "  mesh_dimension()="    << this->mesh_dimension()    << '\n'
      << "  spatial_dimension()=" << this->spatial_dimension() << '\n'
      << "  n_nodes()="           << this->n_nodes()           << '\n'
      << "    n_local_nodes()="   << this->n_local_nodes()     << '\n'
      << "  n_elem()="            << this->n_elem()            << '\n'
      << "    n_local_elem()="    << this->n_local_elem()      << '\n'
#ifdef LIBMESH_ENABLE_AMR
      << "    n_active_elem()="   << this->n_active_elem()     << '\n'
#endif
      << "  n_subdomains()="      << static_cast<std::size_t>(this->n_subdomains()) << '\n'
      << "  n_partitions()="      << static_cast<std::size_t>(this->n_partitions()) << '\n'
      << "  n_processors()="      << static_cast<std::size_t>(this->n_processors()) << '\n'
      << "  n_threads()="         << static_cast<std::size_t>(libMesh::n_threads()) << '\n'
      << "  processor_id()="      << static_cast<std::size_t>(this->processor_id()) << '\n';

  return oss.str();
}

void MeshBase::print_info(std::ostream& os) const
{
  os << this->get_info()
     << std::endl;
}

std::ostream& operator << (std::ostream& os, const MeshBase& m)
{
  m.print_info(os);
  return os;
}

void MeshBase::partition (const unsigned int n_parts)
{
  // NULL partitioner means don't partition
  // Non-serial meshes aren't ready for partitioning yet.
  if(!skip_partitioning() &&
     partitioner().get() &&
     this->is_serial())
    {
      partitioner()->partition (*this, n_parts);
    }
  else
    {
      // Make sure locally cached partition count
      this->recalculate_n_partitions();

      // Make sure any other locally cached data is correct
      this->update_post_partitioning();
    }
}

unsigned int MeshBase::recalculate_n_partitions()
{
  // This requires an inspection on every processor
  parallel_object_only();

  const_element_iterator el  = this->active_local_elements_begin();
  const_element_iterator end = this->active_local_elements_end();

  unsigned int max_proc_id=0;

  for (; el!=end; ++el)
    max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));

  // The number of partitions is one more than the max processor ID.
  _n_parts = max_proc_id+1;

  this->comm().max(_n_parts);

  return _n_parts;
}

const PointLocatorBase& MeshBase::point_locator () const
{
  libmesh_deprecated();

  if (_point_locator.get() == NULL)
    {
      // PointLocator construction may not be safe within threads
      libmesh_assert(!Threads::in_threads);

      _point_locator.reset (PointLocatorBase::build(TREE, *this).release());
    }

  return *_point_locator;
}

AutoPtr<PointLocatorBase> MeshBase::sub_point_locator () const
{
  if (_point_locator.get() == NULL)
    {
      // PointLocator construction may not be safe within threads
      libmesh_assert(!Threads::in_threads);

      _point_locator.reset (PointLocatorBase::build(TREE, *this).release());
    }

  return PointLocatorBase::build(TREE, *this, _point_locator.get());
}

void MeshBase::clear_point_locator ()
{
  _point_locator.reset(NULL);
}

std::string& MeshBase::subdomain_name(subdomain_id_type id)
{
  return _block_id_to_name[id];
}

const std::string& MeshBase::subdomain_name(subdomain_id_type id) const
{
  // An empty string to return when no matching subdomain name is found
  static const std::string empty;

  std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.find(id);
  if (iter == _block_id_to_name.end())
    return empty;
  else
    return iter->second;
}

subdomain_id_type MeshBase::get_id_by_name(const std::string& name) const
{
  // This function is searching the *values* of the map (linear search)
  // We might want to make this more efficient...
  std::map<subdomain_id_type, std::string>::const_iterator
    iter = _block_id_to_name.begin(),
    end_iter = _block_id_to_name.end();

  for ( ; iter != end_iter; ++iter)
    {
      if (iter->second == name)
        return iter->first;
    }

  libmesh_error_msg("Block '" << name << "' does not exist in mesh");
}

void MeshBase::cache_elem_dims()
{
  // This requires an inspection on every processor
  parallel_object_only();

  const_element_iterator el  = this->active_local_elements_begin();
  const_element_iterator end = this->active_local_elements_end();

  for (; el!=end; ++el)
    _elem_dims.insert((*el)->dim());

  // Some different dimension elements may only live on other processors
  this->comm().set_union(_elem_dims);
}

} // namespace libMesh
<|endoftext|>


<commit_before>//Copyright 2015 Adam Smith
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.

// Contact :
// Email             : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP

/*!
	\file FileWindows.inl
	\brief
	\author
	Created			: Adam Smith
	Last modified	: Adam Smith
	\version 1.0
	\date
	Created			: 20th November 2015
	Last Modified	: 15th January 2016
*/

namespace Solaire { namespace File {

    namespace Implementation {

        const char* const makeCString(const StringConstant& aString, char* aPath) {
            const int32_t size = aString.size();
            aPath[size] = '\0';
            if(aString.isContiguous()) {
                std::memcpy(aPath, &aString[0], size);
            }else {
                for(int32_t i = 0; i < size; ++i) aPath[i] = aString[i];
            }
            return aPath;
        }

         bool openFile(const StringConstant& aFilename, HANDLE& aHandle, const int32_t aFlags) {
            char filename[MAX_PATH_LENGTH + 1];
            Implementation::makeCString(aFilename, filename);
            const HANDLE handle = CreateFileA(
                filename,
                aFlags,
                0,
                nullptr,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                nullptr
            );

            return handle != INVALID_HANDLE_VALUE;
        }

         bool openRFile(const StringConstant& aFilename, HANDLE& aHandle) {
            return openFile(aFilename, aHandle, GENERIC_READ);
        }

         bool openWFile(const StringConstant& aFilename, HANDLE& aHandle) {
            return openFile(aFilename, aHandle, GENERIC_WRITE);
        }

         bool openRWFile(const StringConstant& aFilename, HANDLE& aHandle) {
            return openFile(aFilename, aHandle, GENERIC_READ | GENERIC_WRITE);
        }

        bool closeFile(HANDLE& aHandle) {
            return CloseHandle(aHandle);
        }
    }

    AttributeFlags SOLAIRE_EXPORT_CALL getAttributes(const StringConstant& aFilename) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        const char* const filename = Implementation::makeCString(aFilename, buffer);

        const DWORD attributes = GetFileAttributesA(filename);
        DWORD binaryType;
        const BOOL executable = GetBinaryTypeA(filename, &binaryType);

        AttributeFlags tmp = FLAG_NONE;
        if(attributes & FILE_ATTRIBUTE_HIDDEN) tmp |= FLAG_HIDDEN;
        if(attributes & FILE_ATTRIBUTE_DIRECTORY) tmp |= FLAG_DIRECTORY;
        else tmp |= FLAG_FILE;
        if(attributes & FILE_ATTRIBUTE_READONLY) tmp |= FLAG_READ;
        else tmp |= FLAG_READ | FLAG_WRITE;
        if(executable) tmp |= FLAG_EXECUTABLE;
        if(tmp != FLAG_NONE) tmp |= FLAG_EXISTS;

        return tmp;
    }

    bool SOLAIRE_EXPORT_CALL createFile(const StringConstant& aFilename, const AttributeFlags aAttributes) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        const char* const filename = Implementation::makeCString(aFilename, buffer);

        DWORD access = 0;
        if (aAttributes & FLAG_READ) access |= GENERIC_READ;
        if (aAttributes & FLAG_WRITE) access |= GENERIC_WRITE;

        DWORD flags = 0;
        if (aAttributes & FLAG_HIDDEN) flags |= FILE_ATTRIBUTE_HIDDEN;
        if ((aAttributes & FLAG_READ) != 0 && (aAttributes & FLAG_WRITE) == 0) flags |= FILE_ATTRIBUTE_READONLY;
        if (flags == 0) flags = FILE_ATTRIBUTE_NORMAL;

        const HANDLE handle = CreateFileA(
            filename,
            access,
            0,
            nullptr,
            CREATE_NEW,
            flags,
            nullptr
        );

        if(handle != INVALID_HANDLE_VALUE) {
            CloseHandle(handle);
            return true;
        }else {
            return false;
        }
    }

    bool SOLAIRE_EXPORT_CALL createDirectory(const StringConstant& aFilename) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        return CreateDirectoryA(Implementation::makeCString(aFilename, buffer), nullptr) > 0;
    }

    bool SOLAIRE_EXPORT_CALL deleteFile(const StringConstant& aFilename) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        return DeleteFileA(Implementation::makeCString(aFilename, buffer)) > 0;
    }

    bool SOLAIRE_EXPORT_CALL deleteDirectory(const StringConstant& aFilename) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        return DeleteFileA(Implementation::makeCString(aFilename, buffer)) > 0;
    }

    STLString SOLAIRE_EXPORT_CALL getParent(const StringConstant& aFilename) throw() {
        const int32_t length = aFilename.size();
        const int32_t seperator = aFilename.findLastOf(FILE_SEPERATOR);

        STLString path;
        if(seperator != length) for(int32_t i = 0; i <= seperator; ++i) path.pushBack(aFilename[i]);
        return path;
    }

    STLString SOLAIRE_EXPORT_CALL getName(const StringConstant& aFilename) throw() {
        const int32_t length = aFilename.size();
        const int32_t seperator = aFilename.findLastOf(FILE_SEPERATOR);
        const int32_t end = aFilename.findLastOf('.');

        if(seperator == length) {
            return STLString();
        } else {
            STLString tmp;
            for(int32_t i = seperator + 1; i < end; ++i) tmp.pushBack(aFilename[i]);
            return tmp;
        }
    }

    STLString SOLAIRE_EXPORT_CALL getExtension(const StringConstant& aFilename) throw() {
        const int32_t length = aFilename.size();
        const int32_t seperator = aFilename.findLastOf('.');

        if(seperator == length) {
            return STLString();
        } else {
            STLString tmp;
            for(int32_t i = 0; i <= seperator; ++i) tmp.pushBack(aFilename[i]);
            return tmp;
        }
    }

    int32_t SOLAIRE_EXPORT_CALL size(const StringConstant& aFilename) throw() {
        HANDLE handle;
        if(! Implementation::openRFile(aFilename, handle)) return 0;
        const int32_t size = GetFileSize(handle, nullptr);
        Implementation::closeFile(handle);
        return size;
    }

    bool SOLAIRE_EXPORT_CALL getFileList(const StringConstant& aDirectory, Stack<STLString>& aFiles) throw() {
        WIN32_FIND_DATAA findData;
        HANDLE handle = INVALID_HANDLE_VALUE;

        char directory[MAX_PATH_LENGTH + 1];
        Implementation::makeCString(aDirectory, directory);

        uint32_t fileCount = 0;

        handle = FindFirstFileA(directory, &findData);
        if (handle == INVALID_HANDLE_VALUE) return 0;
        do{
            aFiles.pushBack(STLString(findData.cFileName));
        } while(FindNextFileA(handle, &findData) != 0);

        FindClose(handle);

        return fileCount;
    }

    STLString SOLAIRE_EXPORT_CALL getCurrentDirectory() throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        const bool tmp = GetCurrentDirectoryA(MAX_PATH_LENGTH, buffer);
        return tmp ? STLString(buffer) : STLString();
    }

    STLString SOLAIRE_EXPORT_CALL getTemporaryDirectory() throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        const bool tmp = GetTempPathA(MAX_PATH_LENGTH, buffer);
        return tmp ? STLString(buffer) : STLString();
    }

    bool SOLAIRE_EXPORT_CALL rename(const StringConstant& aOldName, const StringConstant& aNewName) throw() {
        //! \todo Optimise Rename
        if(! copy(aOldName, aNewName)) return false;
        if(! deleteFile(aOldName)){
            return deleteFile(aNewName);
        }
        return true;
    }

    bool SOLAIRE_EXPORT_CALL copy(const StringConstant& aSrc, const StringConstant& aDst) throw() {
        char bufferA[MAX_PATH_LENGTH + 1];
        char bufferB[MAX_PATH_LENGTH + 1];
        return CopyFileA(Implementation::makeCString(aSrc, bufferA), Implementation::makeCString(aDst, bufferB), FALSE) > 0;
    }

    bool SOLAIRE_EXPORT_CALL move(const StringConstant& aFilename, const StringConstant& aTarget) throw() {
        char bufferA[MAX_PATH_LENGTH + 1];
        char bufferB[MAX_PATH_LENGTH + 1];
        return MoveFileA(Implementation::makeCString(aFilename, bufferA), Implementation::makeCString(aTarget, bufferB)) > 0;
    }
}}
<commit_msg>Fixed spacing<commit_after>//Copyright 2015 Adam Smith
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.

// Contact :
// Email             : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP

/*!
	\file FileWindows.inl
	\brief
	\author
	Created			: Adam Smith
	Last modified	: Adam Smith
	\version 1.0
	\date
	Created			: 20th November 2015
	Last Modified	: 15th January 2016
*/

namespace Solaire { namespace File {

    namespace Implementation {

        const char* const makeCString(const StringConstant& aString, char* aPath) {
            const int32_t size = aString.size();
            aPath[size] = '\0';
            if(aString.isContiguous()) {
                std::memcpy(aPath, &aString[0], size);
            }else {
                for(int32_t i = 0; i < size; ++i) aPath[i] = aString[i];
            }
            return aPath;
        }

         bool openFile(const StringConstant& aFilename, HANDLE& aHandle, const int32_t aFlags) {
            char filename[MAX_PATH_LENGTH + 1];
            Implementation::makeCString(aFilename, filename);
            const HANDLE handle = CreateFileA(
                filename,
                aFlags,
                0,
                nullptr,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                nullptr
            );

            return handle != INVALID_HANDLE_VALUE;
        }

         bool openRFile(const StringConstant& aFilename, HANDLE& aHandle) {
            return openFile(aFilename, aHandle, GENERIC_READ);
        }

         bool openWFile(const StringConstant& aFilename, HANDLE& aHandle) {
            return openFile(aFilename, aHandle, GENERIC_WRITE);
        }

         bool openRWFile(const StringConstant& aFilename, HANDLE& aHandle) {
            return openFile(aFilename, aHandle, GENERIC_READ | GENERIC_WRITE);
        }

        bool closeFile(HANDLE& aHandle) {
            return CloseHandle(aHandle);
        }
    }

    AttributeFlags SOLAIRE_EXPORT_CALL getAttributes(const StringConstant& aFilename) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        const char* const filename = Implementation::makeCString(aFilename, buffer);

        const DWORD attributes = GetFileAttributesA(filename);
        DWORD binaryType;
        const BOOL executable = GetBinaryTypeA(filename, &binaryType);

        AttributeFlags tmp = FLAG_NONE;
        if(attributes & FILE_ATTRIBUTE_HIDDEN) tmp |= FLAG_HIDDEN;
        if(attributes & FILE_ATTRIBUTE_DIRECTORY) tmp |= FLAG_DIRECTORY;
        else tmp |= FLAG_FILE;
        if(attributes & FILE_ATTRIBUTE_READONLY) tmp |= FLAG_READ;
        else tmp |= FLAG_READ | FLAG_WRITE;
        if(executable) tmp |= FLAG_EXECUTABLE;
        if(tmp != FLAG_NONE) tmp |= FLAG_EXISTS;

        return tmp;
    }

    bool SOLAIRE_EXPORT_CALL createFile(const StringConstant& aFilename, const AttributeFlags aAttributes) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        const char* const filename = Implementation::makeCString(aFilename, buffer);

        DWORD access = 0;
        if(aAttributes & FLAG_READ) access |= GENERIC_READ;
        if(aAttributes & FLAG_WRITE) access |= GENERIC_WRITE;

        DWORD flags = 0;
        if(aAttributes & FLAG_HIDDEN) flags |= FILE_ATTRIBUTE_HIDDEN;
        if((aAttributes & FLAG_READ) != 0 && (aAttributes & FLAG_WRITE) == 0) flags |= FILE_ATTRIBUTE_READONLY;
        if(flags == 0) flags = FILE_ATTRIBUTE_NORMAL;

        const HANDLE handle = CreateFileA(
            filename,
            access,
            0,
            nullptr,
            CREATE_NEW,
            flags,
            nullptr
        );

        if(handle != INVALID_HANDLE_VALUE) {
            CloseHandle(handle);
            return true;
        }else {
            return false;
        }
    }

    bool SOLAIRE_EXPORT_CALL createDirectory(const StringConstant& aFilename) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        return CreateDirectoryA(Implementation::makeCString(aFilename, buffer), nullptr) > 0;
    }

    bool SOLAIRE_EXPORT_CALL deleteFile(const StringConstant& aFilename) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        return DeleteFileA(Implementation::makeCString(aFilename, buffer)) > 0;
    }

    bool SOLAIRE_EXPORT_CALL deleteDirectory(const StringConstant& aFilename) throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        return DeleteFileA(Implementation::makeCString(aFilename, buffer)) > 0;
    }

    STLString SOLAIRE_EXPORT_CALL getParent(const StringConstant& aFilename) throw() {
        const int32_t length = aFilename.size();
        const int32_t seperator = aFilename.findLastOf(FILE_SEPERATOR);

        STLString path;
        if(seperator != length) for(int32_t i = 0; i <= seperator; ++i) path.pushBack(aFilename[i]);
        return path;
    }

    STLString SOLAIRE_EXPORT_CALL getName(const StringConstant& aFilename) throw() {
        const int32_t length = aFilename.size();
        const int32_t seperator = aFilename.findLastOf(FILE_SEPERATOR);
        const int32_t end = aFilename.findLastOf('.');

        if(seperator == length) {
            return STLString();
        }else {
            STLString tmp;
            for(int32_t i = seperator + 1; i < end; ++i) tmp.pushBack(aFilename[i]);
            return tmp;
        }
    }

    STLString SOLAIRE_EXPORT_CALL getExtension(const StringConstant& aFilename) throw() {
        const int32_t length = aFilename.size();
        const int32_t seperator = aFilename.findLastOf('.');

        if(seperator == length) {
            return STLString();
        }else {
            STLString tmp;
            for(int32_t i = 0; i <= seperator; ++i) tmp.pushBack(aFilename[i]);
            return tmp;
        }
    }

    int32_t SOLAIRE_EXPORT_CALL size(const StringConstant& aFilename) throw() {
        HANDLE handle;
        if(! Implementation::openRFile(aFilename, handle)) return 0;
        const int32_t size = GetFileSize(handle, nullptr);
        Implementation::closeFile(handle);
        return size;
    }

    bool SOLAIRE_EXPORT_CALL getFileList(const StringConstant& aDirectory, Stack<STLString>& aFiles) throw() {
        WIN32_FIND_DATAA findData;
        HANDLE handle = INVALID_HANDLE_VALUE;

        char directory[MAX_PATH_LENGTH + 1];
        Implementation::makeCString(aDirectory, directory);

        uint32_t fileCount = 0;

        handle = FindFirstFileA(directory, &findData);
        if (handle == INVALID_HANDLE_VALUE) return 0;
        do{
            aFiles.pushBack(STLString(findData.cFileName));
        } while(FindNextFileA(handle, &findData) != 0);

        FindClose(handle);

        return fileCount;
    }

    STLString SOLAIRE_EXPORT_CALL getCurrentDirectory() throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        const bool tmp = GetCurrentDirectoryA(MAX_PATH_LENGTH, buffer);
        return tmp ? STLString(buffer) : STLString();
    }

    STLString SOLAIRE_EXPORT_CALL getTemporaryDirectory() throw() {
        char buffer[MAX_PATH_LENGTH + 1];
        const bool tmp = GetTempPathA(MAX_PATH_LENGTH, buffer);
        return tmp ? STLString(buffer) : STLString();
    }

    bool SOLAIRE_EXPORT_CALL rename(const StringConstant& aOldName, const StringConstant& aNewName) throw() {
        //! \todo Optimise Rename
        if(! copy(aOldName, aNewName)) return false;
        if(! deleteFile(aOldName)){
            return deleteFile(aNewName);
        }
        return true;
    }

    bool SOLAIRE_EXPORT_CALL copy(const StringConstant& aSrc, const StringConstant& aDst) throw() {
        char bufferA[MAX_PATH_LENGTH + 1];
        char bufferB[MAX_PATH_LENGTH + 1];
        return CopyFileA(Implementation::makeCString(aSrc, bufferA), Implementation::makeCString(aDst, bufferB), FALSE) > 0;
    }

    bool SOLAIRE_EXPORT_CALL move(const StringConstant& aFilename, const StringConstant& aTarget) throw() {
        char bufferA[MAX_PATH_LENGTH + 1];
        char bufferB[MAX_PATH_LENGTH + 1];
        return MoveFileA(Implementation::makeCString(aFilename, bufferA), Implementation::makeCString(aTarget, bufferB)) > 0;
    }
}}
<|endoftext|>


<commit_before>/**
* \file AnnTriggerObject.hpp
* \brief Object for representing a volume that trigger an event
* \author A. Brainville
*/

#ifndef ANNTRIGGEROBJECT
#define ANNTRIGGEROBJECT

#include "systemMacro.h"
#include "AnnVect3.hpp"
#include "AnnPlayer.hpp"
#include "AnnTools.h"

namespace Annwvyn
{
	//Anticipated declaration of AnnEngine class
	class AnnEngine;
	class AnnPhysicsGameEngine;

	///Object for representing a volume that trigger an event
	class DLL AnnTriggerObject
	{
	public:
		///Class constructor
		AnnTriggerObject();

		///Class destructor
		virtual ~AnnTriggerObject(){}

		///Set position form Vector 3D
		/// \param pos 3D vector positioning the object
		void setPosition(Ogre::Vector3 pos);

		///Set position form Variables
		/// \param x X component of the poisition vector
		/// \param y Y component of the poisition vector
		/// \param z Z component of the poisition vector
		void setPosition(float x, float y, float z);

		///Get position
		Ogre::Vector3 getPosition();

		///Get contact information
		bool getContactInformation();

	private:
		///For engine : Set contact state
		/// \param contact Contact state
		void setContactInformation(bool contact);
		virtual bool computeVolumetricTest(AnnPlayer* player) = 0;

		friend class AnnEngine;
		friend class AnnPhysicsEngine;

	private:
		///Position of the object
		AnnVect3 m_position;

		///True if trigger triggerd
		bool m_contactWithPlayer;
		bool lastFrameContactWithPlayer;

	public:
		///When contact happened
		virtual void atContact() {return;}
		///After initialization
		virtual void postInit() {return;}
	};

	class DLL AnnSphericalTriggerObject : public AnnTriggerObject
	{
	public:
		AnnSphericalTriggerObject();
		///GetThreshold distance
		float getThreshold();

		///Set contact information
		/// \param threshold Radius of the "activation sphere" of the trigger"
		void setThreshold(float threshold);

	private:
		bool computeVolumetricTest(AnnPlayer* player);
		///Distance where the trigger is triggered
		float m_threshold;
	};

	class DLL AnnAlignedBoxTriggerObject : public AnnTriggerObject
	{
	public:
		AnnAlignedBoxTriggerObject();
		void setBoundaries(float x1, float x2, float y1, float y2, float z1, float z2);
	private:
		bool computeVolumetricTest(AnnPlayer* player);
		float xMin, xMax, yMin, yMax, zMin, zMax;
	};
}

#endif

<commit_msg>Document new class AnnAlignedBoxTriggerObject<commit_after>/**
* \file AnnTriggerObject.hpp
* \brief Object for representing a volume that trigger an event
* \author A. Brainville
*/

#ifndef ANNTRIGGEROBJECT
#define ANNTRIGGEROBJECT

#include "systemMacro.h"
#include "AnnVect3.hpp"
#include "AnnPlayer.hpp"
#include "AnnTools.h"

namespace Annwvyn
{
	//Anticipated declaration of AnnEngine class
	class AnnEngine;
	class AnnPhysicsGameEngine;

	///Object for representing a volume that trigger an event
	class DLL AnnTriggerObject
	{
	public:
		///Class constructor
		AnnTriggerObject();

		///Class destructor
		virtual ~AnnTriggerObject(){}

		///Set position form Vector 3D
		/// \param pos 3D vector positioning the object
		void setPosition(Ogre::Vector3 pos);

		///Set position form Variables
		/// \param x X component of the poisition vector
		/// \param y Y component of the poisition vector
		/// \param z Z component of the poisition vector
		void setPosition(float x, float y, float z);

		///Get position
		Ogre::Vector3 getPosition();

		///Get contact information
		bool getContactInformation();

	private:
		///For engine : Set contact state
		/// \param contact Contact state
		void setContactInformation(bool contact);

		///Return true if player's head (this is player's trigger point) is inside the trigger volume.
		virtual bool computeVolumetricTest(AnnPlayer* player) = 0;

		friend class AnnEngine;
		friend class AnnPhysicsEngine;

	private:
		///Position of the object
		AnnVect3 m_position;

		///True if trigger triggerd
		bool m_contactWithPlayer;
		bool lastFrameContactWithPlayer;

	public:
		///When contact happened
		virtual void atContact() {return;}
		///After initialization
		virtual void postInit() {return;}
	};

	class DLL AnnSphericalTriggerObject : public AnnTriggerObject
	{
	public:
		AnnSphericalTriggerObject();
		///GetThreshold distance
		float getThreshold();

		///Set contact information
		/// \param threshold Radius of the "activation sphere" of the trigger"
		void setThreshold(float threshold);

	private:
		bool computeVolumetricTest(AnnPlayer* player);
		///Distance where the trigger is triggered
		float m_threshold;
	};

	///Create a trigger volume that is aligned with the scene referential.
	///Volume is defined by min/max XYZ boundaries
	///This is the lowest load in CPU time
	class DLL AnnAlignedBoxTriggerObject : public AnnTriggerObject
	{
	public:
		AnnAlignedBoxTriggerObject();

		///Set the volume dimentions
		/// \param x1 X minimal plane boundary
		/// \param x2 X maximal plane boundary
		/// \param y1 Y minimal plane boundary
		/// \param y2 Y maximal plane boundary
		/// \param z1 Z minimal plane boundary
		/// \param z2 Z maximal plane boundary
		void setBoundaries(float x1, float x2, float y1, float y2, float z1, float z2);
	private:
		bool computeVolumetricTest(AnnPlayer* player);
		///Boundaries values. All defaults to 0
		float xMin, xMax, yMin, yMax, zMin, zMax;
	};
}

#endif

<|endoftext|>


<commit_before>/**
 * \file testModelParameterValues.cpp
 * \author Freek Stulp
 *
 * This file is part of DmpBbo, a set of libraries and programs for the
 * black-box optimization of dynamical movement primitives.
 * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
 *
 * DmpBbo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * DmpBbo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with DmpBbo.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <string>
#include <set>

#include "functionapproximators/ModelParametersGMR.hpp"
#include "functionapproximators/ModelParametersLWR.hpp"
#include "functionapproximators/ModelParametersIRFRLS.hpp"
#include "getFunctionApproximatorsVector.hpp"

using namespace std;
using namespace Eigen;
using namespace DmpBbo;

int main(int n_args, char** args)
{
  int n_basis_functions = 3;
  int n_dims = 1;

  vector<ModelParameters*> model_parameters;

  // LWR
  VectorXd centers = VectorXd::LinSpaced(n_basis_functions,30,50);
  VectorXd widths  = VectorXd::Zero(n_basis_functions);
  VectorXd offsets = (100.0*VectorXd::Random(n_basis_functions)).cast<int>().cast<double>().array().abs();
  VectorXd slopes  = VectorXd::Ones(n_basis_functions);

  model_parameters.push_back(new ModelParametersLWR(centers, widths, slopes, offsets));

  // IRFRLS
  MatrixXd linear_models = (100.0*MatrixXd::Random(n_basis_functions,n_dims)).cast<int>().cast<double>().array().abs();
  MatrixXd cosines_periodes =
  (100.0*MatrixXd::Random(n_basis_functions,n_dims)).cast<int>().cast<double>().array().abs();
  VectorXd cosines_phase =
  (100.0*VectorXd::Random(n_basis_functions)).cast<int>().cast<double>().array().abs();

  model_parameters.push_back(new ModelParametersIRFRLS(linear_models, cosines_periodes, cosines_phase));

  // GMR

  vector<VectorXd> centers_gmr;
  vector<double> priors_gmr;
  vector<MatrixXd> slopes_gmr;
  vector<VectorXd> biases_gmr;
  vector<MatrixXd> inverseCovarsL_gmr;

  VectorXd centers_gmr_1 = (100.0*VectorXd::Random(n_dims)).cast<int>().cast<double>().array().abs();
  centers_gmr.push_back(centers_gmr_1);

  double a = 0.3;
  priors_gmr.push_back(a);

  MatrixXd slopes_gmr_1 = (100.0*MatrixXd::Random(n_dims,n_dims)).cast<int>().cast<double>().array().abs();
  slopes_gmr.push_back(slopes_gmr_1);

  VectorXd biases_gmr_1 = (100.0*VectorXd::Random(n_dims)).cast<int>().cast<double>().array().abs();
  biases_gmr.push_back(biases_gmr_1);

  MatrixXd inverseCovarsL_gmr_1 = (100.0*MatrixXd::Random(n_dims,n_dims)).cast<int>().cast<double>().array().abs();
  inverseCovarsL_gmr.push_back(inverseCovarsL_gmr_1);

  model_parameters.push_back(new ModelParametersGMR(centers_gmr,priors_gmr,slopes_gmr,biases_gmr,inverseCovarsL_gmr));

  for (unsigned int mm=0; mm<model_parameters.size(); mm++)
  {
    ModelParameters* mp = model_parameters[mm];

    cout << "____________________________________________________________________" << endl;
    cout << *mp << endl << endl;

    set<string> selected_labels;

    // LWR (also GMR partially)
    //selected_labels.insert("widths");
    //selected_labels.insert("offsets");
    selected_labels.insert("slopes");
    selected_labels.insert("centers");

    // IRFRLS
    //selected_labels.insert("linear_model");
    selected_labels.insert("phases");
    //selected_labels.insert("periods");

    mp->setSelectedParameters(selected_labels);

    cout << "vector size (all     ) = " << mp->getParameterVectorAllSize() << endl;
    cout << "vector size (selected) = " <<  mp->getParameterVectorSelectedSize() << endl;

    VectorXi selected_mask;
    mp->getParameterVectorMask(selected_labels,selected_mask);
    cout << "mask = " << selected_mask.transpose() << endl << endl;

    VectorXd values, min_values, max_values, values_normalized;

    mp->getParameterVectorAll(values);
    //mp->getParameterVectorAllMinMax(min_values,max_values);

    cout << "values     (all     ): " << values.transpose() << endl;
    //cout << "min_values (all     ): " << min_values.transpose() << endl;
    //cout << "max_values (all     ): " << max_values.transpose() << endl << endl;

    mp->getParameterVectorSelected(values);
    mp->getParameterVectorSelectedMinMax(min_values,max_values);
    mp->getParameterVectorSelectedNormalized(values_normalized);
    cout << "values     (selected): " << values.transpose() << endl;
    cout << "min_values (selected): " << min_values.transpose() << endl;
    cout << "max_values (selected): " << max_values.transpose() << endl ;
    cout << "values_norm(selected): " << values_normalized.transpose() << endl << endl;

    VectorXd new_values = VectorXd::LinSpaced(mp->getParameterVectorSelectedSize(),2,20);
    mp->setParameterVectorSelected(new_values);

    mp->getParameterVectorAll(values);
    //mp->getParameterVectorAllMinMax(min_values,max_values);

    cout << "values     (all     ): " << values.transpose() << endl;
    //cout << "min_values (all     ): " << min_values.transpose() << endl;
    //cout << "max_values (all     ): " << max_values.transpose() << endl << endl;

    mp->getParameterVectorSelected(values);
    mp->getParameterVectorSelectedMinMax(min_values,max_values);
    mp->getParameterVectorSelectedNormalized(values_normalized);
    cout << "values     (selected): " << values.transpose() << endl;
    cout << "min_values (selected): " << min_values.transpose() << endl;
    cout << "max_values (selected): " << max_values.transpose() << endl;
    cout << "values_norm(selected): " << values_normalized.transpose() << endl << endl;

    new_values = VectorXd::LinSpaced(mp->getParameterVectorSelectedSize(),0.49,0.51);
    mp->setParameterVectorSelectedNormalized(new_values);

    mp->getParameterVectorAll(values);
    //mp->getParameterVectorAllMinMax(min_values,max_values);

    cout << "values     (all     ): " << values.transpose() << endl;
    //cout << "min_values (all     ): " << min_values.transpose() << endl;
    //cout << "max_values (all     ): " << max_values.transpose() << endl << endl;

    mp->getParameterVectorSelected(values);
    mp->getParameterVectorSelectedMinMax(min_values,max_values);
    mp->getParameterVectorSelectedNormalized(values_normalized);
    cout << "values     (selected): " << values.transpose() << endl;
    cout << "min_values (selected): " << min_values.transpose() << endl;
    cout << "max_values (selected): " << max_values.transpose() << endl;
    cout << "values_norm(selected): " << values_normalized.transpose() << endl << endl;
  }

  return 0;
}

<commit_msg>Excluded GMR from a test: no parameters can be optimized at the moment.<commit_after>/**
 * \file testModelParameterValues.cpp
 * \author Freek Stulp
 *
 * This file is part of DmpBbo, a set of libraries and programs for the
 * black-box optimization of dynamical movement primitives.
 * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
 *
 * DmpBbo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * DmpBbo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with DmpBbo.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <string>
#include <set>

#include "functionapproximators/ModelParametersGMR.hpp"
#include "functionapproximators/ModelParametersLWR.hpp"
#include "functionapproximators/ModelParametersIRFRLS.hpp"
#include "getFunctionApproximatorsVector.hpp"

using namespace std;
using namespace Eigen;
using namespace DmpBbo;

int main(int n_args, char** args)
{
  int n_basis_functions = 3;
  int n_dims = 1;

  vector<ModelParameters*> model_parameters;

  // LWR
  VectorXd centers = VectorXd::LinSpaced(n_basis_functions,30,50);
  VectorXd widths  = VectorXd::Zero(n_basis_functions);
  VectorXd offsets = (100.0*VectorXd::Random(n_basis_functions)).cast<int>().cast<double>().array().abs();
  VectorXd slopes  = VectorXd::Ones(n_basis_functions);

  model_parameters.push_back(new ModelParametersLWR(centers, widths, slopes, offsets));

  // IRFRLS
  MatrixXd linear_models = (100.0*MatrixXd::Random(n_basis_functions,n_dims)).cast<int>().cast<double>().array().abs();
  MatrixXd cosines_periodes =
  (100.0*MatrixXd::Random(n_basis_functions,n_dims)).cast<int>().cast<double>().array().abs();
  VectorXd cosines_phase =
  (100.0*VectorXd::Random(n_basis_functions)).cast<int>().cast<double>().array().abs();

  model_parameters.push_back(new ModelParametersIRFRLS(linear_models, cosines_periodes, cosines_phase));

  // GMR
  /*
  vector<VectorXd> centers_gmr;
  vector<double> priors_gmr;
  vector<MatrixXd> slopes_gmr;
  vector<VectorXd> biases_gmr;
  vector<MatrixXd> inverseCovarsL_gmr;

  VectorXd centers_gmr_1 = (100.0*VectorXd::Random(n_dims)).cast<int>().cast<double>().array().abs();
  centers_gmr.push_back(centers_gmr_1);

  double a = 0.3;
  priors_gmr.push_back(a);

  MatrixXd slopes_gmr_1 = (100.0*MatrixXd::Random(n_dims,n_dims)).cast<int>().cast<double>().array().abs();
  slopes_gmr.push_back(slopes_gmr_1);

  VectorXd biases_gmr_1 = (100.0*VectorXd::Random(n_dims)).cast<int>().cast<double>().array().abs();
  biases_gmr.push_back(biases_gmr_1);

  MatrixXd inverseCovarsL_gmr_1 = (100.0*MatrixXd::Random(n_dims,n_dims)).cast<int>().cast<double>().array().abs();
  inverseCovarsL_gmr.push_back(inverseCovarsL_gmr_1);

  model_parameters.push_back(new ModelParametersGMR(centers_gmr,priors_gmr,slopes_gmr,biases_gmr,inverseCovarsL_gmr));
  */

  for (unsigned int mm=0; mm<model_parameters.size(); mm++)
  {
    ModelParameters* mp = model_parameters[mm];

    cout << "____________________________________________________________________" << endl;
    cout << *mp << endl << endl;

    set<string> selected_labels;

    // LWR (also GMR partially)
    //selected_labels.insert("widths");
    //selected_labels.insert("offsets");
    selected_labels.insert("slopes");
    selected_labels.insert("centers");

    // IRFRLS
    //selected_labels.insert("linear_model");
    selected_labels.insert("phases");
    //selected_labels.insert("periods");

    mp->setSelectedParameters(selected_labels);

    cout << "vector size (all     ) = " << mp->getParameterVectorAllSize() << endl;
    cout << "vector size (selected) = " <<  mp->getParameterVectorSelectedSize() << endl;

    VectorXi selected_mask;
    mp->getParameterVectorMask(selected_labels,selected_mask);
    cout << "mask = " << selected_mask.transpose() << endl << endl;

    VectorXd values, min_values, max_values, values_normalized;

    mp->getParameterVectorAll(values);
    //mp->getParameterVectorAllMinMax(min_values,max_values);

    cout << "values     (all     ): " << values.transpose() << endl;
    //cout << "min_values (all     ): " << min_values.transpose() << endl;
    //cout << "max_values (all     ): " << max_values.transpose() << endl << endl;

    mp->getParameterVectorSelected(values);
    mp->getParameterVectorSelectedMinMax(min_values,max_values);
    mp->getParameterVectorSelectedNormalized(values_normalized);
    cout << "values     (selected): " << values.transpose() << endl;
    cout << "min_values (selected): " << min_values.transpose() << endl;
    cout << "max_values (selected): " << max_values.transpose() << endl ;
    cout << "values_norm(selected): " << values_normalized.transpose() << endl << endl;

    VectorXd new_values = VectorXd::LinSpaced(mp->getParameterVectorSelectedSize(),2,20);
    mp->setParameterVectorSelected(new_values);

    mp->getParameterVectorAll(values);
    //mp->getParameterVectorAllMinMax(min_values,max_values);

    cout << "values     (all     ): " << values.transpose() << endl;
    //cout << "min_values (all     ): " << min_values.transpose() << endl;
    //cout << "max_values (all     ): " << max_values.transpose() << endl << endl;

    mp->getParameterVectorSelected(values);
    mp->getParameterVectorSelectedMinMax(min_values,max_values);
    mp->getParameterVectorSelectedNormalized(values_normalized);
    cout << "values     (selected): " << values.transpose() << endl;
    cout << "min_values (selected): " << min_values.transpose() << endl;
    cout << "max_values (selected): " << max_values.transpose() << endl;
    cout << "values_norm(selected): " << values_normalized.transpose() << endl << endl;

    new_values = VectorXd::LinSpaced(mp->getParameterVectorSelectedSize(),0.49,0.51);
    mp->setParameterVectorSelectedNormalized(new_values);

    mp->getParameterVectorAll(values);
    //mp->getParameterVectorAllMinMax(min_values,max_values);

    cout << "values     (all     ): " << values.transpose() << endl;
    //cout << "min_values (all     ): " << min_values.transpose() << endl;
    //cout << "max_values (all     ): " << max_values.transpose() << endl << endl;

    mp->getParameterVectorSelected(values);
    mp->getParameterVectorSelectedMinMax(min_values,max_values);
    mp->getParameterVectorSelectedNormalized(values_normalized);
    cout << "values     (selected): " << values.transpose() << endl;
    cout << "min_values (selected): " << min_values.transpose() << endl;
    cout << "max_values (selected): " << max_values.transpose() << endl;
    cout << "values_norm(selected): " << values_normalized.transpose() << endl << endl;
  }

  return 0;
}

<|endoftext|>