<commit_before>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *    All rights reserved.
 *
 *    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.
 */

/**
 * @file DeviceCallbacks.cpp
 *
 * Implements all the callbacks to the application from the CHIP Stack
 *
 **/
#include "DeviceCallbacks.h"

#include "CHIPDeviceManager.h"
#include "Globals.h"
#include "LEDWidget.h"
#include "WiFiWidget.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "gen/attribute-id.h"
#include "gen/cluster-id.h"
#include <app/util/basic-types.h>
#include <lib/mdns/DiscoveryManager.h>
#include <support/CodeUtils.h>

static const char * TAG = "echo-devicecallbacks";

using namespace ::chip;
using namespace ::chip::Inet;
using namespace ::chip::System;
using namespace ::chip::DeviceLayer;

uint32_t identifyTimerCount;
constexpr uint32_t kIdentifyTimerDelayMS = 250;

void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg)
{
    switch (event->Type)
    {
    case DeviceEventType::kInternetConnectivityChange:
        OnInternetConnectivityChange(event);
        break;

    case DeviceEventType::kSessionEstablished:
        OnSessionEstablished(event);
        break;
    }

    ESP_LOGI(TAG, "Current free heap: %d\n", heap_caps_get_free_size(MALLOC_CAP_8BIT));
}

void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
                                                  uint16_t manufacturerCode, uint8_t type, uint8_t size, uint8_t * value)
{
    ESP_LOGI(TAG, "PostAttributeChangeCallback - Cluster ID: '0x%04x', EndPoint ID: '0x%02x', Attribute ID: '0x%04x'", clusterId,
             endpointId, attributeId);

    switch (clusterId)
    {
    case ZCL_ON_OFF_CLUSTER_ID:
        OnOnOffPostAttributeChangeCallback(endpointId, attributeId, value);
        break;

    case ZCL_IDENTIFY_CLUSTER_ID:
        OnIdentifyPostAttributeChangeCallback(endpointId, attributeId, value);
        break;

    default:
        ESP_LOGI(TAG, "Unhandled cluster ID: %d", clusterId);
        break;
    }

    ESP_LOGI(TAG, "Current free heap: %d\n", heap_caps_get_free_size(MALLOC_CAP_8BIT));
}

void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event)
{
    if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established)
    {
        ESP_LOGI(TAG, "Server ready at: %s:%d", event->InternetConnectivityChange.address, CHIP_PORT);
        wifiLED.Set(true);
        chip::Mdns::DiscoveryManager::GetInstance().StartPublishDevice();
    }
    else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost)
    {
        ESP_LOGE(TAG, "Lost IPv4 connectivity...");
        wifiLED.Set(false);
    }
    if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established)
    {
        ESP_LOGI(TAG, "IPv6 Server ready...");
        chip::Mdns::DiscoveryManager::GetInstance().StartPublishDevice();
    }
    else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost)
    {
        ESP_LOGE(TAG, "Lost IPv6 connectivity...");
    }
}

void DeviceCallbacks::OnSessionEstablished(const ChipDeviceEvent * event)
{
    if (event->SessionEstablished.IsCommissioner)
    {
        ESP_LOGI(TAG, "Commissioner detected!");
    }
}

void DeviceCallbacks::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value)
{
    VerifyOrExit(attributeId == ZCL_ON_OFF_ATTRIBUTE_ID, ESP_LOGI(TAG, "Unhandled Attribute ID: '0x%04x", attributeId));
    VerifyOrExit(endpointId == 1 || endpointId == 2, ESP_LOGE(TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId));

    // At this point we can assume that value points to a bool value.
    endpointId == 1 ? statusLED1.Set(*value) : statusLED2.Set(*value);

exit:
    return;
}

void IdentifyTimerHandler(Layer * systemLayer, void * appState, Error error)
{
    statusLED1.Animate();

    // Decrement the timer count.
    identifyTimerCount--;

    if (identifyTimerCount)
    {
        SystemLayer.StartTimer(kIdentifyTimerDelayMS, IdentifyTimerHandler, appState);
    }
}

void DeviceCallbacks::OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value)
{
    VerifyOrExit(attributeId == ZCL_IDENTIFY_TIME_ATTRIBUTE_ID, ESP_LOGI(TAG, "Unhandled Attribute ID: '0x%04x", attributeId));
    VerifyOrExit(endpointId == 1, ESP_LOGE(TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId));

    statusLED1.Blink(kIdentifyTimerDelayMS * 2);

    // timerCount represents the number of callback execution before the we stopped the timer.
    // value is expressed in seconds and the timer is fired every 250ms, so just multiply value by 4.
    // Also, we want timerCount to be odd number, so the ligth state ends in the same state it starts.
    identifyTimerCount = (*value) * 4;

    SystemLayer.CancelTimer(IdentifyTimerHandler, this);
    SystemLayer.StartTimer(kIdentifyTimerDelayMS, IdentifyTimerHandler, this);

exit:
    return;
}
<commit_msg>Fix the identify timer logic on the esp32 all-clusters-app (#3917)<commit_after>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *    All rights reserved.
 *
 *    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.
 */

/**
 * @file DeviceCallbacks.cpp
 *
 * Implements all the callbacks to the application from the CHIP Stack
 *
 **/
#include "DeviceCallbacks.h"

#include "CHIPDeviceManager.h"
#include "Globals.h"
#include "LEDWidget.h"
#include "WiFiWidget.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "gen/attribute-id.h"
#include "gen/cluster-id.h"
#include <app/util/basic-types.h>
#include <lib/mdns/DiscoveryManager.h>
#include <support/CodeUtils.h>

static const char * TAG = "app-devicecallbacks";

using namespace ::chip;
using namespace ::chip::Inet;
using namespace ::chip::System;
using namespace ::chip::DeviceLayer;

uint32_t identifyTimerCount;
constexpr uint32_t kIdentifyTimerDelayMS = 250;

void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg)
{
    switch (event->Type)
    {
    case DeviceEventType::kInternetConnectivityChange:
        OnInternetConnectivityChange(event);
        break;

    case DeviceEventType::kSessionEstablished:
        OnSessionEstablished(event);
        break;
    }

    ESP_LOGI(TAG, "Current free heap: %d\n", heap_caps_get_free_size(MALLOC_CAP_8BIT));
}

void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
                                                  uint16_t manufacturerCode, uint8_t type, uint8_t size, uint8_t * value)
{
    ESP_LOGI(TAG, "PostAttributeChangeCallback - Cluster ID: '0x%04x', EndPoint ID: '0x%02x', Attribute ID: '0x%04x'", clusterId,
             endpointId, attributeId);

    switch (clusterId)
    {
    case ZCL_ON_OFF_CLUSTER_ID:
        OnOnOffPostAttributeChangeCallback(endpointId, attributeId, value);
        break;

    case ZCL_IDENTIFY_CLUSTER_ID:
        OnIdentifyPostAttributeChangeCallback(endpointId, attributeId, value);
        break;

    default:
        ESP_LOGI(TAG, "Unhandled cluster ID: %d", clusterId);
        break;
    }

    ESP_LOGI(TAG, "Current free heap: %d\n", heap_caps_get_free_size(MALLOC_CAP_8BIT));
}

void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event)
{
    if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established)
    {
        ESP_LOGI(TAG, "Server ready at: %s:%d", event->InternetConnectivityChange.address, CHIP_PORT);
        wifiLED.Set(true);
        chip::Mdns::DiscoveryManager::GetInstance().StartPublishDevice();
    }
    else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost)
    {
        ESP_LOGE(TAG, "Lost IPv4 connectivity...");
        wifiLED.Set(false);
    }
    if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established)
    {
        ESP_LOGI(TAG, "IPv6 Server ready...");
        chip::Mdns::DiscoveryManager::GetInstance().StartPublishDevice();
    }
    else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost)
    {
        ESP_LOGE(TAG, "Lost IPv6 connectivity...");
    }
}

void DeviceCallbacks::OnSessionEstablished(const ChipDeviceEvent * event)
{
    if (event->SessionEstablished.IsCommissioner)
    {
        ESP_LOGI(TAG, "Commissioner detected!");
    }
}

void DeviceCallbacks::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value)
{
    VerifyOrExit(attributeId == ZCL_ON_OFF_ATTRIBUTE_ID, ESP_LOGI(TAG, "Unhandled Attribute ID: '0x%04x", attributeId));
    VerifyOrExit(endpointId == 1 || endpointId == 2, ESP_LOGE(TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId));

    // At this point we can assume that value points to a bool value.
    endpointId == 1 ? statusLED1.Set(*value) : statusLED2.Set(*value);

exit:
    return;
}

void IdentifyTimerHandler(Layer * systemLayer, void * appState, Error error)
{
    statusLED1.Animate();

    if (identifyTimerCount)
    {
        SystemLayer.StartTimer(kIdentifyTimerDelayMS, IdentifyTimerHandler, appState);
        // Decrement the timer count.
        identifyTimerCount--;
    }
}

void DeviceCallbacks::OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value)
{
    VerifyOrExit(attributeId == ZCL_IDENTIFY_TIME_ATTRIBUTE_ID, ESP_LOGI(TAG, "Unhandled Attribute ID: '0x%04x", attributeId));
    VerifyOrExit(endpointId == 1, ESP_LOGE(TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId));

    statusLED1.Blink(kIdentifyTimerDelayMS * 2);

    // timerCount represents the number of callback executions before we stop the timer.
    // value is expressed in seconds and the timer is fired every 250ms, so just multiply value by 4.
    // Also, we want timerCount to be odd number, so the ligth state ends in the same state it starts.
    identifyTimerCount = (*value) * 4;

    SystemLayer.CancelTimer(IdentifyTimerHandler, this);
    SystemLayer.StartTimer(kIdentifyTimerDelayMS, IdentifyTimerHandler, this);

exit:
    return;
}
<|endoftext|>


<commit_before>/************************************************************************
    filename:   FalFrameWindow.cpp
    created:    Sat Jul 2 2005
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

    This library 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.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
*************************************************************************/
#include "FalFrameWindow.h"
#include "falagard/CEGUIFalWidgetLookManager.h"
#include "falagard/CEGUIFalWidgetLookFeel.h"
#include "CEGUIWindowManager.h"
#include "elements/CEGUITitlebar.h"
#include "elements/CEGUIPushButton.h"

// Start of CEGUI namespace section
namespace CEGUI
{
    const utf8 FalagardFrameWindow::WidgetTypeName[] = "Falagard/FrameWindow";

    FalagardFrameWindow::FalagardFrameWindow(const String& type, const String& name) :
        FrameWindow(type, name)
    {
    }

    FalagardFrameWindow::~FalagardFrameWindow()
    {
    }

    void FalagardFrameWindow::populateRenderCache()
    {
        // do not render anything for the rolled-up state.
        if (d_rolledup)
            return;

        // build state name
        String stateName(d_enabled ? ((d_parent && d_parent->isActive()) ? "Active" : "Inactive") : "Disabled");
        stateName += d_titlebar->isVisible() ? "WithTitle" : "NoTitle";
        stateName += d_frameEnabled ? "WithFrame" : "NoFrame";

        const StateImagery* imagery;

        try
        {
            // get WidgetLookFeel for the assigned look.
            const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
            // try and get imagery for our current state
            imagery = &wlf.getStateImagery(stateName);
        }
        catch (UnknownObjectException)
        {
            // log error so we know imagery is missing, and then quit.
            return;
        }

        // peform the rendering operation.
        imagery->render(*this);
    }

    Rect FalagardFrameWindow::getUnclippedInnerRect(void) const
    {
        if (d_rolledup)
            return Rect(0,0,0,0);

        // build name of area to fetch
        String areaName("Client");
        areaName += d_titlebar->isVisible() ? "WithTitle" : "NoTitle";
        areaName += d_frameEnabled ? "WithFrame" : "NoFrame";

        // get WidgetLookFeel for the assigned look.
        const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
        return wlf.getNamedArea(areaName).getArea().getPixelRect(*this, getPixelRect());
    }

    Titlebar* FalagardFrameWindow::createTitlebar(const String& name) const
    {
        return static_cast<Titlebar*>(WindowManager::getSingleton().getWindow(getName() + "__auto_titlebar__"));
    }

    PushButton* FalagardFrameWindow::createCloseButton(const String& name) const
    {
        return static_cast<PushButton*>(WindowManager::getSingleton().getWindow(getName() + "__auto_closebutton__"));
    }

    void FalagardFrameWindow::layoutComponentWidgets()
    {
        // get WidgetLookFeel for the assigned look.
        try
        {
            const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
            wlf.layoutChildWidgets(*this);
        }
        catch (UnknownObjectException)
        {}
    }

    //////////////////////////////////////////////////////////////////////////
    /*************************************************************************

        Factory Methods

    *************************************************************************/
    //////////////////////////////////////////////////////////////////////////
    Window* FalagardFrameWindowFactory::createWindow(const String& name)
    {
        return new FalagardFrameWindow(d_type, name);
    }

    void FalagardFrameWindowFactory::destroyWindow(Window* window)
    {
        if (window->getType() == d_type)
            delete window;
    }

} // End of  CEGUI namespace section
<commit_msg>Fixed bug in code that selected which state to use.<commit_after>/************************************************************************
    filename:   FalFrameWindow.cpp
    created:    Sat Jul 2 2005
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

    This library 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.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
*************************************************************************/
#include "FalFrameWindow.h"
#include "falagard/CEGUIFalWidgetLookManager.h"
#include "falagard/CEGUIFalWidgetLookFeel.h"
#include "CEGUIWindowManager.h"
#include "elements/CEGUITitlebar.h"
#include "elements/CEGUIPushButton.h"

// Start of CEGUI namespace section
namespace CEGUI
{
    const utf8 FalagardFrameWindow::WidgetTypeName[] = "Falagard/FrameWindow";

    FalagardFrameWindow::FalagardFrameWindow(const String& type, const String& name) :
        FrameWindow(type, name)
    {
    }

    FalagardFrameWindow::~FalagardFrameWindow()
    {
    }

    void FalagardFrameWindow::populateRenderCache()
    {
        // do not render anything for the rolled-up state.
        if (d_rolledup)
            return;

        // build state name
        String stateName(d_enabled ? (isActive() ? "Active" : "Inactive") : "Disabled");
        stateName += d_titlebar->isVisible() ? "WithTitle" : "NoTitle";
        stateName += d_frameEnabled ? "WithFrame" : "NoFrame";

        const StateImagery* imagery;

        try
        {
            // get WidgetLookFeel for the assigned look.
            const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
            // try and get imagery for our current state
            imagery = &wlf.getStateImagery(stateName);
        }
        catch (UnknownObjectException)
        {
            // log error so we know imagery is missing, and then quit.
            return;
        }

        // peform the rendering operation.
        imagery->render(*this);
    }

    Rect FalagardFrameWindow::getUnclippedInnerRect(void) const
    {
        if (d_rolledup)
            return Rect(0,0,0,0);

        // build name of area to fetch
        String areaName("Client");
        areaName += d_titlebar->isVisible() ? "WithTitle" : "NoTitle";
        areaName += d_frameEnabled ? "WithFrame" : "NoFrame";

        // get WidgetLookFeel for the assigned look.
        const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
        return wlf.getNamedArea(areaName).getArea().getPixelRect(*this, getPixelRect());
    }

    Titlebar* FalagardFrameWindow::createTitlebar(const String& name) const
    {
        return static_cast<Titlebar*>(WindowManager::getSingleton().getWindow(getName() + "__auto_titlebar__"));
    }

    PushButton* FalagardFrameWindow::createCloseButton(const String& name) const
    {
        return static_cast<PushButton*>(WindowManager::getSingleton().getWindow(getName() + "__auto_closebutton__"));
    }

    void FalagardFrameWindow::layoutComponentWidgets()
    {
        // get WidgetLookFeel for the assigned look.
        try
        {
            const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
            wlf.layoutChildWidgets(*this);
        }
        catch (UnknownObjectException)
        {}
    }

    //////////////////////////////////////////////////////////////////////////
    /*************************************************************************

        Factory Methods

    *************************************************************************/
    //////////////////////////////////////////////////////////////////////////
    Window* FalagardFrameWindowFactory::createWindow(const String& name)
    {
        return new FalagardFrameWindow(d_type, name);
    }

    void FalagardFrameWindowFactory::destroyWindow(Window* window)
    {
        if (window->getType() == d_type)
            delete window;
    }

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>/*
 * BitboardCA. Cellular Automata using bitboard algorithms.
 * Copyright (C) Toshiyuki Hirooka <toshi.hirooka@gmail.com> http://wasabi.in/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#include "OuterTotalisticCA.h"

#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include "BitboardViewer.h"

using namespace BitboardCA;

OuterTotalisticCA::OuterTotalisticCA(std::size_t size_x, std::size_t size_y)
	: LargeBitboard(size_x, size_y)
{
}

OuterTotalisticCA::~OuterTotalisticCA()
{
}

void OuterTotalisticCA::Step()
{
	BitboardViewer viewer;
	LargeBitboard new_large_bitboard(m_BitboardSizeX, m_BitboardSizeY, true);
	new_large_bitboard.Clear();

	// calc outer totalistic each bitboards
	for ( std::size_t y = 1 ; y < m_BitboardSizeY - 1 ; y++ )
	{
		for ( std::size_t x = 1 ; x < m_BitboardSizeX - 1 ; x++ )
		{
			new_large_bitboard.SetBitboard(StepByOuterTotalistic(
					m_BitboardList[(x  ) + (y  ) * m_BitboardSizeX],
					m_BitboardList[(x-1) + (y-1) * m_BitboardSizeX],
					m_BitboardList[(x  ) + (y-1) * m_BitboardSizeX],
					m_BitboardList[(x+1) + (y-1) * m_BitboardSizeX],
					m_BitboardList[(x-1) + (y  ) * m_BitboardSizeX],
					m_BitboardList[(x+1) + (y  ) * m_BitboardSizeX],
					m_BitboardList[(x-1) + (y+1) * m_BitboardSizeX],
					m_BitboardList[(x  ) + (y+1) * m_BitboardSizeX],
					m_BitboardList[(x+1) + (y+1) * m_BitboardSizeX]
			), x, y);
		}
	}

	// mask for usable a expect multiple of 8
	// mask X
	const static Bitboard MASK_X[8] = {
		0xffffffffffffffffULL,
		0x8080808080808080ULL,
		0xc0c0c0c0c0c0c0c0ULL,
		0xe0e0e0e0e0e0e0e0ULL,
		0xf0f0f0f0f0f0f0f0ULL,
		0xf8f8f8f8f8f8f8f8ULL,
		0xfcfcfcfcfcfcfcfcULL,
		0xfefefefefefefefeULL
	};
	for(std::size_t i=1; i<m_BitboardSizeY; i++)
		new_large_bitboard.SetBitboard(
				new_large_bitboard.GetBitboard(i * m_BitboardSizeX - 2) & MASK_X[m_SizeX % 8],
				i * m_BitboardSizeX - 2);

	// mask Y
	const static Bitboard MASK_Y[8] = {
		0xffffffffffffffffULL,
		0xff00000000000000ULL,
		0xffff000000000000ULL,
		0xffffff0000000000ULL,
		0xffffffff00000000ULL,
		0xffffffffff000000ULL,
		0xffffffffffff0000ULL,
		0xffffffffffffff00ULL
	};
	for(std::size_t i=1; i<m_BitboardSizeX; i++)
		new_large_bitboard.SetBitboard(
				new_large_bitboard.GetBitboard(i + m_BitboardSizeX * (m_BitboardSizeY - 2)) & MASK_Y[m_SizeY % 8],
				i + m_BitboardSizeX * (m_BitboardSizeY - 2));

	// copy back
	for ( std::size_t i = 0 ; i < GetBitboardListSize() ; i ++ )
		m_BitboardList[i] = new_large_bitboard.GetBitboard(i);
}

// explanation in japanese http://d.hatena.ne.jp/tosik/20071115/1195120024
Bitboard OuterTotalisticCA::StepByOuterTotalistic(Bitboard board,
		Bitboard board_a, Bitboard board_b, Bitboard board_c,
		Bitboard board_d,                   Bitboard board_e,
		Bitboard board_f, Bitboard board_g, Bitboard board_h)
{

	Bitboard s0, s1, s2, s3, s4, s5, s6, s7, s8;

	// shift 1 bit to center
	Bitboard a, b, c, d, e, f, g, h;
	a = ( ( board   & 0xfefefefefefefe00ULL ) >> 9  ) | ( ( board_a & 0x0000000000000001ULL ) << 63 ) |
		( ( board_b & 0x00000000000000feULL ) << 55 ) | ( ( board_d & 0x0101010101010100ULL ) >> 1  ) ;
	b = ( ( board   & 0xffffffffffffff00ULL ) >> 8  ) | ( ( board_b & 0x00000000000000ffULL ) << 56 ) ;
	c = ( ( board   & 0x7f7f7f7f7f7f7f00ULL ) >> 7  ) | ( ( board_c & 0x0000000000000080ULL ) << 49 ) |
		( ( board_b & 0x000000000000007fULL ) << 57 ) | ( ( board_e & 0x8080808080808000ULL ) >> 15 ) ;
	d = ( ( board   & 0xfefefefefefefefeULL ) >> 1  ) | ( ( board_d & 0x0101010101010101ULL ) << 7  ) ;
	e = ( ( board   & 0x7f7f7f7f7f7f7f7fULL ) << 1  ) | ( ( board_e & 0x8080808080808080ULL ) >> 7  ) ;
	f = ( ( board   & 0x00fefefefefefefeULL ) << 7  ) | ( ( board_f & 0x0100000000000000ULL ) >> 49 ) |
		( ( board_g & 0xfe00000000000000ULL ) >> 57 ) | ( ( board_d & 0x0001010101010101ULL ) << 15 ) ;
	g = ( ( board   & 0x00ffffffffffffffULL ) << 8  ) | ( ( board_g & 0xff00000000000000ULL ) >> 56 ) ;
	h = ( ( board   & 0x007f7f7f7f7f7f7fULL ) << 9  ) | ( ( board_h & 0x8000000000000000ULL ) >> 63 ) |
		( ( board_g & 0x7f00000000000000ULL ) >> 55 ) | ( ( board_e & 0x0080808080808080ULL ) << 1  ) ;

	// count sums
	// s0..8 are sums of living neighborhoods

	s0 = ~( a | b );
	s1 = a ^ b;
	s2 = a & b;

	s3 = c & s2;
	s2 = ( s2 & ~c ) | ( s1 & c );
	s1 = ( s1 & ~c ) | ( s0 & c );
	s0 = s0 & ~c;

	s4 = d & s3;
	s3 = ( s3 & ~d ) | ( s2 & d );
	s2 = ( s2 & ~d ) | ( s1 & d );
	s1 = ( s1 & ~d ) | ( s0 & d );
	s0 = s0 & ~d;

	s5 = e & s4;
	s4 = ( s4 & ~e ) | ( s3 & e );
	s3 = ( s3 & ~e ) | ( s2 & e );
	s2 = ( s2 & ~e ) | ( s1 & e );
	s1 = ( s1 & ~e ) | ( s0 & e );
	s0 = s0 & ~e;

	s6 = f & s5;
	s5 = ( s5 & ~f ) | ( s4 & f );
	s4 = ( s4 & ~f ) | ( s3 & f );
	s3 = ( s3 & ~f ) | ( s2 & f );
	s2 = ( s2 & ~f ) | ( s1 & f );
	s1 = ( s1 & ~f ) | ( s0 & f );
	s0 = s0 & ~f;

	s7 = g & s6;
	s6 = ( s6 & ~g ) | ( s5 & g );
	s5 = ( s5 & ~g ) | ( s4 & g );
	s4 = ( s4 & ~g ) | ( s3 & g );
	s3 = ( s3 & ~g ) | ( s2 & g );
	s2 = ( s2 & ~g ) | ( s1 & g );
	s1 = ( s1 & ~g ) | ( s0 & g );
	s0 = s0 & ~g;

	s8 = h & s7;
	s7 = ( s7 & ~h ) | ( s6 & h );
	s6 = ( s6 & ~h ) | ( s5 & h );
	s5 = ( s5 & ~h ) | ( s4 & h );
	s4 = ( s4 & ~h ) | ( s3 & h );
	s3 = ( s3 & ~h ) | ( s2 & h );
	s2 = ( s2 & ~h ) | ( s1 & h );
	s1 = ( s1 & ~h ) | ( s0 & h );
	s0 = s0 & ~h;

	// calc optional rule using sums
	return Rule(board, s0, s1, s2, s3, s4, s5, s6, s7, s8);
}

<commit_msg>changed formatting.<commit_after>/*
 * BitboardCA. Cellular Automata using bitboard algorithms.
 * Copyright (C) Toshiyuki Hirooka <toshi.hirooka@gmail.com> http://wasabi.in/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#include "OuterTotalisticCA.h"

#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include "BitboardViewer.h"

using namespace BitboardCA;

OuterTotalisticCA::OuterTotalisticCA(std::size_t size_x, std::size_t size_y)
	: LargeBitboard(size_x, size_y)
{
}

OuterTotalisticCA::~OuterTotalisticCA()
{
}

void OuterTotalisticCA::Step()
{
	BitboardViewer viewer;
	LargeBitboard new_large_bitboard(m_BitboardSizeX, m_BitboardSizeY, true);
	new_large_bitboard.Clear();

	// calc outer totalistic each bitboards
	for ( std::size_t y = 1 ; y < m_BitboardSizeY - 1 ; y++ )
	{
		for ( std::size_t x = 1 ; x < m_BitboardSizeX - 1 ; x++ )
		{
			new_large_bitboard.SetBitboard(StepByOuterTotalistic(
					m_BitboardList[(x  ) + (y  ) * m_BitboardSizeX],
					m_BitboardList[(x-1) + (y-1) * m_BitboardSizeX],
					m_BitboardList[(x  ) + (y-1) * m_BitboardSizeX],
					m_BitboardList[(x+1) + (y-1) * m_BitboardSizeX],
					m_BitboardList[(x-1) + (y  ) * m_BitboardSizeX],
					m_BitboardList[(x+1) + (y  ) * m_BitboardSizeX],
					m_BitboardList[(x-1) + (y+1) * m_BitboardSizeX],
					m_BitboardList[(x  ) + (y+1) * m_BitboardSizeX],
					m_BitboardList[(x+1) + (y+1) * m_BitboardSizeX]
			), x, y);
		}
	}

	// mask for usable a expect multiple of 8
	// mask X
	const static Bitboard MASK_X[8] = {
		0xffffffffffffffffULL,
		0x8080808080808080ULL,
		0xc0c0c0c0c0c0c0c0ULL,
		0xe0e0e0e0e0e0e0e0ULL,
		0xf0f0f0f0f0f0f0f0ULL,
		0xf8f8f8f8f8f8f8f8ULL,
		0xfcfcfcfcfcfcfcfcULL,
		0xfefefefefefefefeULL
	};
	for ( std::size_t i = 1 ; i < m_BitboardSizeY ; i ++)
		new_large_bitboard.SetBitboard(
				new_large_bitboard.GetBitboard(i * m_BitboardSizeX - 2) & MASK_X[m_SizeX % 8],
				i * m_BitboardSizeX - 2);

	// mask Y
	const static Bitboard MASK_Y[8] = {
		0xffffffffffffffffULL,
		0xff00000000000000ULL,
		0xffff000000000000ULL,
		0xffffff0000000000ULL,
		0xffffffff00000000ULL,
		0xffffffffff000000ULL,
		0xffffffffffff0000ULL,
		0xffffffffffffff00ULL
	};
	for ( std::size_t i = 1 ; i < m_BitboardSizeX ; i ++)
		new_large_bitboard.SetBitboard(
				new_large_bitboard.GetBitboard(i + m_BitboardSizeX * (m_BitboardSizeY - 2)) & MASK_Y[m_SizeY % 8],
				i + m_BitboardSizeX * (m_BitboardSizeY - 2));

	// copy back
	for ( std::size_t i = 0 ; i < GetBitboardListSize() ; i ++ )
		m_BitboardList[i] = new_large_bitboard.GetBitboard(i);
}

// explanation in japanese http://d.hatena.ne.jp/tosik/20071115/1195120024
Bitboard OuterTotalisticCA::StepByOuterTotalistic(Bitboard board,
		Bitboard board_a, Bitboard board_b, Bitboard board_c,
		Bitboard board_d,                   Bitboard board_e,
		Bitboard board_f, Bitboard board_g, Bitboard board_h)
{

	Bitboard s0, s1, s2, s3, s4, s5, s6, s7, s8;

	// shift 1 bit to center
	Bitboard a, b, c, d, e, f, g, h;
	a = ( ( board   & 0xfefefefefefefe00ULL ) >> 9  ) | ( ( board_a & 0x0000000000000001ULL ) << 63 ) |
		( ( board_b & 0x00000000000000feULL ) << 55 ) | ( ( board_d & 0x0101010101010100ULL ) >> 1  ) ;
	b = ( ( board   & 0xffffffffffffff00ULL ) >> 8  ) | ( ( board_b & 0x00000000000000ffULL ) << 56 ) ;
	c = ( ( board   & 0x7f7f7f7f7f7f7f00ULL ) >> 7  ) | ( ( board_c & 0x0000000000000080ULL ) << 49 ) |
		( ( board_b & 0x000000000000007fULL ) << 57 ) | ( ( board_e & 0x8080808080808000ULL ) >> 15 ) ;
	d = ( ( board   & 0xfefefefefefefefeULL ) >> 1  ) | ( ( board_d & 0x0101010101010101ULL ) << 7  ) ;
	e = ( ( board   & 0x7f7f7f7f7f7f7f7fULL ) << 1  ) | ( ( board_e & 0x8080808080808080ULL ) >> 7  ) ;
	f = ( ( board   & 0x00fefefefefefefeULL ) << 7  ) | ( ( board_f & 0x0100000000000000ULL ) >> 49 ) |
		( ( board_g & 0xfe00000000000000ULL ) >> 57 ) | ( ( board_d & 0x0001010101010101ULL ) << 15 ) ;
	g = ( ( board   & 0x00ffffffffffffffULL ) << 8  ) | ( ( board_g & 0xff00000000000000ULL ) >> 56 ) ;
	h = ( ( board   & 0x007f7f7f7f7f7f7fULL ) << 9  ) | ( ( board_h & 0x8000000000000000ULL ) >> 63 ) |
		( ( board_g & 0x7f00000000000000ULL ) >> 55 ) | ( ( board_e & 0x0080808080808080ULL ) << 1  ) ;

	// count sums
	// s0..8 are sums of living neighborhoods

	s0 = ~( a | b );
	s1 = a ^ b;
	s2 = a & b;

	s3 = c & s2;
	s2 = ( s2 & ~c ) | ( s1 & c );
	s1 = ( s1 & ~c ) | ( s0 & c );
	s0 = s0 & ~c;

	s4 = d & s3;
	s3 = ( s3 & ~d ) | ( s2 & d );
	s2 = ( s2 & ~d ) | ( s1 & d );
	s1 = ( s1 & ~d ) | ( s0 & d );
	s0 = s0 & ~d;

	s5 = e & s4;
	s4 = ( s4 & ~e ) | ( s3 & e );
	s3 = ( s3 & ~e ) | ( s2 & e );
	s2 = ( s2 & ~e ) | ( s1 & e );
	s1 = ( s1 & ~e ) | ( s0 & e );
	s0 = s0 & ~e;

	s6 = f & s5;
	s5 = ( s5 & ~f ) | ( s4 & f );
	s4 = ( s4 & ~f ) | ( s3 & f );
	s3 = ( s3 & ~f ) | ( s2 & f );
	s2 = ( s2 & ~f ) | ( s1 & f );
	s1 = ( s1 & ~f ) | ( s0 & f );
	s0 = s0 & ~f;

	s7 = g & s6;
	s6 = ( s6 & ~g ) | ( s5 & g );
	s5 = ( s5 & ~g ) | ( s4 & g );
	s4 = ( s4 & ~g ) | ( s3 & g );
	s3 = ( s3 & ~g ) | ( s2 & g );
	s2 = ( s2 & ~g ) | ( s1 & g );
	s1 = ( s1 & ~g ) | ( s0 & g );
	s0 = s0 & ~g;

	s8 = h & s7;
	s7 = ( s7 & ~h ) | ( s6 & h );
	s6 = ( s6 & ~h ) | ( s5 & h );
	s5 = ( s5 & ~h ) | ( s4 & h );
	s4 = ( s4 & ~h ) | ( s3 & h );
	s3 = ( s3 & ~h ) | ( s2 & h );
	s2 = ( s2 & ~h ) | ( s1 & h );
	s1 = ( s1 & ~h ) | ( s0 & h );
	s0 = s0 & ~h;

	// calc optional rule using sums
	return Rule(board, s0, s1, s2, s3, s4, s5, s6, s7, s8);
}

<|endoftext|>


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

#include <folly/experimental/SingletonRelaxedCounter.h>

#include <cstddef>
#include <thread>

#include <boost/thread/barrier.hpp>

#include <folly/Benchmark.h>
#include <folly/init/Init.h>
#include <folly/portability/GFlags.h>

DEFINE_int32(num_threads, 4, "No. of threads allocting the objects");

namespace folly {

namespace {
struct PrivateTag {};
} // namespace

using Counter = SingletonRelaxedCounter<size_t, PrivateTag>;

// small wrappers around the functions being benchmarked
// useful for looking at the inlined native code of the fast path
extern "C" void check() noexcept {
  Counter::add(1);
}

// a noop which the compiler cannot see through
// used to prevent some compiler optimizations which could skew benchmarks
[[gnu::weak]] void noop() noexcept {}

BENCHMARK(MultiThreadPerformance, iters) {
  BenchmarkSuspender braces;

  boost::barrier barrier(1 + FLAGS_num_threads);

  std::vector<std::thread> threads(FLAGS_num_threads);

  for (auto& thread : threads) {
    thread = std::thread([&] {
      auto once = [] {
        noop();
        Counter::add(1);
        noop();
        Counter::sub(1);
      };

      // in case the first call does expensive setup, such as take a global lock
      once();

      barrier.wait(); // A - wait for thread start

      barrier.wait(); // B - init the work

      for (auto i = 0u; i < iters; ++i) {
        once();
      }

      barrier.wait(); // C - join the work
    });
  }

  barrier.wait(); // A - wait for thread start

  // we want to exclude thread start/stop operations from measurement
  braces.dismissing([&] {
    barrier.wait(); // B - init the work
    barrier.wait(); // C - join the work
  });

  for (auto& thread : threads) {
    thread.join();
  }
}
} // namespace folly

int main(int argc, char** argv) {
  folly::Init init(&argc, &argv);
  folly::runBenchmarks();
  return 0;
}
<commit_msg>revise SingletonRelaxedCounter check functions<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/experimental/SingletonRelaxedCounter.h>

#include <cstddef>
#include <thread>

#include <boost/thread/barrier.hpp>

#include <folly/Benchmark.h>
#include <folly/init/Init.h>
#include <folly/lang/Keep.h>
#include <folly/portability/GFlags.h>

DEFINE_int32(num_threads, 4, "No. of threads allocting the objects");

namespace {
struct PrivateTag {};
} // namespace

using Counter = folly::SingletonRelaxedCounter<size_t, PrivateTag>;

// small wrappers around the functions being benchmarked
// useful for looking at the inlined native code of the fast path
extern "C" FOLLY_KEEP void check_singleton_relaxed_counter_add_1() {
  Counter::add(1);
}
extern "C" FOLLY_KEEP void check_singleton_relaxed_counter_add(size_t i) {
  Counter::add(i);
}

namespace folly {

// a noop which the compiler cannot see through
// used to prevent some compiler optimizations which could skew benchmarks
[[gnu::weak]] void noop() noexcept {}

BENCHMARK(MultiThreadPerformance, iters) {
  BenchmarkSuspender braces;

  boost::barrier barrier(1 + FLAGS_num_threads);

  std::vector<std::thread> threads(FLAGS_num_threads);

  for (auto& thread : threads) {
    thread = std::thread([&] {
      auto once = [] {
        noop();
        Counter::add(1);
        noop();
        Counter::sub(1);
      };

      // in case the first call does expensive setup, such as take a global lock
      once();

      barrier.wait(); // A - wait for thread start

      barrier.wait(); // B - init the work

      for (auto i = 0u; i < iters; ++i) {
        once();
      }

      barrier.wait(); // C - join the work
    });
  }

  barrier.wait(); // A - wait for thread start

  // we want to exclude thread start/stop operations from measurement
  braces.dismissing([&] {
    barrier.wait(); // B - init the work
    barrier.wait(); // C - join the work
  });

  for (auto& thread : threads) {
    thread.join();
  }
}
} // namespace folly

int main(int argc, char** argv) {
  folly::Init init(&argc, &argv);
  folly::runBenchmarks();
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: toolbarcontrollerfactory.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-22 10:42:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
#define __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_
#include <com/sun/star/frame/XUIControllerRegistration.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

namespace framework
{

class ConfigurationAccess_ToolbarControllerFactory;
class ToolbarControllerFactory :  public com::sun::star::lang::XTypeProvider                        ,
                                  public com::sun::star::lang::XServiceInfo                         ,
                                  public com::sun::star::lang::XMultiComponentFactory               ,
                                  public ::com::sun::star::frame::XUIControllerRegistration   ,
                                  private ThreadHelpBase                                            ,   // Struct for right initalization of mutex member! Must be first of baseclasses.
                                  public ::cppu::OWeakObject
{
    public:
        ToolbarControllerFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
        virtual ~ToolbarControllerFactory();

        //  XInterface, XTypeProvider, XServiceInfo
        FWK_DECLARE_XINTERFACE
        FWK_DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        // XMultiComponentFactory
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithContext( const ::rtl::OUString& aServiceSpecifier, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArgumentsAndContext( const ::rtl::OUString& ServiceSpecifier, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames() throw (::com::sun::star::uno::RuntimeException);

        // XUIControllerRegistration
        virtual sal_Bool SAL_CALL hasController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL registerController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName, const ::rtl::OUString& aControllerImplementationName ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL deregisterController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);

    private:
        sal_Bool                                                                         m_bConfigRead;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
        ConfigurationAccess_ToolbarControllerFactory*                                    m_pConfigAccess;
};

} // namespace framework

#endif // __FRAMEWORK_SERVICES_TOOLBARCONTROLLERFACTORY_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.6.226); FILE MERGED 2008/04/01 15:18:30 thb 1.6.226.3: #i85898# Stripping all external header guards 2008/04/01 10:57:59 thb 1.6.226.2: #i85898# Stripping all external header guards 2008/03/28 15:34:59 rt 1.6.226.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: toolbarcontrollerfactory.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
#define __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#include <threadhelp/threadhelpbase.hxx>
#include <macros/generic.hxx>
#include <macros/xinterface.hxx>
#include <macros/xtypeprovider.hxx>
#include <macros/xserviceinfo.hxx>
#include <stdtypes.h>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/frame/XUIControllerRegistration.hpp>

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________
#include <cppuhelper/weak.hxx>
#include <rtl/ustring.hxx>

namespace framework
{

class ConfigurationAccess_ToolbarControllerFactory;
class ToolbarControllerFactory :  public com::sun::star::lang::XTypeProvider                        ,
                                  public com::sun::star::lang::XServiceInfo                         ,
                                  public com::sun::star::lang::XMultiComponentFactory               ,
                                  public ::com::sun::star::frame::XUIControllerRegistration   ,
                                  private ThreadHelpBase                                            ,   // Struct for right initalization of mutex member! Must be first of baseclasses.
                                  public ::cppu::OWeakObject
{
    public:
        ToolbarControllerFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
        virtual ~ToolbarControllerFactory();

        //  XInterface, XTypeProvider, XServiceInfo
        FWK_DECLARE_XINTERFACE
        FWK_DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        // XMultiComponentFactory
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithContext( const ::rtl::OUString& aServiceSpecifier, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArgumentsAndContext( const ::rtl::OUString& ServiceSpecifier, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames() throw (::com::sun::star::uno::RuntimeException);

        // XUIControllerRegistration
        virtual sal_Bool SAL_CALL hasController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL registerController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName, const ::rtl::OUString& aControllerImplementationName ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL deregisterController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);

    private:
        sal_Bool                                                                         m_bConfigRead;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
        ConfigurationAccess_ToolbarControllerFactory*                                    m_pConfigAccess;
};

} // namespace framework

#endif // __FRAMEWORK_SERVICES_TOOLBARCONTROLLERFACTORY_HXX_
<|endoftext|>


<commit_before>#include "client.h"

#include <boost/algorithm/string.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/assert.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string.h>

#include "random.h"

const static boost::posix_time::millisec DEFAULT_ASSET_TIMEOUT(500);

using namespace std;
namespace asio = boost::asio;

using namespace bithorde;

AssetBinding::AssetBinding(Client* client, Asset* asset, Asset::Handle handle) :
	_client(client),
	_asset(asset),
	_handle(handle),
	_statusTimer(client->_ioSvc)
{
}

Asset* AssetBinding::asset() const
{
	return _asset;
}

ReadAsset* AssetBinding::readAsset() const
{
	return dynamic_cast<ReadAsset*>(_asset);
}

void AssetBinding::close()
{
	_asset = NULL;
	setTimer(DEFAULT_ASSET_TIMEOUT);
}

void AssetBinding::setTimer(const boost::posix_time::time_duration& timeout)
{
	_timerCancelled = false;
	_statusTimer.expires_from_now(timeout);
	_statusTimer.async_wait(boost::bind(&AssetBinding::onTimeout, shared_from_this(), boost::asio::placeholders::error));
}

void AssetBinding::clearTimer()
{
	_timerCancelled = true;
	_statusTimer.cancel();
}

void AssetBinding::orphaned()
{
	_client = NULL;
	clearTimer();
}

void AssetBinding::onTimeout(const boost::system::error_code& error)
{
	if (error || _timerCancelled)
		return;
	if (_asset) {
		bithorde::AssetStatus msg;
		msg.set_status(bithorde::Status::TIMEOUT);
		_asset->handleMessage(msg);
	} else if (_client) {
		_client->informBound(*this, rand64(), DEFAULT_ASSET_TIMEOUT.total_milliseconds());
		setTimer(DEFAULT_ASSET_TIMEOUT);
	}
}

Client::Client(asio::io_service& ioSvc, string myName) :
	_ioSvc(ioSvc),
	_connection(),
	_myName(myName),
	_handleAllocator(1),
	_rpcIdAllocator(1),
	_protoVersion(0)
{
}

Client::~Client()
{
	for (auto iter = _assetMap.begin(); iter != _assetMap.end(); iter++) {
		iter->second->orphaned();
	}
}

void Client::connect(Connection::Pointer newConn) {
	BOOST_ASSERT(!_connection);

	_rpcIdAllocator.reset();
	_connection = newConn;

	_messageConnection = _connection->message.connect(Connection::MessageSignal::slot_type(&Client::onIncomingMessage, this, _1, _2));
	_writableConnection = _connection->writable.connect(writable);
	_disconnectedConnection = _connection->disconnected.connect(Connection::VoidSignal::slot_type(&Client::onDisconnected, this));

	sayHello();
}

void Client::connect(asio::ip::tcp::endpoint& ep) {
	connect(Connection::create(_ioSvc, ep));
}

void Client::connect(asio::local::stream_protocol::endpoint& ep) {
	connect(Connection::create(_ioSvc, ep));
}

void Client::connect(string spec) {
	vector<string> host_port;
	if (spec[0] == '/') {
		asio::local::stream_protocol::endpoint ep(spec);
		connect(ep);
	} else if (boost::algorithm::split(host_port, spec, boost::algorithm::is_any_of(":"), boost::algorithm::token_compress_on).size() == 2) {
		asio::ip::tcp::resolver resolver(_ioSvc);
		asio::ip::tcp::resolver::query q(host_port[0], host_port[1]);
		asio::ip::tcp::resolver::iterator iter = resolver.resolve(q);
		if (iter != asio::ip::tcp::resolver::iterator()) {
			asio::ip::tcp::endpoint ep(iter->endpoint());
			connect(ep);
		}
	} else {
		throw string("Failed to parse: " + spec);
	}
}

void Client::onDisconnected() {
	_connection.reset();
	for (auto iter=_assetMap.begin(); iter != _assetMap.end(); iter++) {
		auto binding = iter->second;
		if (binding) {
			binding->clearTimer();
			auto asset = binding->readAsset();
			if (asset) {
				bithorde::AssetStatus s;
				s.set_status(bithorde::DISCONNECTED);
				asset->statusUpdate(s);
			} else {
				_handleAllocator.free(iter->first);
				_assetMap.erase(iter);
			}
		}
	}
	disconnected();
}

bool Client::isConnected()
{
	return _connection;
}

const std::string& Client::peerName()
{
	return _peerName;
}

bool Client::sendMessage(Connection::MessageType type, const google::protobuf::Message& msg, const Message::Deadline& expires)
{
	BOOST_ASSERT(_connection);

	return _connection->sendMessage(type, msg, expires, false);
}

void Client::sayHello() {
	bithorde::HandShake h;
	h.set_protoversion(2);
	h.set_name(_myName);

	sendMessage(Connection::MessageType::HandShake, h);
}

void Client::onIncomingMessage(Connection::MessageType type, ::google::protobuf::Message& msg)
{
	switch (type) {
	case Connection::MessageType::HandShake: return onMessage((bithorde::HandShake&) msg);
	case Connection::MessageType::BindRead: return onMessage((bithorde::BindRead&) msg);
	case Connection::MessageType::AssetStatus: return onMessage((bithorde::AssetStatus&) msg);
	case Connection::MessageType::ReadRequest: return onMessage((bithorde::Read::Request&) msg);
	case Connection::MessageType::ReadResponse: return onMessage((bithorde::Read::Response&) msg);
	case Connection::MessageType::BindWrite: return onMessage((bithorde::BindWrite&) msg);
	case Connection::MessageType::DataSegment: return onMessage((bithorde::DataSegment&) msg);
	case Connection::MessageType::HandShakeConfirmed: return onMessage((bithorde::HandShakeConfirmed&) msg);
	case Connection::MessageType::Ping: return onMessage((bithorde::Ping&) msg);
	}
}

void Client::onMessage(const bithorde::HandShake &msg)
{
	if (msg.protoversion() >= 2) {
		_protoVersion = 2;
	} else {
		cerr << "Only Protocol-version 2 or higher supported" << endl;
		_connection->close();
		_connection.reset();
		return;
	}

	_peerName = msg.name();

	if (msg.has_challenge()) {
		cerr << "Challenge required" << endl;
		// Setup encryption
	} else {
		for (auto iter = _assetMap.begin(); iter != _assetMap.end(); iter++) {
			BOOST_ASSERT(iter->second->readAsset());
			informBound(*iter->second, rand64(), DEFAULT_ASSET_TIMEOUT.total_milliseconds());
		}

		authenticated(_peerName);
	}
}

void Client::onMessage(bithorde::BindRead & msg) {
	cerr << "unsupported: handling BindRead" << endl;
	bithorde::AssetStatus resp;
	resp.set_handle(msg.handle());
	resp.set_status(ERROR);
	sendMessage(Connection::MessageType::AssetStatus, resp);
}

void Client::onMessage(const bithorde::AssetStatus & msg) {
	if (!msg.has_handle())
		return;
	Asset::Handle handle = msg.handle();
	if (_assetMap.count(handle)) {
		AssetBinding& a = *_assetMap[handle];
		a.clearTimer();
		if (a) {
			a->handleMessage(msg);
		} else if (msg.status() != bithorde::Status::SUCCESS) {
			_assetMap.erase(handle);
			_handleAllocator.free(handle);
		} else {
			cerr << "WARNING: " << peerName() << ':' << handle << " Status OK recieved for Asset supposedly closed or re-written." << endl;
		}
	} else if (msg.ids_size()) {
		cerr << "WARNING: " << peerName() << ':' << handle << " AssetStatus " << bithorde::Status_Name(msg.status()) << " for unmapped handle" << endl;
	}
}

void Client::onMessage(const bithorde::Read::Request & msg) {
	cerr << "unsupported: handling Read-Requests" << endl;
	bithorde::Read::Response resp;
	resp.set_reqid(msg.reqid());
	resp.set_status(ERROR);
	sendMessage(Connection::MessageType::ReadResponse, resp);
}

void Client::onMessage(const bithorde::Read::Response & msg) {
	if (_requestIdMap.count(msg.reqid())) {
		Asset::Handle assetHandle = _requestIdMap[msg.reqid()];
		releaseRPCRequest(msg.reqid());
		if (_assetMap.count(assetHandle)) {
			Asset* a = _assetMap[assetHandle]->asset();
			if (a) {
				a->handleMessage(msg);
			} else {
				cerr << "WARNING: ReadResponse " << msg.reqid() << " for handle being closed " << assetHandle << endl;
			}
		} else {
			cerr << "WARNING: ReadResponse " << msg.reqid() << " for unmapped handle " << assetHandle << endl;
		}
	} else {
		cerr << "WARNING: ReadResponse with unknown requestId" << endl;
	}
}

void Client::onMessage(const bithorde::BindWrite & msg) {
	cerr << "unsupported: handling BindWrite" << endl;
	bithorde::AssetStatus resp;
	resp.set_handle(msg.handle());
	resp.set_status(ERROR);
	sendMessage(Connection::MessageType::AssetStatus, resp);
}
void Client::onMessage(const bithorde::DataSegment & msg) {
	cerr << "unsupported: handling DataSegment-pushes" << endl;
	_connection->close();
}
void Client::onMessage(const bithorde::HandShakeConfirmed & msg) {
	cerr << "unsupported: challenge-response handshakes" << endl;
	_connection->close();
}
void Client::onMessage(const bithorde::Ping & msg) {
	bithorde::Ping reply;
	_connection->sendMessage(Connection::MessageType::Ping, reply, Message::NEVER, false);
}

bool Client::bind(ReadAsset &asset) {
	return bind(asset, rand64(), DEFAULT_ASSET_TIMEOUT.total_milliseconds());
}

bool Client::bind(ReadAsset& asset, uint64_t uuid, int timeout_ms) {
	if (!asset.isBound()) {
		BOOST_ASSERT(asset._handle < 0);
		BOOST_ASSERT(asset.requestIds().size() > 0);
		asset._handle = _handleAllocator.allocate();
		BOOST_ASSERT(asset._handle > 0);
		BOOST_ASSERT(_assetMap.count(asset._handle) == 0);
		auto& bind = _assetMap[asset._handle];
		bind = boost::make_shared<AssetBinding>(this, &asset, asset._handle);
		bind->setTimer(boost::posix_time::millisec(timeout_ms));
	}

	return informBound(*_assetMap[asset._handle], uuid, timeout_ms);
}

bool Client::bind(UploadAsset & asset)
{
	BOOST_ASSERT(asset._client.get() == this);
	BOOST_ASSERT(asset._handle < 0);
	BOOST_ASSERT(asset.size() > 0);
	asset._handle = _handleAllocator.allocate();
	auto& bind = _assetMap[asset._handle];
	bind = boost::make_shared<AssetBinding>(this, &asset, asset._handle);
	bind->setTimer(DEFAULT_ASSET_TIMEOUT);
	bithorde::BindWrite msg;
	msg.set_handle(asset._handle);
	msg.set_size(asset.size());
	const auto& link = asset.link();
	if (!link.empty())
		msg.set_linkpath(link.string());
	return _connection->sendMessage(Connection::MessageType::BindWrite, msg, Message::NEVER, false);
}

bool Client::release(Asset & asset)
{
	BOOST_ASSERT(asset.isBound());
	BOOST_ASSERT(_assetMap.find(asset._handle) != _assetMap.end());

	auto& binding = *_assetMap[asset._handle];

	// Leave binding dangling, so it won't be reused until confirmation has been received from the other side.
	binding.close();
	asset._handle = -1;

	if (_connection)
		return informBound(binding, rand64(), DEFAULT_ASSET_TIMEOUT.total_milliseconds());
	else
		return true; // Since connection is down, other side should not have the bound state as it is.
}

bool Client::informBound(const AssetBinding& asset, uint64_t uuid, int timeout_ms)
{
	BOOST_ASSERT(asset._handle >= 0);

	if (!_connection)
		return false;

	bithorde::BindRead msg;
	msg.set_handle(asset._handle);

	ReadAsset * readAsset = asset.readAsset();
	if (readAsset)
		msg.mutable_ids()->CopyFrom(readAsset->requestIds());
	msg.set_timeout(timeout_ms);
	msg.set_uuid(uuid);

	return _connection->sendMessage(Connection::MessageType::BindRead, msg, Message::in(timeout_ms), true);
}

int Client::allocRPCRequest(Asset::Handle asset)
{
	int res = _rpcIdAllocator.allocate();
	_requestIdMap[res] = asset;
	return res;
}

void Client::releaseRPCRequest(int reqId)
{
	if (_requestIdMap.erase(reqId))
		_rpcIdAllocator.free(reqId);
}
<commit_msg>[lib/client]Use different default timeouts for binding and closing assets.<commit_after>#include "client.h"

#include <boost/algorithm/string.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/assert.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string.h>

#include "random.h"

const static boost::posix_time::millisec DEFAULT_ASSET_TIMEOUT(1500);
const static boost::posix_time::millisec CLOSE_TIMEOUT(300);

using namespace std;
namespace asio = boost::asio;

using namespace bithorde;

AssetBinding::AssetBinding(Client* client, Asset* asset, Asset::Handle handle) :
	_client(client),
	_asset(asset),
	_handle(handle),
	_statusTimer(client->_ioSvc)
{
}

Asset* AssetBinding::asset() const
{
	return _asset;
}

ReadAsset* AssetBinding::readAsset() const
{
	return dynamic_cast<ReadAsset*>(_asset);
}

void AssetBinding::close()
{
	_asset = NULL;
	setTimer(CLOSE_TIMEOUT);
}

void AssetBinding::setTimer(const boost::posix_time::time_duration& timeout)
{
	_timerCancelled = false;
	_statusTimer.expires_from_now(timeout);
	_statusTimer.async_wait(boost::bind(&AssetBinding::onTimeout, shared_from_this(), boost::asio::placeholders::error));
}

void AssetBinding::clearTimer()
{
	_timerCancelled = true;
	_statusTimer.cancel();
}

void AssetBinding::orphaned()
{
	_client = NULL;
	clearTimer();
}

void AssetBinding::onTimeout(const boost::system::error_code& error)
{
	if (error || _timerCancelled)
		return;
	if (_asset) {
		bithorde::AssetStatus msg;
		msg.set_status(bithorde::Status::TIMEOUT);
		_asset->handleMessage(msg);
	} else if (_client) {
		_client->informBound(*this, rand64(), CLOSE_TIMEOUT.total_milliseconds());
		setTimer(CLOSE_TIMEOUT);
	}
}

Client::Client(asio::io_service& ioSvc, string myName) :
	_ioSvc(ioSvc),
	_connection(),
	_myName(myName),
	_handleAllocator(1),
	_rpcIdAllocator(1),
	_protoVersion(0)
{
}

Client::~Client()
{
	for (auto iter = _assetMap.begin(); iter != _assetMap.end(); iter++) {
		iter->second->orphaned();
	}
}

void Client::connect(Connection::Pointer newConn) {
	BOOST_ASSERT(!_connection);

	_rpcIdAllocator.reset();
	_connection = newConn;

	_messageConnection = _connection->message.connect(Connection::MessageSignal::slot_type(&Client::onIncomingMessage, this, _1, _2));
	_writableConnection = _connection->writable.connect(writable);
	_disconnectedConnection = _connection->disconnected.connect(Connection::VoidSignal::slot_type(&Client::onDisconnected, this));

	sayHello();
}

void Client::connect(asio::ip::tcp::endpoint& ep) {
	connect(Connection::create(_ioSvc, ep));
}

void Client::connect(asio::local::stream_protocol::endpoint& ep) {
	connect(Connection::create(_ioSvc, ep));
}

void Client::connect(string spec) {
	vector<string> host_port;
	if (spec[0] == '/') {
		asio::local::stream_protocol::endpoint ep(spec);
		connect(ep);
	} else if (boost::algorithm::split(host_port, spec, boost::algorithm::is_any_of(":"), boost::algorithm::token_compress_on).size() == 2) {
		asio::ip::tcp::resolver resolver(_ioSvc);
		asio::ip::tcp::resolver::query q(host_port[0], host_port[1]);
		asio::ip::tcp::resolver::iterator iter = resolver.resolve(q);
		if (iter != asio::ip::tcp::resolver::iterator()) {
			asio::ip::tcp::endpoint ep(iter->endpoint());
			connect(ep);
		}
	} else {
		throw string("Failed to parse: " + spec);
	}
}

void Client::onDisconnected() {
	_connection.reset();
	for (auto iter=_assetMap.begin(); iter != _assetMap.end(); iter++) {
		auto binding = iter->second;
		if (binding) {
			binding->clearTimer();
			auto asset = binding->readAsset();
			if (asset) {
				bithorde::AssetStatus s;
				s.set_status(bithorde::DISCONNECTED);
				asset->statusUpdate(s);
			} else {
				_handleAllocator.free(iter->first);
				_assetMap.erase(iter);
			}
		}
	}
	disconnected();
}

bool Client::isConnected()
{
	return _connection;
}

const std::string& Client::peerName()
{
	return _peerName;
}

bool Client::sendMessage(Connection::MessageType type, const google::protobuf::Message& msg, const Message::Deadline& expires)
{
	BOOST_ASSERT(_connection);

	return _connection->sendMessage(type, msg, expires, false);
}

void Client::sayHello() {
	bithorde::HandShake h;
	h.set_protoversion(2);
	h.set_name(_myName);

	sendMessage(Connection::MessageType::HandShake, h);
}

void Client::onIncomingMessage(Connection::MessageType type, ::google::protobuf::Message& msg)
{
	switch (type) {
	case Connection::MessageType::HandShake: return onMessage((bithorde::HandShake&) msg);
	case Connection::MessageType::BindRead: return onMessage((bithorde::BindRead&) msg);
	case Connection::MessageType::AssetStatus: return onMessage((bithorde::AssetStatus&) msg);
	case Connection::MessageType::ReadRequest: return onMessage((bithorde::Read::Request&) msg);
	case Connection::MessageType::ReadResponse: return onMessage((bithorde::Read::Response&) msg);
	case Connection::MessageType::BindWrite: return onMessage((bithorde::BindWrite&) msg);
	case Connection::MessageType::DataSegment: return onMessage((bithorde::DataSegment&) msg);
	case Connection::MessageType::HandShakeConfirmed: return onMessage((bithorde::HandShakeConfirmed&) msg);
	case Connection::MessageType::Ping: return onMessage((bithorde::Ping&) msg);
	}
}

void Client::onMessage(const bithorde::HandShake &msg)
{
	if (msg.protoversion() >= 2) {
		_protoVersion = 2;
	} else {
		cerr << "Only Protocol-version 2 or higher supported" << endl;
		_connection->close();
		_connection.reset();
		return;
	}

	_peerName = msg.name();

	if (msg.has_challenge()) {
		cerr << "Challenge required" << endl;
		// Setup encryption
	} else {
		for (auto iter = _assetMap.begin(); iter != _assetMap.end(); iter++) {
			BOOST_ASSERT(iter->second->readAsset());
			informBound(*iter->second, rand64(), DEFAULT_ASSET_TIMEOUT.total_milliseconds());
		}

		authenticated(_peerName);
	}
}

void Client::onMessage(bithorde::BindRead & msg) {
	cerr << "unsupported: handling BindRead" << endl;
	bithorde::AssetStatus resp;
	resp.set_handle(msg.handle());
	resp.set_status(ERROR);
	sendMessage(Connection::MessageType::AssetStatus, resp);
}

void Client::onMessage(const bithorde::AssetStatus & msg) {
	if (!msg.has_handle())
		return;
	Asset::Handle handle = msg.handle();
	if (_assetMap.count(handle)) {
		AssetBinding& a = *_assetMap[handle];
		a.clearTimer();
		if (a) {
			a->handleMessage(msg);
		} else if (msg.status() != bithorde::Status::SUCCESS) {
			_assetMap.erase(handle);
			_handleAllocator.free(handle);
		} else {
			cerr << "WARNING: " << peerName() << ':' << handle << " Status OK recieved for Asset supposedly closed or re-written." << endl;
		}
	} else if (msg.ids_size()) {
		cerr << "WARNING: " << peerName() << ':' << handle << " AssetStatus " << bithorde::Status_Name(msg.status()) << " for unmapped handle" << endl;
	}
}

void Client::onMessage(const bithorde::Read::Request & msg) {
	cerr << "unsupported: handling Read-Requests" << endl;
	bithorde::Read::Response resp;
	resp.set_reqid(msg.reqid());
	resp.set_status(ERROR);
	sendMessage(Connection::MessageType::ReadResponse, resp);
}

void Client::onMessage(const bithorde::Read::Response & msg) {
	if (_requestIdMap.count(msg.reqid())) {
		Asset::Handle assetHandle = _requestIdMap[msg.reqid()];
		releaseRPCRequest(msg.reqid());
		if (_assetMap.count(assetHandle)) {
			Asset* a = _assetMap[assetHandle]->asset();
			if (a) {
				a->handleMessage(msg);
			} else {
				cerr << "WARNING: ReadResponse " << msg.reqid() << " for handle being closed " << assetHandle << endl;
			}
		} else {
			cerr << "WARNING: ReadResponse " << msg.reqid() << " for unmapped handle " << assetHandle << endl;
		}
	} else {
		cerr << "WARNING: ReadResponse with unknown requestId" << endl;
	}
}

void Client::onMessage(const bithorde::BindWrite & msg) {
	cerr << "unsupported: handling BindWrite" << endl;
	bithorde::AssetStatus resp;
	resp.set_handle(msg.handle());
	resp.set_status(ERROR);
	sendMessage(Connection::MessageType::AssetStatus, resp);
}
void Client::onMessage(const bithorde::DataSegment & msg) {
	cerr << "unsupported: handling DataSegment-pushes" << endl;
	_connection->close();
}
void Client::onMessage(const bithorde::HandShakeConfirmed & msg) {
	cerr << "unsupported: challenge-response handshakes" << endl;
	_connection->close();
}
void Client::onMessage(const bithorde::Ping & msg) {
	bithorde::Ping reply;
	_connection->sendMessage(Connection::MessageType::Ping, reply, Message::NEVER, false);
}

bool Client::bind(ReadAsset &asset) {
	return bind(asset, rand64(), DEFAULT_ASSET_TIMEOUT.total_milliseconds());
}

bool Client::bind(ReadAsset& asset, uint64_t uuid, int timeout_ms) {
	if (!asset.isBound()) {
		BOOST_ASSERT(asset._handle < 0);
		BOOST_ASSERT(asset.requestIds().size() > 0);
		asset._handle = _handleAllocator.allocate();
		BOOST_ASSERT(asset._handle > 0);
		BOOST_ASSERT(_assetMap.count(asset._handle) == 0);
		auto& bind = _assetMap[asset._handle];
		bind = boost::make_shared<AssetBinding>(this, &asset, asset._handle);
		bind->setTimer(boost::posix_time::millisec(timeout_ms));
	}

	return informBound(*_assetMap[asset._handle], uuid, timeout_ms);
}

bool Client::bind(UploadAsset & asset)
{
	BOOST_ASSERT(asset._client.get() == this);
	BOOST_ASSERT(asset._handle < 0);
	BOOST_ASSERT(asset.size() > 0);
	asset._handle = _handleAllocator.allocate();
	auto& bind = _assetMap[asset._handle];
	bind = boost::make_shared<AssetBinding>(this, &asset, asset._handle);
	bind->setTimer(DEFAULT_ASSET_TIMEOUT);
	bithorde::BindWrite msg;
	msg.set_handle(asset._handle);
	msg.set_size(asset.size());
	const auto& link = asset.link();
	if (!link.empty())
		msg.set_linkpath(link.string());
	return _connection->sendMessage(Connection::MessageType::BindWrite, msg, Message::NEVER, false);
}

bool Client::release(Asset & asset)
{
	BOOST_ASSERT(asset.isBound());
	BOOST_ASSERT(_assetMap.find(asset._handle) != _assetMap.end());

	auto& binding = *_assetMap[asset._handle];

	// Leave binding dangling, so it won't be reused until confirmation has been received from the other side.
	binding.close();
	asset._handle = -1;

	if (_connection)
		return informBound(binding, rand64(), DEFAULT_ASSET_TIMEOUT.total_milliseconds());
	else
		return true; // Since connection is down, other side should not have the bound state as it is.
}

bool Client::informBound(const AssetBinding& asset, uint64_t uuid, int timeout_ms)
{
	BOOST_ASSERT(asset._handle >= 0);

	if (!_connection)
		return false;

	bithorde::BindRead msg;
	msg.set_handle(asset._handle);

	ReadAsset * readAsset = asset.readAsset();
	if (readAsset)
		msg.mutable_ids()->CopyFrom(readAsset->requestIds());
	msg.set_timeout(timeout_ms);
	msg.set_uuid(uuid);

	return _connection->sendMessage(Connection::MessageType::BindRead, msg, Message::in(timeout_ms), true);
}

int Client::allocRPCRequest(Asset::Handle asset)
{
	int res = _rpcIdAllocator.allocate();
	_requestIdMap[res] = asset;
	return res;
}

void Client::releaseRPCRequest(int reqId)
{
	if (_requestIdMap.erase(reqId))
		_rpcIdAllocator.free(reqId);
}
<|endoftext|>


<commit_before>/**
 * @file
 * @brief Implementation of default digitization module
 * @copyright MIT License
 */

#include "DefaultDigitizerModule.hpp"

#include "core/utils/unit.h"
#include "tools/ROOT.h"

#include <TFile.h>
#include <TH1D.h>
#include <TProfile.h>

#include "objects/PixelHit.hpp"

using namespace allpix;

DefaultDigitizerModule::DefaultDigitizerModule(Configuration config,
                                               Messenger* messenger,
                                               std::shared_ptr<Detector> detector)
    : Module(config, std::move(detector)), config_(std::move(config)), messenger_(messenger), pixel_message_(nullptr) {
    // Enable parallelization of this module if multithreading is enabled
    enable_parallelization();

    // Require PixelCharge message for single detector
    messenger_->bindSingle(this, &DefaultDigitizerModule::pixel_message_, MsgFlags::REQUIRED);

    // Seed the random generator with the global seed
    random_generator_.seed(getRandomSeed());

    // Set defaults for config variables
    config_.setDefault<int>("electronics_noise", Units::get(110, "e"));
    config_.setDefault<int>("threshold", Units::get(600, "e"));
    config_.setDefault<int>("threshold_smearing", Units::get(30, "e"));

    config_.setDefault<int>("adc_resolution", 0);
    config_.setDefault<int>("adc_smearing", Units::get(300, "e"));
    config_.setDefault<double>("adc_offset", Units::get(0, "e"));
    config_.setDefault<double>("adc_slope", Units::get(10, "e"));

    config_.setDefault<bool>("output_plots", false);
}

void DefaultDigitizerModule::init() {
    if(config_.get<bool>("output_plots")) {
        LOG(TRACE) << "Creating output plots";

        // Create histograms if needed
        h_pxq = new TH1D("pixelcharge", "raw pixel charge;pixel charge [ke];pixels", 100, 0, 10);
        h_pxq_noise = new TH1D("pixelcharge_noise_", "pixel charge w/ el. noise;pixel charge [ke];pixels", 100, 0, 10);
        h_thr = new TH1D("threshold", "applied threshold; threshold [ke];events", 100, 0, 10);
        h_pxq_thr = new TH1D("pixelcharge_threshold_", "pixel charge above threshold;pixel charge [ke];pixels", 100, 0, 10);
        h_pxq_adc = new TH1D("pixelcharge_adc", "pixel charge after ADC;pixel charge [ke];pixels", 100, 0, 10);
    }

    // Conversion to ADC units requested:
    if(config_.get<int>("adc_resolution") > 63) {
        throw InvalidValueError(config_, "adc_resolution", "precision higher than 64bit is not possible");
    }
    if(config_.get<int>("adc_resolution") > 0) {
        LOG(INFO) << "Converting charge to ADC units, ADC resolution: " << config_.get<int>("adc_resolution")
                  << "bit, max. value " << ((1ll << config_.get<int>("adc_resolution")) - 1);
    }
}

void DefaultDigitizerModule::run(unsigned int) {
    // Loop through all pixels with charges
    std::vector<PixelHit> hits;
    for(auto& pixel_charge : pixel_message_->getData()) {
        auto pixel = pixel_charge.getPixel();
        auto pixel_index = pixel.getIndex();
        auto charge = static_cast<double>(pixel_charge.getCharge());

        LOG(DEBUG) << "Received pixel " << pixel_index << ", charge " << Units::display(charge, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq->Fill(charge / 1e3);
        }

        // Add electronics noise from Gaussian:
        std::normal_distribution<double> el_noise(0, config_.get<unsigned int>("electronics_noise"));
        charge += el_noise(random_generator_);

        LOG(DEBUG) << "Charge with noise: " << Units::display(charge, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq_noise->Fill(charge / 1e3);
        }

        // FIXME Simulate gain / gain smearing

        // Smear the threshold, Gaussian distribution around "threshold" with width "threshold_smearing"
        std::normal_distribution<double> thr_smearing(config_.get<unsigned int>("threshold"),
                                                      config_.get<unsigned int>("threshold_smearing"));
        double threshold = thr_smearing(random_generator_);
        if(config_.get<bool>("output_plots")) {
            h_thr->Fill(threshold / 1e3);
        }

        // Discard charges below threshold:
        if(charge < threshold) {
            LOG(DEBUG) << "Below smeared threshold: " << Units::display(charge, "e") << " < "
                       << Units::display(threshold, "e");
            continue;
        }

        LOG(DEBUG) << "Passed threshold: " << Units::display(charge, "e") << " > " << Units::display(threshold, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq_thr->Fill(charge / 1e3);
        }

        // Simulate ADC if resolution set to more than 0bit
        if(config_.get<int>("adc_resolution") > 0) {
            // Add ADC smearing:
            std::normal_distribution<double> adc_smearing(0, config_.get<unsigned int>("adc_smearing"));
            charge += adc_smearing(random_generator_);
            if(config_.get<bool>("output_plots")) {
                h_pxq_adc->Fill(charge / 1e3);
            }
            LOG(DEBUG) << "Smeared for simulating limited ADC sensitivity: " << Units::display(charge, "e");

            // Convert to ADC units and precision:
            charge = static_cast<double>(std::max(std::min(static_cast<long long>(config_.get<double>("adc_offset") +
                                                                                charge / config_.get<double>("adc_slope")),
                                                           (1ll << config_.get<int>("adc_resolution")) - 1),
                                                  0ll));
            LOG(DEBUG) << "Charge converted to ADC units: " << charge;
        }

        // Add the hit to the hitmap
        hits.emplace_back(pixel, 0, charge, &pixel_charge);
    }

    // Output summary and update statistics
    LOG(INFO) << "Digitized " << hits.size() << " pixel hits";
    total_hits_ += hits.size();

    if(!hits.empty()) {
        // Create and dispatch hit message
        auto hits_message = std::make_shared<PixelHitMessage>(std::move(hits), getDetector());
        messenger_->dispatchMessage(this, hits_message);
    }
}

void DefaultDigitizerModule::finalize() {
    if(config_.get<bool>("output_plots")) {
        // Write histograms
        LOG(TRACE) << "Writing output plots to file";
        h_pxq->Write();
        h_pxq_noise->Write();
        h_thr->Write();
        h_pxq_thr->Write();
        h_pxq_adc->Write();
    }

    LOG(INFO) << "Digitized " << total_hits_ << " pixel hits in total";
}
<commit_msg>Digitizer: 31bit is enough ADC resolution, let's not waste memory<commit_after>/**
 * @file
 * @brief Implementation of default digitization module
 * @copyright MIT License
 */

#include "DefaultDigitizerModule.hpp"

#include "core/utils/unit.h"
#include "tools/ROOT.h"

#include <TFile.h>
#include <TH1D.h>
#include <TProfile.h>

#include "objects/PixelHit.hpp"

using namespace allpix;

DefaultDigitizerModule::DefaultDigitizerModule(Configuration config,
                                               Messenger* messenger,
                                               std::shared_ptr<Detector> detector)
    : Module(config, std::move(detector)), config_(std::move(config)), messenger_(messenger), pixel_message_(nullptr) {
    // Enable parallelization of this module if multithreading is enabled
    enable_parallelization();

    // Require PixelCharge message for single detector
    messenger_->bindSingle(this, &DefaultDigitizerModule::pixel_message_, MsgFlags::REQUIRED);

    // Seed the random generator with the global seed
    random_generator_.seed(getRandomSeed());

    // Set defaults for config variables
    config_.setDefault<int>("electronics_noise", Units::get(110, "e"));
    config_.setDefault<int>("threshold", Units::get(600, "e"));
    config_.setDefault<int>("threshold_smearing", Units::get(30, "e"));

    config_.setDefault<int>("adc_resolution", 0);
    config_.setDefault<int>("adc_smearing", Units::get(300, "e"));
    config_.setDefault<double>("adc_offset", Units::get(0, "e"));
    config_.setDefault<double>("adc_slope", Units::get(10, "e"));

    config_.setDefault<bool>("output_plots", false);
}

void DefaultDigitizerModule::init() {
    if(config_.get<bool>("output_plots")) {
        LOG(TRACE) << "Creating output plots";

        // Create histograms if needed
        h_pxq = new TH1D("pixelcharge", "raw pixel charge;pixel charge [ke];pixels", 100, 0, 10);
        h_pxq_noise = new TH1D("pixelcharge_noise_", "pixel charge w/ el. noise;pixel charge [ke];pixels", 100, 0, 10);
        h_thr = new TH1D("threshold", "applied threshold; threshold [ke];events", 100, 0, 10);
        h_pxq_thr = new TH1D("pixelcharge_threshold_", "pixel charge above threshold;pixel charge [ke];pixels", 100, 0, 10);
        h_pxq_adc = new TH1D("pixelcharge_adc", "pixel charge after ADC;pixel charge [ke];pixels", 100, 0, 10);
    }

    // Conversion to ADC units requested:
    if(config_.get<int>("adc_resolution") > 31) {
        throw InvalidValueError(config_, "adc_resolution", "precision higher than 31bit is not possible");
    }
    if(config_.get<int>("adc_resolution") > 0) {
        LOG(INFO) << "Converting charge to ADC units, ADC resolution: " << config_.get<int>("adc_resolution")
                  << "bit, max. value " << ((1 << config_.get<int>("adc_resolution")) - 1);
    }
}

void DefaultDigitizerModule::run(unsigned int) {
    // Loop through all pixels with charges
    std::vector<PixelHit> hits;
    for(auto& pixel_charge : pixel_message_->getData()) {
        auto pixel = pixel_charge.getPixel();
        auto pixel_index = pixel.getIndex();
        auto charge = static_cast<double>(pixel_charge.getCharge());

        LOG(DEBUG) << "Received pixel " << pixel_index << ", charge " << Units::display(charge, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq->Fill(charge / 1e3);
        }

        // Add electronics noise from Gaussian:
        std::normal_distribution<double> el_noise(0, config_.get<unsigned int>("electronics_noise"));
        charge += el_noise(random_generator_);

        LOG(DEBUG) << "Charge with noise: " << Units::display(charge, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq_noise->Fill(charge / 1e3);
        }

        // FIXME Simulate gain / gain smearing

        // Smear the threshold, Gaussian distribution around "threshold" with width "threshold_smearing"
        std::normal_distribution<double> thr_smearing(config_.get<unsigned int>("threshold"),
                                                      config_.get<unsigned int>("threshold_smearing"));
        double threshold = thr_smearing(random_generator_);
        if(config_.get<bool>("output_plots")) {
            h_thr->Fill(threshold / 1e3);
        }

        // Discard charges below threshold:
        if(charge < threshold) {
            LOG(DEBUG) << "Below smeared threshold: " << Units::display(charge, "e") << " < "
                       << Units::display(threshold, "e");
            continue;
        }

        LOG(DEBUG) << "Passed threshold: " << Units::display(charge, "e") << " > " << Units::display(threshold, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq_thr->Fill(charge / 1e3);
        }

        // Simulate ADC if resolution set to more than 0bit
        if(config_.get<int>("adc_resolution") > 0) {
            // Add ADC smearing:
            std::normal_distribution<double> adc_smearing(0, config_.get<unsigned int>("adc_smearing"));
            charge += adc_smearing(random_generator_);
            if(config_.get<bool>("output_plots")) {
                h_pxq_adc->Fill(charge / 1e3);
            }
            LOG(DEBUG) << "Smeared for simulating limited ADC sensitivity: " << Units::display(charge, "e");

            // Convert to ADC units and precision:
            charge = static_cast<double>(std::max(
                std::min(static_cast<int>(config_.get<double>("adc_offset") + charge / config_.get<double>("adc_slope")),
                         (1 << config_.get<int>("adc_resolution")) - 1),
                0));
            LOG(DEBUG) << "Charge converted to ADC units: " << charge;
        }

        // Add the hit to the hitmap
        hits.emplace_back(pixel, 0, charge, &pixel_charge);
    }

    // Output summary and update statistics
    LOG(INFO) << "Digitized " << hits.size() << " pixel hits";
    total_hits_ += hits.size();

    if(!hits.empty()) {
        // Create and dispatch hit message
        auto hits_message = std::make_shared<PixelHitMessage>(std::move(hits), getDetector());
        messenger_->dispatchMessage(this, hits_message);
    }
}

void DefaultDigitizerModule::finalize() {
    if(config_.get<bool>("output_plots")) {
        // Write histograms
        LOG(TRACE) << "Writing output plots to file";
        h_pxq->Write();
        h_pxq_noise->Write();
        h_thr->Write();
        h_pxq_thr->Write();
        h_pxq_adc->Write();
    }

    LOG(INFO) << "Digitized " << total_hits_ << " pixel hits in total";
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 * Point Cloud Library (PCL) - www.pointclouds.org
 * Copyright (c) 2009-2011, Willow Garage, Inc.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the following
 *   disclaimer in the documentation and/or other materials provided
 *   with the distribution.
 * * Neither the name of Willow Garage, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: example_rift_estimation.cpp 5172 2012-03-18 10:43:15Z desinghkar $
 *
 *
 */

//STL
#include <iostream>

//PCL
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/common/io.h>
#include <pcl/keypoints/sift_keypoint.h>
#include <pcl/keypoints/impl/sift_keypoint.hpp>
#include <pcl/features/normal_3d.h>
//#include <pcl/visualization/pcl_visualizer.h>

int
main(int, char** argv)
{
  std::string filename = argv[1];
  std::cout << "Reading " << filename << std::endl;
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
  if(pcl::io::loadPCDFile<pcl::PointXYZRGB> (filename, *cloud) == -1) // load the file
  {
  PCL_ERROR ("Couldn't read file");
  return -1;
  }
  std::cout << "points: " << cloud->points.size () <<std::endl;

  // Parameters for sift computation
  const float min_scale = 0.1;
  const int n_octaves = 6;
  const int n_scales_per_octave = 10;
  const float min_contrast = 0.5;

  // Estimate the sift interest points using Intensity values from RGB values
  pcl::SIFTKeypoint<pcl::PointXYZRGB, pcl::PointWithScale> sift;
  pcl::PointCloud<pcl::PointWithScale> result;
  pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZRGB> ());
  sift.setSearchMethod(tree);
  sift.setScales(min_scale, n_octaves, n_scales_per_octave);
  sift.setMinimumContrast(min_contrast);
  sift.setInputCloud(cloud);
  sift.compute(result);

  // Copying the pointwithscale to pointxyz so as visualize the cloud
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_temp (new pcl::PointCloud<pcl::PointXYZ>);
  copyPointCloud(result, *cloud_temp);

  // Saving the resultant cloud
  std::cout << "Resulting sift points are of size: " << cloud_temp->points.size () <<std::endl;
  pcl::io::savePCDFileASCII("sift_points.pcd", *cloud_temp);

/*
  // Visualization of keypoints along with the original cloud
  pcl::visualization::PCLVisualizer viewer("PCL Viewer");
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> keypoints_color_handler (cloud_temp, 0, 255, 0);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> cloud_color_handler (cloud, 255, 255, 0);
  viewer.setBackgroundColor( 0.0, 0.0, 0.0 );
  viewer.addPointCloud(cloud, "cloud");
  viewer.addPointCloud(cloud_temp, keypoints_color_handler, "keypoints");
  viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 7, "keypoints");

  while(!viewer.wasStopped ())
  {
  viewer.spinOnce ();
  }
*/

  return 0;

}
<commit_msg>property addition to the file<commit_after>/*
 * Software License Agreement (BSD License)
 *
 * Point Cloud Library (PCL) - www.pointclouds.org
 * Copyright (c) 2009-2011, Willow Garage, Inc.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the following
 *   disclaimer in the documentation and/or other materials provided
 *   with the distribution.
 * * Neither the name of Willow Garage, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 *
 */

//STL
#include <iostream>

//PCL
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/common/io.h>
#include <pcl/keypoints/sift_keypoint.h>
#include <pcl/keypoints/impl/sift_keypoint.hpp>
#include <pcl/features/normal_3d.h>
//#include <pcl/visualization/pcl_visualizer.h>

int
main(int, char** argv)
{
  std::string filename = argv[1];
  std::cout << "Reading " << filename << std::endl;
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
  if(pcl::io::loadPCDFile<pcl::PointXYZRGB> (filename, *cloud) == -1) // load the file
  {
  PCL_ERROR ("Couldn't read file");
  return -1;
  }
  std::cout << "points: " << cloud->points.size () <<std::endl;

  // Parameters for sift computation
  const float min_scale = 0.1;
  const int n_octaves = 6;
  const int n_scales_per_octave = 10;
  const float min_contrast = 0.5;

  // Estimate the sift interest points using Intensity values from RGB values
  pcl::SIFTKeypoint<pcl::PointXYZRGB, pcl::PointWithScale> sift;
  pcl::PointCloud<pcl::PointWithScale> result;
  pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZRGB> ());
  sift.setSearchMethod(tree);
  sift.setScales(min_scale, n_octaves, n_scales_per_octave);
  sift.setMinimumContrast(min_contrast);
  sift.setInputCloud(cloud);
  sift.compute(result);

  // Copying the pointwithscale to pointxyz so as visualize the cloud
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_temp (new pcl::PointCloud<pcl::PointXYZ>);
  copyPointCloud(result, *cloud_temp);

  // Saving the resultant cloud
  std::cout << "Resulting sift points are of size: " << cloud_temp->points.size () <<std::endl;
  pcl::io::savePCDFileASCII("sift_points.pcd", *cloud_temp);

/*
  // Visualization of keypoints along with the original cloud
  pcl::visualization::PCLVisualizer viewer("PCL Viewer");
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> keypoints_color_handler (cloud_temp, 0, 255, 0);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> cloud_color_handler (cloud, 255, 255, 0);
  viewer.setBackgroundColor( 0.0, 0.0, 0.0 );
  viewer.addPointCloud(cloud, "cloud");
  viewer.addPointCloud(cloud_temp, keypoints_color_handler, "keypoints");
  viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 7, "keypoints");

  while(!viewer.wasStopped ())
  {
  viewer.spinOnce ();
  }
*/

  return 0;

}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | Copyright (C) 2011 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

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

    OpenFOAM 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 General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

Global
    readTimeControls

Author
    lhzhu
Description
    Read the control parameters used by setDeltaT,
    Add a convergence check interval: e.g.,
           convergeCheckSteps 100`
    and a convergence criteria, e.g,
           convergeTol        1.0e-3
    The convergence is check by the temperature field

\*---------------------------------------------------------------------------*/

const bool adjustTimeStep =
    runTime.controlDict().lookupOrDefault("adjustTimeStep", false);

scalar maxCo =
    runTime.controlDict().lookupOrDefault<scalar>("maxCo", 1.0);

scalar maxDeltaT =
    runTime.controlDict().lookupOrDefault<scalar>("maxDeltaT", GREAT);

scalar convergeTol =
    runTime.controlDict().lookupOrDefault<scalar>("convergeTol", 1.0e-6);

label convergeCheckSteps =
    runTime.controlDict().lookupOrDefault("convergeCheckSteps", 100);

scalar TemperatureChange = 1.0;
// ************************************************************************* //
//
<commit_msg>converge check, change default interval and tolerance<commit_after>/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | Copyright (C) 2011 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

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

    OpenFOAM 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 General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

Global
    readTimeControls

Author
    lhzhu
Description
    Read the control parameters used by setDeltaT,
    Add a convergence check interval: e.g.,
           convergeCheckSteps 100`
    and a convergence criteria, e.g,
           convergeTol        1.0e-3
    The convergence is check by the temperature field

\*---------------------------------------------------------------------------*/

const bool adjustTimeStep =
    runTime.controlDict().lookupOrDefault("adjustTimeStep", false);

scalar maxCo =
    runTime.controlDict().lookupOrDefault<scalar>("maxCo", 1.0);

scalar maxDeltaT =
    runTime.controlDict().lookupOrDefault<scalar>("maxDeltaT", GREAT);

scalar convergeTol =
    runTime.controlDict().lookupOrDefault<scalar>("convergeTol", 1.0e-12);

label convergeCheckSteps =
    runTime.controlDict().lookupOrDefault("convergeCheckSteps", 1);

scalar TemperatureChange = 1.0;
// ************************************************************************* //
//
<|endoftext|>