<commit_before>/*************************************************************************
 *
 *  $RCSfile: BPreparedStatement.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: oj $ $Date: 2002-08-23 13:17:05 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef CONNECTIVITY_ADABAS_PREPAREDSTATEMENT_HXX
#define CONNECTIVITY_ADABAS_PREPAREDSTATEMENT_HXX

#ifndef _CONNECTIVITY_ODBC_OPREPAREDSTATEMENT_HXX_
#include "odbc/OPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_BCONNECTION_HXX_
#include "adabas/BConnection.hxx"
#endif

namespace connectivity
{
    namespace adabas
    {
        class OAdabasPreparedStatement :    public  ::connectivity::odbc::OPreparedStatement
        {
            ::vos::ORef<OSQLColumns>    m_aSelectColumns;
        protected:
            virtual odbc::OResultSet* createResulSet();
            virtual void setResultSetConcurrency(sal_Int32 _par0)   ;
            virtual void setResultSetType(sal_Int32 _par0)          ;
            virtual void setUsingBookmarks(sal_Bool _bUseBookmark)  ;
        public:
            OAdabasPreparedStatement( OAdabasConnection* _pConnection,const ::std::vector<OTypeInfo>& _TypeInfo,const ::rtl::OUString& sql);
        };
    }
}

#endif // CONNECTIVITY_ADABAS_PREPAREDSTATEMENT_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.322); FILE MERGED 2005/09/05 17:24:55 rt 1.4.322.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BPreparedStatement.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:45:31 $
 *
 *  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 CONNECTIVITY_ADABAS_PREPAREDSTATEMENT_HXX
#define CONNECTIVITY_ADABAS_PREPAREDSTATEMENT_HXX

#ifndef _CONNECTIVITY_ODBC_OPREPAREDSTATEMENT_HXX_
#include "odbc/OPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_BCONNECTION_HXX_
#include "adabas/BConnection.hxx"
#endif

namespace connectivity
{
    namespace adabas
    {
        class OAdabasPreparedStatement :    public  ::connectivity::odbc::OPreparedStatement
        {
            ::vos::ORef<OSQLColumns>    m_aSelectColumns;
        protected:
            virtual odbc::OResultSet* createResulSet();
            virtual void setResultSetConcurrency(sal_Int32 _par0)   ;
            virtual void setResultSetType(sal_Int32 _par0)          ;
            virtual void setUsingBookmarks(sal_Bool _bUseBookmark)  ;
        public:
            OAdabasPreparedStatement( OAdabasConnection* _pConnection,const ::std::vector<OTypeInfo>& _TypeInfo,const ::rtl::OUString& sql);
        };
    }
}

#endif // CONNECTIVITY_ADABAS_PREPAREDSTATEMENT_HXX

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "SettingsUI.h"
#include "Hotkeys.h"
#include "afxdialogex.h"

#include "HotkeyPrompt.h"
#include "KeyGrabber.h"

IMPLEMENT_DYNAMIC(Hotkeys, CPropertyPage)

Hotkeys::Hotkeys() :
CPropertyPage(Hotkeys::IDD) {

}

Hotkeys::~Hotkeys() {
}

void Hotkeys::DoDataExchange(CDataExchange* pDX)
{
    CPropertyPage::DoDataExchange(pDX);
    DDX_Control(pDX, LST_KEYS, _list);
    DDX_Control(pDX, BTN_KEYS, _keys);
}

BOOL Hotkeys::OnInitDialog() {
    CPropertyPage::OnInitDialog();

    DWORD exStyle = _list.GetExtendedStyle();
    exStyle |= LVS_EX_FULLROWSELECT;
    _list.SetExtendedStyle(exStyle);

    RECT r;
    _list.GetWindowRect(&r);
    int width = r.right - r.left;

    _list.InsertColumn(0, L"Hotkeys", NULL, (int) (width * .465));
    _list.InsertColumn(1, L"Action", NULL, (int) (width * .465));

    _list.InsertItem(0, L"CTRL+ALT+OemVolumeUp");
    _list.SetItemText(0, 1, L"Increase Volume 5% [Parallels Audio Controller]");

    return TRUE;
}

void Hotkeys::SelectItem(int idx) {
    /* First unselect the selected item (not strictly necessary in our case) */
    int sel = _list.GetSelectionMark();
    _list.SetItemState(sel, ~LVIS_SELECTED, LVIS_SELECTED);

    /* Select the item */
    _list.SetItemState(idx, LVIS_SELECTED, LVIS_SELECTED);
    _list.SetSelectionMark(idx);

    /* Scroll down to the item, if necessary */
    _list.EnsureVisible(idx, FALSE);
}

BEGIN_MESSAGE_MAP(Hotkeys, CPropertyPage)
    ON_BN_CLICKED(BTN_ADD, &Hotkeys::OnBnClickedAdd)
    ON_BN_CLICKED(BTN_REMOVE, &Hotkeys::OnBnClickedRemove)
    ON_NOTIFY(LVN_ITEMCHANGED, LST_KEYS, &Hotkeys::OnLvnItemchangedKeys)
    ON_BN_CLICKED(BTN_KEYS, &Hotkeys::OnBnClickedKeys)
END_MESSAGE_MAP()

void Hotkeys::OnBnClickedAdd() {
    int items = _list.GetItemCount();
    for (int i = 0; i < items; ++i) {
        if (_list.GetItemText(i, 0) == L""
            && _list.GetItemText(i, 1) == L"") {
            /* We found a blank item already in the list */
            SelectItem(i);
            return;
        }
    }

    int idx = _list.InsertItem(items, L"");
    _list.SetItemText(idx, 1, L"");
    SelectItem(idx);
}

void Hotkeys::OnBnClickedRemove() {

}

void Hotkeys::OnLvnItemchangedKeys(NMHDR *pNMHDR, LRESULT *pResult) {
    LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
    // TODO: Add your control notification handler code here
    *pResult = 0;
}

void Hotkeys::OnBnClickedKeys() {
    HotkeyPrompt hkp;
    hkp.DoModal();
    int keyCombo = KeyGrabber::Instance()->KeyCombination();
    MessageBox(std::to_wstring(keyCombo).c_str());
}
<commit_msg>Test combination -> string conversion<commit_after>#include "stdafx.h"
#include "SettingsUI.h"
#include "Hotkeys.h"
#include "afxdialogex.h"

#include "HotkeyPrompt.h"
#include "KeyGrabber.h"

IMPLEMENT_DYNAMIC(Hotkeys, CPropertyPage)

Hotkeys::Hotkeys() :
CPropertyPage(Hotkeys::IDD) {

}

Hotkeys::~Hotkeys() {
}

void Hotkeys::DoDataExchange(CDataExchange* pDX)
{
    CPropertyPage::DoDataExchange(pDX);
    DDX_Control(pDX, LST_KEYS, _list);
    DDX_Control(pDX, BTN_KEYS, _keys);
}

BOOL Hotkeys::OnInitDialog() {
    CPropertyPage::OnInitDialog();

    DWORD exStyle = _list.GetExtendedStyle();
    exStyle |= LVS_EX_FULLROWSELECT;
    _list.SetExtendedStyle(exStyle);

    RECT r;
    _list.GetWindowRect(&r);
    int width = r.right - r.left;

    _list.InsertColumn(0, L"Hotkeys", NULL, (int) (width * .465));
    _list.InsertColumn(1, L"Action", NULL, (int) (width * .465));

    _list.InsertItem(0, L"CTRL+ALT+OemVolumeUp");
    _list.SetItemText(0, 1, L"Increase Volume 5% [Parallels Audio Controller]");

    return TRUE;
}

void Hotkeys::SelectItem(int idx) {
    /* First unselect the selected item (not strictly necessary in our case) */
    int sel = _list.GetSelectionMark();
    _list.SetItemState(sel, ~LVIS_SELECTED, LVIS_SELECTED);

    /* Select the item */
    _list.SetItemState(idx, LVIS_SELECTED, LVIS_SELECTED);
    _list.SetSelectionMark(idx);

    /* Scroll down to the item, if necessary */
    _list.EnsureVisible(idx, FALSE);
}

BEGIN_MESSAGE_MAP(Hotkeys, CPropertyPage)
    ON_BN_CLICKED(BTN_ADD, &Hotkeys::OnBnClickedAdd)
    ON_BN_CLICKED(BTN_REMOVE, &Hotkeys::OnBnClickedRemove)
    ON_NOTIFY(LVN_ITEMCHANGED, LST_KEYS, &Hotkeys::OnLvnItemchangedKeys)
    ON_BN_CLICKED(BTN_KEYS, &Hotkeys::OnBnClickedKeys)
END_MESSAGE_MAP()

void Hotkeys::OnBnClickedAdd() {
    int items = _list.GetItemCount();
    for (int i = 0; i < items; ++i) {
        if (_list.GetItemText(i, 0) == L""
            && _list.GetItemText(i, 1) == L"") {
            /* We found a blank item already in the list */
            SelectItem(i);
            return;
        }
    }

    int idx = _list.InsertItem(items, L"");
    _list.SetItemText(idx, 1, L"");
    SelectItem(idx);
}

void Hotkeys::OnBnClickedRemove() {

}

void Hotkeys::OnLvnItemchangedKeys(NMHDR *pNMHDR, LRESULT *pResult) {
    LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
    // TODO: Add your control notification handler code here
    *pResult = 0;
}

void Hotkeys::OnBnClickedKeys() {
    HotkeyPrompt hkp;
    hkp.DoModal();
    int keyCombo = KeyGrabber::Instance()->KeyCombination();
    MessageBox(HotkeyManager::HotkeysToString(keyCombo).c_str());
}
<|endoftext|>


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

#include <xmloff/XMLEventsImportContext.hxx>

#include "XMLEventImportHelper.hxx"

#include <com/sun/star/document/XEventsSupplier.hpp>
#include <xmloff/xmlimp.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlerror.hxx>

using namespace ::com::sun::star::uno;
using namespace ::xmloff::token;

using ::com::sun::star::xml::sax::XAttributeList;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::container::XNameReplace;
using ::com::sun::star::document::XEventsSupplier;
using ::com::sun::star::lang::IllegalArgumentException;

TYPEINIT1(XMLEventsImportContext,  SvXMLImportContext);

XMLEventsImportContext::XMLEventsImportContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrfx,
    const OUString& rLocalName) :
        SvXMLImportContext(rImport, nPrfx, rLocalName)
{
}

XMLEventsImportContext::XMLEventsImportContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrfx,
    const OUString& rLocalName,
    const Reference<XEventsSupplier> & xEventsSupplier) :
        SvXMLImportContext(rImport, nPrfx, rLocalName),
        xEvents(xEventsSupplier->getEvents())
{
}

XMLEventsImportContext::XMLEventsImportContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrfx,
    const OUString& rLocalName,
    const Reference<XNameReplace> & xNameReplace) :
        SvXMLImportContext(rImport, nPrfx, rLocalName),
        xEvents(xNameReplace)
{
}

XMLEventsImportContext::~XMLEventsImportContext()
{
//  // if, for whatever reason, the object gets destroyed prematurely,
//  // we need to delete the collected events
}

void XMLEventsImportContext::StartElement(
    const Reference<XAttributeList> &)
{
    // nothing to be done
}

void XMLEventsImportContext::EndElement()
{
    // nothing to be done
}

SvXMLImportContext* XMLEventsImportContext::CreateChildContext(
    sal_uInt16 p_nPrefix,
    const OUString& rLocalName,
    const Reference<XAttributeList> & xAttrList )
{
    // a) search for script:language and script:event-name attribute
    // b) delegate to factory. The factory will:
    //    1) translate XML event name into API event name
    //    2) get proper event context factory from import
    //    3) instantiate context

    // a) search for script:language and script:event-name attribute
    OUString sLanguage;
    OUString sEventName;
    sal_Int16 nCount = xAttrList->getLength();
    for (sal_Int16 nAttr = 0; nAttr < nCount; nAttr++)
    {
        OUString sLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName );

        if (XML_NAMESPACE_SCRIPT == nPrefix)
        {
            if (IsXMLToken(sLocalName, XML_EVENT_NAME))
            {
                sEventName = xAttrList->getValueByIndex(nAttr);
            }
            else if (IsXMLToken(sLocalName, XML_LANGUAGE))
            {
                sLanguage = xAttrList->getValueByIndex(nAttr);
            }
            // else: ignore -> let child context handle this
        }
        // else: ignore -> let child context handle this
    }

    // b) delegate to factory
    return GetImport().GetEventImport().CreateContext(
        GetImport(), p_nPrefix, rLocalName, xAttrList,
        this, sEventName, sLanguage);
}

void XMLEventsImportContext::SetEvents(
    const Reference<XEventsSupplier> & xEventsSupplier)
{
    if (xEventsSupplier.is())
    {
        SetEvents(xEventsSupplier->getEvents());
    }
}

void XMLEventsImportContext::SetEvents(
    const Reference<XNameReplace> & xNameRepl)
{
    if (xNameRepl.is())
    {
        xEvents = xNameRepl;

        // now iterate over vector and a) insert b) delete all elements
        EventsVector::iterator aEnd = aCollectEvents.end();
        for(EventsVector::iterator aIter = aCollectEvents.begin();
            aIter != aEnd;
            ++aIter)
        {
            AddEventValues(aIter->first, aIter->second);
        }
        aCollectEvents.clear();
    }
}

bool XMLEventsImportContext::GetEventSequence(
    const OUString& rName,
    Sequence<PropertyValue> & rSequence )
{
    // search through the vector
    // (This shouldn't take a lot of time, since this method should only get
    //  called if only one (or few) events are being expected)

    // iterate over vector until end or rName is found;
    EventsVector::iterator aIter = aCollectEvents.begin();
    while( (aIter != aCollectEvents.end()) && (aIter->first != rName) )
    {
        ++aIter;
    }

    // if we're not at the end, set the sequence
    bool bRet = (aIter != aCollectEvents.end());
    if (bRet)
        rSequence = aIter->second;

    return bRet;
}

void XMLEventsImportContext::AddEventValues(
    const OUString& rEventName,
    const Sequence<PropertyValue> & rValues )
{
    // if we already have the events, set them; else just collect
    if (xEvents.is())
    {
        // set event (if name is known)
        if (xEvents->hasByName(rEventName))
        {
            Any aAny;
            aAny <<= rValues;

            try
            {
                xEvents->replaceByName(rEventName, aAny);
            } catch ( const IllegalArgumentException & rException )
            {
                Sequence<OUString> aMsgParams(1);

                aMsgParams[0] = rEventName;

                GetImport().SetError(XMLERROR_FLAG_ERROR |
                                     XMLERROR_ILLEGAL_EVENT,
                                     aMsgParams, rException.Message, 0);
            }
        }
    }
    else
    {
        EventNameValuesPair aPair(rEventName, rValues);
        aCollectEvents.push_back(aPair);
    }
}

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

#include <xmloff/XMLEventsImportContext.hxx>

#include "XMLEventImportHelper.hxx"

#include <com/sun/star/document/XEventsSupplier.hpp>
#include <xmloff/xmlimp.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlerror.hxx>

using namespace ::com::sun::star::uno;
using namespace ::xmloff::token;

using ::com::sun::star::xml::sax::XAttributeList;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::container::XNameReplace;
using ::com::sun::star::document::XEventsSupplier;
using ::com::sun::star::lang::IllegalArgumentException;

TYPEINIT1(XMLEventsImportContext,  SvXMLImportContext);

XMLEventsImportContext::XMLEventsImportContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrfx,
    const OUString& rLocalName) :
        SvXMLImportContext(rImport, nPrfx, rLocalName)
{
}

XMLEventsImportContext::XMLEventsImportContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrfx,
    const OUString& rLocalName,
    const Reference<XEventsSupplier> & xEventsSupplier) :
        SvXMLImportContext(rImport, nPrfx, rLocalName),
        xEvents(xEventsSupplier->getEvents())
{
}

XMLEventsImportContext::XMLEventsImportContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrfx,
    const OUString& rLocalName,
    const Reference<XNameReplace> & xNameReplace) :
        SvXMLImportContext(rImport, nPrfx, rLocalName),
        xEvents(xNameReplace)
{
}

XMLEventsImportContext::~XMLEventsImportContext()
{
//  // if, for whatever reason, the object gets destroyed prematurely,
//  // we need to delete the collected events
}

void XMLEventsImportContext::StartElement(
    const Reference<XAttributeList> &)
{
    // nothing to be done
}

void XMLEventsImportContext::EndElement()
{
    // nothing to be done
}

SvXMLImportContext* XMLEventsImportContext::CreateChildContext(
    sal_uInt16 p_nPrefix,
    const OUString& rLocalName,
    const Reference<XAttributeList> & xAttrList )
{
    // a) search for script:language and script:event-name attribute
    // b) delegate to factory. The factory will:
    //    1) translate XML event name into API event name
    //    2) get proper event context factory from import
    //    3) instantiate context

    // a) search for script:language and script:event-name attribute
    OUString sLanguage;
    OUString sEventName;
    sal_Int16 nCount = xAttrList->getLength();
    for (sal_Int16 nAttr = 0; nAttr < nCount; nAttr++)
    {
        OUString sLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName );

        if (XML_NAMESPACE_SCRIPT == nPrefix)
        {
            if (IsXMLToken(sLocalName, XML_EVENT_NAME))
            {
                sEventName = xAttrList->getValueByIndex(nAttr);
            }
            else if (IsXMLToken(sLocalName, XML_LANGUAGE))
            {
                sLanguage = xAttrList->getValueByIndex(nAttr);
            }
            // else: ignore -> let child context handle this
        }
        // else: ignore -> let child context handle this
    }

    // b) delegate to factory
    return GetImport().GetEventImport().CreateContext(
        GetImport(), p_nPrefix, rLocalName, xAttrList,
        this, sEventName, sLanguage);
}

void XMLEventsImportContext::SetEvents(
    const Reference<XEventsSupplier> & xEventsSupplier)
{
    if (xEventsSupplier.is())
    {
        SetEvents(xEventsSupplier->getEvents());
    }
}

void XMLEventsImportContext::SetEvents(
    const Reference<XNameReplace> & xNameRepl)
{
    if (xNameRepl.is())
    {
        xEvents = xNameRepl;

        // now iterate over vector and a) insert b) delete all elements
        EventsVector::iterator aEnd = aCollectEvents.end();
        for(EventsVector::iterator aIter = aCollectEvents.begin();
            aIter != aEnd;
            ++aIter)
        {
            AddEventValues(aIter->first, aIter->second);
        }
        aCollectEvents.clear();
    }
}

bool XMLEventsImportContext::GetEventSequence(
    const OUString& rName,
    Sequence<PropertyValue> & rSequence )
{
    // search through the vector
    // (This shouldn't take a lot of time, since this method should only get
    //  called if only one (or few) events are being expected)

    // iterate over vector until end or rName is found;
    EventsVector::iterator aIter = aCollectEvents.begin();
    while( (aIter != aCollectEvents.end()) && (aIter->first != rName) )
    {
        ++aIter;
    }

    // if we're not at the end, set the sequence
    if (aIter != aCollectEvents.end())
    {
        rSequence = aIter->second;
        return true;
    }

    return false;
}

void XMLEventsImportContext::AddEventValues(
    const OUString& rEventName,
    const Sequence<PropertyValue> & rValues )
{
    // if we already have the events, set them; else just collect
    if (xEvents.is())
    {
        // set event (if name is known)
        if (xEvents->hasByName(rEventName))
        {
            Any aAny;
            aAny <<= rValues;

            try
            {
                xEvents->replaceByName(rEventName, aAny);
            } catch ( const IllegalArgumentException & rException )
            {
                Sequence<OUString> aMsgParams(1);

                aMsgParams[0] = rEventName;

                GetImport().SetError(XMLERROR_FLAG_ERROR |
                                     XMLERROR_ILLEGAL_EVENT,
                                     aMsgParams, rException.Message, 0);
            }
        }
    }
    else
    {
        EventNameValuesPair aPair(rEventName, rValues);
        aCollectEvents.push_back(aPair);
    }
}

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


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageMasterImportContext.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-07 16:17:29 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX
#include "PageMasterImportContext.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_
#include "PageMasterPropHdl.hxx"
#endif
#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#include "PagePropertySetContext.hxx"
#endif
#ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX
#include "PageHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERIMPORTPROPMAPPER_HXX
#include "PageMasterImportPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

void PageStyleContext::SetAttribute( sal_uInt16 nPrefixKey,
                                        const rtl::OUString& rLocalName,
                                        const rtl::OUString& rValue )
{
    // TODO: use a map here
    if( XML_NAMESPACE_STYLE == nPrefixKey && IsXMLToken( rLocalName, XML_PAGE_USAGE ) )
    {
        sPageUsage = rValue;
    }
    else
    {
        XMLPropStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue );
    }
}

TYPEINIT1( PageStyleContext, XMLPropStyleContext );

PageStyleContext::PageStyleContext( SvXMLImport& rImport,
        sal_uInt16 nPrfx, const rtl::OUString& rLName,
        const uno::Reference< xml::sax::XAttributeList > & xAttrList,
        SvXMLStylesContext& rStyles,
        sal_Bool bDefaultStyle) :
    XMLPropStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, XML_STYLE_FAMILY_PAGE_MASTER, bDefaultStyle),
    sPageUsage()
{
}

PageStyleContext::~PageStyleContext()
{
}

SvXMLImportContext *PageStyleContext::CreateChildContext(
        sal_uInt16 nPrefix,
        const rtl::OUString& rLocalName,
        const uno::Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = NULL;

    if( XML_NAMESPACE_STYLE == nPrefix &&
        ((IsXMLToken(rLocalName, XML_HEADER_STYLE )) ||
         (IsXMLToken(rLocalName, XML_FOOTER_STYLE )) ) )
    {
        sal_Bool bHeader = IsXMLToken(rLocalName, XML_HEADER_STYLE);
        UniReference < SvXMLImportPropertyMapper > xImpPrMap =
            GetStyles()->GetImportPropertyMapper( GetFamily() );
        if( xImpPrMap.is() )
        {
            const UniReference< XMLPropertySetMapper >& rMapper = xImpPrMap->getPropertySetMapper();
            sal_Int32 nFlag;
            if (bHeader)
                nFlag = CTF_PM_HEADERFLAG;
            else
                nFlag = CTF_PM_FOOTERFLAG;
            sal_Int32 nStartIndex (-1);
            sal_Int32 nEndIndex (-1);
            sal_Bool bFirst(sal_False);
            sal_Bool bEnd(sal_False);
            sal_Int32 nIndex = 0;
            while ( nIndex < rMapper->GetEntryCount() && !bEnd)
            {
                if ((rMapper->GetEntryContextId( nIndex ) & CTF_PM_FLAGMASK) == nFlag)
                {
                    if (!bFirst)
                    {
                        bFirst = sal_True;
                        nStartIndex = nIndex;
                    }
                }
                else if (bFirst)
                {
                    bEnd = sal_True;
                    nEndIndex = nIndex;
                }
                nIndex++;
            }
            if (!bEnd)
                nEndIndex = nIndex;
            pContext = new PageHeaderFooterContext(GetImport(), nPrefix, rLocalName,
                            xAttrList, GetProperties(), xImpPrMap, nStartIndex, nEndIndex, bHeader);
        }
    }
    if( XML_NAMESPACE_STYLE == nPrefix &&
        IsXMLToken(rLocalName, XML_PAGE_LAYOUT_PROPERTIES) )
    {
        UniReference < SvXMLImportPropertyMapper > xImpPrMap =
            GetStyles()->GetImportPropertyMapper( GetFamily() );
        if( xImpPrMap.is() )
        {
            const UniReference< XMLPropertySetMapper >& rMapper = xImpPrMap->getPropertySetMapper();
            sal_Int32 nEndIndex (-1);
            sal_Bool bEnd(sal_False);
            sal_Int32 nIndex = 0;
            sal_Int16 nContextID;
            while ( nIndex < rMapper->GetEntryCount() && !bEnd)
            {
                nContextID = rMapper->GetEntryContextId( nIndex );
                if (nContextID && ((nContextID & CTF_PM_FLAGMASK) != XML_PM_CTF_START))
                {
                    nEndIndex = nIndex;
                    bEnd = sal_True;
                }
                nIndex++;
            }
            if (!bEnd)
                nEndIndex = nIndex;
            PageContextType aType = Page;
            pContext = new PagePropertySetContext( GetImport(), nPrefix,
                                                    rLocalName, xAttrList,
                                                    XML_TYPE_PROP_PAGE_LAYOUT,
                                                    GetProperties(),
                                                    xImpPrMap, 0, nEndIndex, aType);
        }
    }

    if (!pContext)
        pContext = XMLPropStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                           xAttrList );
    return pContext;
}

void PageStyleContext::FillPropertySet(
            const uno::Reference<beans::XPropertySet > & rPropSet )
{
    XMLPropStyleContext::FillPropertySet(rPropSet);
    if (sPageUsage.getLength())
    {
        uno::Any aPageUsage;
        XMLPMPropHdl_PageStyleLayout aPageUsageHdl;
        if (aPageUsageHdl.importXML(sPageUsage, aPageUsage, GetImport().GetMM100UnitConverter()))
            rPropSet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PageStyleLayout")), aPageUsage);
    }
}

// text grid enhancement for better CJK support
//set default page layout style
void PageStyleContext::SetDefaults( )
{
    Reference < XMultiServiceFactory > xFactory ( GetImport().GetModel(), UNO_QUERY);
    if (xFactory.is())
    {
        Reference < XInterface > xInt = xFactory->createInstance (
        rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.Defaults" ) ) );
        Reference < beans::XPropertySet > xProperties ( xInt, UNO_QUERY );
        if ( xProperties.is() )
            FillPropertySet ( xProperties );
    }
}

<commit_msg>INTEGRATION: CWS changefileheader (1.14.20); FILE MERGED 2008/04/01 13:04:57 thb 1.14.20.2: #i85898# Stripping all external header guards 2008/03/31 16:28:19 rt 1.14.20.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: PageMasterImportContext.cxx,v $
 * $Revision: 1.15 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#include "PageMasterImportContext.hxx"
#include "xmlnmspe.hxx"
#include <xmloff/xmltoken.hxx>
#include "PageMasterPropHdl.hxx"
#include "PagePropertySetContext.hxx"
#ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX
#include "PageHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif
#include "PageMasterImportPropMapper.hxx"
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

void PageStyleContext::SetAttribute( sal_uInt16 nPrefixKey,
                                        const rtl::OUString& rLocalName,
                                        const rtl::OUString& rValue )
{
    // TODO: use a map here
    if( XML_NAMESPACE_STYLE == nPrefixKey && IsXMLToken( rLocalName, XML_PAGE_USAGE ) )
    {
        sPageUsage = rValue;
    }
    else
    {
        XMLPropStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue );
    }
}

TYPEINIT1( PageStyleContext, XMLPropStyleContext );

PageStyleContext::PageStyleContext( SvXMLImport& rImport,
        sal_uInt16 nPrfx, const rtl::OUString& rLName,
        const uno::Reference< xml::sax::XAttributeList > & xAttrList,
        SvXMLStylesContext& rStyles,
        sal_Bool bDefaultStyle) :
    XMLPropStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, XML_STYLE_FAMILY_PAGE_MASTER, bDefaultStyle),
    sPageUsage()
{
}

PageStyleContext::~PageStyleContext()
{
}

SvXMLImportContext *PageStyleContext::CreateChildContext(
        sal_uInt16 nPrefix,
        const rtl::OUString& rLocalName,
        const uno::Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = NULL;

    if( XML_NAMESPACE_STYLE == nPrefix &&
        ((IsXMLToken(rLocalName, XML_HEADER_STYLE )) ||
         (IsXMLToken(rLocalName, XML_FOOTER_STYLE )) ) )
    {
        sal_Bool bHeader = IsXMLToken(rLocalName, XML_HEADER_STYLE);
        UniReference < SvXMLImportPropertyMapper > xImpPrMap =
            GetStyles()->GetImportPropertyMapper( GetFamily() );
        if( xImpPrMap.is() )
        {
            const UniReference< XMLPropertySetMapper >& rMapper = xImpPrMap->getPropertySetMapper();
            sal_Int32 nFlag;
            if (bHeader)
                nFlag = CTF_PM_HEADERFLAG;
            else
                nFlag = CTF_PM_FOOTERFLAG;
            sal_Int32 nStartIndex (-1);
            sal_Int32 nEndIndex (-1);
            sal_Bool bFirst(sal_False);
            sal_Bool bEnd(sal_False);
            sal_Int32 nIndex = 0;
            while ( nIndex < rMapper->GetEntryCount() && !bEnd)
            {
                if ((rMapper->GetEntryContextId( nIndex ) & CTF_PM_FLAGMASK) == nFlag)
                {
                    if (!bFirst)
                    {
                        bFirst = sal_True;
                        nStartIndex = nIndex;
                    }
                }
                else if (bFirst)
                {
                    bEnd = sal_True;
                    nEndIndex = nIndex;
                }
                nIndex++;
            }
            if (!bEnd)
                nEndIndex = nIndex;
            pContext = new PageHeaderFooterContext(GetImport(), nPrefix, rLocalName,
                            xAttrList, GetProperties(), xImpPrMap, nStartIndex, nEndIndex, bHeader);
        }
    }
    if( XML_NAMESPACE_STYLE == nPrefix &&
        IsXMLToken(rLocalName, XML_PAGE_LAYOUT_PROPERTIES) )
    {
        UniReference < SvXMLImportPropertyMapper > xImpPrMap =
            GetStyles()->GetImportPropertyMapper( GetFamily() );
        if( xImpPrMap.is() )
        {
            const UniReference< XMLPropertySetMapper >& rMapper = xImpPrMap->getPropertySetMapper();
            sal_Int32 nEndIndex (-1);
            sal_Bool bEnd(sal_False);
            sal_Int32 nIndex = 0;
            sal_Int16 nContextID;
            while ( nIndex < rMapper->GetEntryCount() && !bEnd)
            {
                nContextID = rMapper->GetEntryContextId( nIndex );
                if (nContextID && ((nContextID & CTF_PM_FLAGMASK) != XML_PM_CTF_START))
                {
                    nEndIndex = nIndex;
                    bEnd = sal_True;
                }
                nIndex++;
            }
            if (!bEnd)
                nEndIndex = nIndex;
            PageContextType aType = Page;
            pContext = new PagePropertySetContext( GetImport(), nPrefix,
                                                    rLocalName, xAttrList,
                                                    XML_TYPE_PROP_PAGE_LAYOUT,
                                                    GetProperties(),
                                                    xImpPrMap, 0, nEndIndex, aType);
        }
    }

    if (!pContext)
        pContext = XMLPropStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                           xAttrList );
    return pContext;
}

void PageStyleContext::FillPropertySet(
            const uno::Reference<beans::XPropertySet > & rPropSet )
{
    XMLPropStyleContext::FillPropertySet(rPropSet);
    if (sPageUsage.getLength())
    {
        uno::Any aPageUsage;
        XMLPMPropHdl_PageStyleLayout aPageUsageHdl;
        if (aPageUsageHdl.importXML(sPageUsage, aPageUsage, GetImport().GetMM100UnitConverter()))
            rPropSet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PageStyleLayout")), aPageUsage);
    }
}

// text grid enhancement for better CJK support
//set default page layout style
void PageStyleContext::SetDefaults( )
{
    Reference < XMultiServiceFactory > xFactory ( GetImport().GetModel(), UNO_QUERY);
    if (xFactory.is())
    {
        Reference < XInterface > xInt = xFactory->createInstance (
        rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.Defaults" ) ) );
        Reference < beans::XPropertySet > xProperties ( xInt, UNO_QUERY );
        if ( xProperties.is() )
            FillPropertySet ( xProperties );
    }
}

<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo 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.
 *****************************************************************************/

#include <fstream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <string>
#include <pcl/io/pcd_io.h>

#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/lib/pcl_util/pcl_types.h"
#include "modules/perception/obstacle/common/file_system_util.h"
#include "modules/perception/obstacle/common/pose_util.h"
#include "modules/perception/obstacle/onboard/lidar_process.h"
#include "modules/perception/obstacle/lidar/visualizer/opengl_visualizer/opengl_visualizer.h"
#include "modules/perception/obstacle/lidar/visualizer/opengl_visualizer/frame_content.h"

DECLARE_string(flagfile);
DECLARE_bool(enable_visualization);
DECLARE_string(config_manager_path);
DEFINE_string(pcd_path, "./pcd/", "pcd path");
DEFINE_string(pose_path, "./pose/", "pose path");
DEFINE_string(output_path, "./output/", "output path");
DEFINE_bool(save_obstacles, true, "save obstacles to file");

namespace apollo {
namespace perception {

DEFINE_int32(start_frame, 1, "start frame");

class OfflineLidarPerceptionTool {
 public:
  OfflineLidarPerceptionTool() {
      config_manager_ = NULL;
  };

  ~OfflineLidarPerceptionTool() = default;

  bool Init(bool use_visualization = false) {
    config_manager_ = Singleton<ConfigManager>::Get();
    if (config_manager_ == NULL || !config_manager_->Init()) {
      AERROR << "failed to init ConfigManager";
      return false;
    }

    lidar_process_.reset(new LidarProcess());
    if (!lidar_process_->Init()) {
      AERROR << "failed to init lidar_process.";
      return false;
    }

    output_dir_ = FLAGS_output_path;

    if (use_visualization) {
      visualizer_.reset(new OpenglVisualizer());
      if(!visualizer_->Init()) {
        AERROR<<"init visialuzer failed"<<std::endl;
      };
    }
    return true;
  }

  void Run(const std::string& pcd_path, const std::string pose_path,
    const std::string& output_path) {
    std::string pcd_folder = pcd_path;
    std::string pose_folder = pose_path;
    std::vector<std::string> pcd_file_names;
    std::vector<std::string> pose_file_names;
    AINFO << "starting to run";
    GetFileNamesInFolderById(pose_folder, ".pose", &pose_file_names);
    GetFileNamesInFolderById(pcd_folder, ".pcd", &pcd_file_names);
    AINFO<<" pose size " << pose_file_names.size();
    AINFO<<" pcd size " << pcd_file_names.size();
    if (pose_file_names.size() != pcd_file_names.size()) {
      AERROR << "pcd file number does not match pose file number";
      return;
    }
    double time_stamp = 0.0;
    int start_frame = FLAGS_start_frame;
    AINFO << "starting frame is "<<start_frame;
    sleep(1);
    for (size_t i = 0; i < pcd_file_names.size(); i++) {
      AINFO << "***************** Frame " << i << " ******************";
      std::ostringstream oss;
      pcl_util::PointCloudPtr cloud(new pcl_util::PointCloud);
      AINFO << "load pcd file from file path" << pcd_folder + pcd_file_names[i];
      pcl::io::loadPCDFile<pcl_util::Point>(pcd_folder + pcd_file_names[i], *cloud);

      //read pose
      Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();
      int frame_id = -1;
      if (!ReadPoseFile(pose_folder + pose_file_names[i],
        &pose, &frame_id, &time_stamp)) {
        AERROR << "Failed to read pose file" << pose_file_names[i];
        return;
      }

      std::shared_ptr<Eigen::Matrix4d> velodyne_trans = std::make_shared<Eigen::Matrix4d>(pose);
      lidar_process_->Process(time_stamp, cloud, velodyne_trans);

      std::vector<ObjectPtr> result_objects = lidar_process_->GetObjects();
      const pcl_util::PointIndicesPtr roi_indices = lidar_process_->GetROIIndices();

      pcl_util::PointCloudPtr roi_cloud(new pcl_util::PointCloud);
  	  	pcl::copyPointCloud(*cloud, *roi_indices, *roi_cloud);

      if (visualizer_) {
        pcl_util::PointDCloudPtr transformed_cloud(new pcl_util::PointDCloud);
        transform_perception_cloud(cloud, pose, transformed_cloud);
        AERROR<<"transformed cloud size is "<<transformed_cloud->size();

        pcl_util::PointIndices roi_indices_1;
        FrameContent content;
        content.SetLidarPose(pose);
        content.SetLidarCloud(cloud);
        content.SetLidarRoiCloud(roi_cloud);
        content.SetTrackedObjects(result_objects);
        visualizer_->UpdateCameraSystem(&content);
        visualizer_->Render(content);
      }
      AINFO << "finish pc";

      if (FLAGS_save_obstacles) {
        oss << std::setfill('0') << std::setw(6) << i;
        std::string filename = FLAGS_output_path + oss.str() + ".txt";
        SaveTrackingInformation(result_objects, pose, frame_id, cloud, filename);
      }
    }
  }

  void SaveTrackingInformation(std::vector<ObjectPtr>& objects,
    const Eigen::Matrix4d& pose_v2w,
    const int& frame_id,
    const pcl_util::PointCloudPtr& cloud,
    const std::string& filename) {
    std::ofstream fout(filename.c_str(), std::ios::out);
    if (!fout) {
      AERROR << filename << " is not exist!";
      return;
    }
    // write frame id & number of objects at the beignning
    fout << frame_id << " " << objects.size() << std::endl;

    typename pcl::PointCloud<pcl_util::Point>::Ptr
      trans_cloud(new pcl::PointCloud<pcl_util::Point>());
    Eigen::Matrix4d pose_velo2tw = pose_v2w;
    pcl::copyPointCloud(*cloud, *trans_cloud);
    transform_point_cloud<pcl_util::Point>(*trans_cloud, pose_v2w);
    AINFO << "point size of transforming cloud is " << trans_cloud->size();
    pcl::KdTreeFLANN<pcl_util::Point> pcl_kdtree;
    pcl_kdtree.setInputCloud(trans_cloud);
    std::vector<int> k_indices;
    std::vector<float> k_sqrt_dist;
    Eigen::Matrix4d pose_tw2velo = pose_velo2tw.inverse();

    for (int i = 0; i < objects.size(); i++) {
      Eigen::Vector3f coord_dir(0.0, 1.0, 0.0);
      Eigen::Vector4d dir_velo = pose_tw2velo * Eigen::Vector4d(objects[i]->direction[0],
        objects[i]->direction[1], objects[i]->direction[2], 0);
      Eigen::Vector4d ct_velo = pose_tw2velo * Eigen::Vector4d(objects[i]->center[0],
        objects[i]->center[1], objects[i]->center[2], 1);
      Eigen::Vector3f dir_velo3(dir_velo[0], dir_velo[1], dir_velo[2]);
      double theta = vector_theta_2d_xy(coord_dir, dir_velo3);
      std::string type ="unknown";
      if (objects[i]->type == PEDESTRIAN) {
          type = "pedestrain";
      } else if (objects[i]->type == VEHICLE) {
          type = "smallMot";
      } else if (objects[i]->type == BICYCLE) {
          type = "nonMot";
      }
      // write tracking details
      fout << objects[i]->id << " " << objects[i]->track_id << " "
        << type << " "
        << std::setprecision(10)
        << ct_velo[0] << " "
        << ct_velo[1] << " "
        << ct_velo[2] << " "
        << objects[i]->length << " "
        << objects[i]->width << " "
        << objects[i]->height << " "
        << theta << " "
        << 0 << " "
        << 0 << " "
        << objects[i]->velocity[0] << " "
        << objects[i]->velocity[1] << " "
        << objects[i]->velocity[2] << " "
        << objects[i]->cloud->size() << " ";

      for (int j = 0; j < objects[i]->cloud->size(); j++) {
        const pcl_util::Point& pt = objects[i]->cloud->points[j];
        pcl_util::Point query_pt;
        query_pt.x = pt.x;
        query_pt.y = pt.y;
        query_pt.z = pt.z;
        k_indices.resize(1);
        k_sqrt_dist.resize(1);
        pcl_kdtree.nearestKSearch(query_pt, 1, k_indices, k_sqrt_dist);
        fout << k_indices[0] << " ";
      }
      fout << std::endl;
    }
    fout.close();
    return;
  }

protected:
    ConfigManager* config_manager_;
    std::unique_ptr<LidarProcess> lidar_process_;
    std::unique_ptr<OpenglVisualizer> visualizer_;
    std::string output_dir_;
    std::string pose_dir_;
    std::string label_file_;
};

}  // namespace perception
}  // namespace apollo

int main(int argc, char* argv[]) {
    FLAGS_flagfile = "./modules/perception/tool/offline_visualizer_tool/conf/offline_lidar_perception_test.flag";
    gflags::ParseCommandLineFlags(&argc, &argv, true);
    apollo::perception::OfflineLidarPerceptionTool tool;
    tool.Init(FLAGS_enable_visualization);
    tool.Run(FLAGS_pcd_path, FLAGS_pose_path, FLAGS_output_path);
    return 0;
}
<commit_msg>perception: fix compile warning.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo 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.
 *****************************************************************************/

#include <cstddef>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <string>
#include <pcl/io/pcd_io.h>

#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/lib/pcl_util/pcl_types.h"
#include "modules/perception/obstacle/common/file_system_util.h"
#include "modules/perception/obstacle/common/pose_util.h"
#include "modules/perception/obstacle/onboard/lidar_process.h"
#include "modules/perception/obstacle/lidar/visualizer/opengl_visualizer/opengl_visualizer.h"
#include "modules/perception/obstacle/lidar/visualizer/opengl_visualizer/frame_content.h"

DECLARE_string(flagfile);
DECLARE_bool(enable_visualization);
DECLARE_string(config_manager_path);
DEFINE_string(pcd_path, "./pcd/", "pcd path");
DEFINE_string(pose_path, "./pose/", "pose path");
DEFINE_string(output_path, "./output/", "output path");
DEFINE_bool(save_obstacles, true, "save obstacles to file");

namespace apollo {
namespace perception {

DEFINE_int32(start_frame, 1, "start frame");

class OfflineLidarPerceptionTool {
 public:
  OfflineLidarPerceptionTool() {
      config_manager_ = NULL;
  };

  ~OfflineLidarPerceptionTool() = default;

  bool Init(bool use_visualization = false) {
    config_manager_ = Singleton<ConfigManager>::Get();
    if (config_manager_ == NULL || !config_manager_->Init()) {
      AERROR << "failed to init ConfigManager";
      return false;
    }

    lidar_process_.reset(new LidarProcess());
    if (!lidar_process_->Init()) {
      AERROR << "failed to init lidar_process.";
      return false;
    }

    output_dir_ = FLAGS_output_path;

    if (use_visualization) {
      visualizer_.reset(new OpenglVisualizer());
      if(!visualizer_->Init()) {
        AERROR<<"init visialuzer failed"<<std::endl;
      };
    }
    return true;
  }

  void Run(const std::string& pcd_path, const std::string pose_path,
    const std::string& output_path) {
    std::string pcd_folder = pcd_path;
    std::string pose_folder = pose_path;
    std::vector<std::string> pcd_file_names;
    std::vector<std::string> pose_file_names;
    AINFO << "starting to run";
    GetFileNamesInFolderById(pose_folder, ".pose", &pose_file_names);
    GetFileNamesInFolderById(pcd_folder, ".pcd", &pcd_file_names);
    AINFO<<" pose size " << pose_file_names.size();
    AINFO<<" pcd size " << pcd_file_names.size();
    if (pose_file_names.size() != pcd_file_names.size()) {
      AERROR << "pcd file number does not match pose file number";
      return;
    }
    double time_stamp = 0.0;
    int start_frame = FLAGS_start_frame;
    AINFO << "starting frame is "<<start_frame;
    sleep(1);
    for (size_t i = 0; i < pcd_file_names.size(); i++) {
      AINFO << "***************** Frame " << i << " ******************";
      std::ostringstream oss;
      pcl_util::PointCloudPtr cloud(new pcl_util::PointCloud);
      AINFO << "load pcd file from file path" << pcd_folder + pcd_file_names[i];
      pcl::io::loadPCDFile<pcl_util::Point>(pcd_folder + pcd_file_names[i], *cloud);

      //read pose
      Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();
      int frame_id = -1;
      if (!ReadPoseFile(pose_folder + pose_file_names[i],
        &pose, &frame_id, &time_stamp)) {
        AERROR << "Failed to read pose file" << pose_file_names[i];
        return;
      }

      std::shared_ptr<Eigen::Matrix4d> velodyne_trans = std::make_shared<Eigen::Matrix4d>(pose);
      lidar_process_->Process(time_stamp, cloud, velodyne_trans);

      std::vector<ObjectPtr> result_objects = lidar_process_->GetObjects();
      const pcl_util::PointIndicesPtr roi_indices = lidar_process_->GetROIIndices();

      pcl_util::PointCloudPtr roi_cloud(new pcl_util::PointCloud);
  	  	pcl::copyPointCloud(*cloud, *roi_indices, *roi_cloud);

      if (visualizer_) {
        pcl_util::PointDCloudPtr transformed_cloud(new pcl_util::PointDCloud);
        transform_perception_cloud(cloud, pose, transformed_cloud);
        AERROR<<"transformed cloud size is "<<transformed_cloud->size();

        pcl_util::PointIndices roi_indices_1;
        FrameContent content;
        content.SetLidarPose(pose);
        content.SetLidarCloud(cloud);
        content.SetLidarRoiCloud(roi_cloud);
        content.SetTrackedObjects(result_objects);
        visualizer_->UpdateCameraSystem(&content);
        visualizer_->Render(content);
      }
      AINFO << "finish pc";

      if (FLAGS_save_obstacles) {
        oss << std::setfill('0') << std::setw(6) << i;
        std::string filename = FLAGS_output_path + oss.str() + ".txt";
        SaveTrackingInformation(result_objects, pose, frame_id, cloud, filename);
      }
    }
  }

  void SaveTrackingInformation(std::vector<ObjectPtr>& objects,
    const Eigen::Matrix4d& pose_v2w,
    const int& frame_id,
    const pcl_util::PointCloudPtr& cloud,
    const std::string& filename) {
    std::ofstream fout(filename.c_str(), std::ios::out);
    if (!fout) {
      AERROR << filename << " is not exist!";
      return;
    }
    // write frame id & number of objects at the beignning
    fout << frame_id << " " << objects.size() << std::endl;

    typename pcl::PointCloud<pcl_util::Point>::Ptr
      trans_cloud(new pcl::PointCloud<pcl_util::Point>());
    Eigen::Matrix4d pose_velo2tw = pose_v2w;
    pcl::copyPointCloud(*cloud, *trans_cloud);
    transform_point_cloud<pcl_util::Point>(*trans_cloud, pose_v2w);
    AINFO << "point size of transforming cloud is " << trans_cloud->size();
    pcl::KdTreeFLANN<pcl_util::Point> pcl_kdtree;
    pcl_kdtree.setInputCloud(trans_cloud);
    std::vector<int> k_indices;
    std::vector<float> k_sqrt_dist;
    Eigen::Matrix4d pose_tw2velo = pose_velo2tw.inverse();

    for (std::size_t i = 0; i < objects.size(); i++) {
      Eigen::Vector3f coord_dir(0.0, 1.0, 0.0);
      Eigen::Vector4d dir_velo = pose_tw2velo * Eigen::Vector4d(objects[i]->direction[0],
        objects[i]->direction[1], objects[i]->direction[2], 0);
      Eigen::Vector4d ct_velo = pose_tw2velo * Eigen::Vector4d(objects[i]->center[0],
        objects[i]->center[1], objects[i]->center[2], 1);
      Eigen::Vector3f dir_velo3(dir_velo[0], dir_velo[1], dir_velo[2]);
      double theta = vector_theta_2d_xy(coord_dir, dir_velo3);
      std::string type ="unknown";
      if (objects[i]->type == PEDESTRIAN) {
          type = "pedestrain";
      } else if (objects[i]->type == VEHICLE) {
          type = "smallMot";
      } else if (objects[i]->type == BICYCLE) {
          type = "nonMot";
      }
      // write tracking details
      fout << objects[i]->id << " " << objects[i]->track_id << " "
        << type << " "
        << std::setprecision(10)
        << ct_velo[0] << " "
        << ct_velo[1] << " "
        << ct_velo[2] << " "
        << objects[i]->length << " "
        << objects[i]->width << " "
        << objects[i]->height << " "
        << theta << " "
        << 0 << " "
        << 0 << " "
        << objects[i]->velocity[0] << " "
        << objects[i]->velocity[1] << " "
        << objects[i]->velocity[2] << " "
        << objects[i]->cloud->size() << " ";

      for (std::size_t j = 0; j < objects[i]->cloud->size(); j++) {
        const pcl_util::Point& pt = objects[i]->cloud->points[j];
        pcl_util::Point query_pt;
        query_pt.x = pt.x;
        query_pt.y = pt.y;
        query_pt.z = pt.z;
        k_indices.resize(1);
        k_sqrt_dist.resize(1);
        pcl_kdtree.nearestKSearch(query_pt, 1, k_indices, k_sqrt_dist);
        fout << k_indices[0] << " ";
      }
      fout << std::endl;
    }
    fout.close();
    return;
  }

protected:
    ConfigManager* config_manager_;
    std::unique_ptr<LidarProcess> lidar_process_;
    std::unique_ptr<OpenglVisualizer> visualizer_;
    std::string output_dir_;
    std::string pose_dir_;
    std::string label_file_;
};

}  // namespace perception
}  // namespace apollo

int main(int argc, char* argv[]) {
    FLAGS_flagfile = "./modules/perception/tool/offline_visualizer_tool/conf/offline_lidar_perception_test.flag";
    gflags::ParseCommandLineFlags(&argc, &argv, true);
    apollo::perception::OfflineLidarPerceptionTool tool;
    tool.Init(FLAGS_enable_visualization);
    tool.Run(FLAGS_pcd_path, FLAGS_pose_path, FLAGS_output_path);
    return 0;
}
<|endoftext|>


<commit_before>// Fill out your copyright notice in the Description page of Project Settings.

#include "Mighty.h"
#include "Card.h"

#include "PaperSpriteActor.h"
#include "PaperSprite.h"
#include "PaperSpriteComponent.h"

// Sets default values
ACard::ACard()
{
	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	RootComponent = spriteComp = CreateDefaultSubobject<UPaperSpriteComponent>(TEXT("PrimarySprite"));

	ConstructorHelpers::FObjectFinder<UPaperSprite> Material(TEXT("/Game/Resources/card_images/jr_sprite.jr_sprite"));
	if (Material.Object != nullptr)
	{
		auto* sprite = (UPaperSprite*)Material.Object;
		spriteComp->SetSprite(sprite);
	}
}

// Called when the game starts or when spawned
void ACard::BeginPlay()
{
	Super::BeginPlay();
}

// Called every frame
void ACard::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}

void ACard::SetImage(const std::string& imgName)
{
	std::string texName = "/Game/Resources/card_images/" + imgName + "." + imgName;
	std::string resourceName = "/Game/Resources/card_images/" + imgName + "_sprite." + imgName + "_sprite";

	auto texFs = FString(texName.c_str());
	auto fs = FString(resourceName.c_str());

	auto* tex = static_cast<UTexture2D*>(StaticLoadObject(UTexture2D::StaticClass(), nullptr, *texFs, TEXT("")));

	FSpriteAssetInitParameters params;
	params.SetTextureAndFill(tex);

	auto* sprite = static_cast<UPaperSprite*>(StaticConstructObject(UPaperSprite::StaticClass(), spriteComp));
	sprite->InitializeSprite(params);

	spriteComp->SetSprite(sprite);
}<commit_msg>Removed deprecated function<commit_after>// Fill out your copyright notice in the Description page of Project Settings.

#include "Mighty.h"
#include "Card.h"

#include "PaperSpriteActor.h"
#include "PaperSprite.h"
#include "PaperSpriteComponent.h"

// Sets default values
ACard::ACard()
{
	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	RootComponent = spriteComp = CreateDefaultSubobject<UPaperSpriteComponent>(TEXT("PrimarySprite"));

	ConstructorHelpers::FObjectFinder<UPaperSprite> Material(TEXT("/Game/Resources/card_images/jr_sprite.jr_sprite"));
	if (Material.Object != nullptr)
	{
		auto* sprite = (UPaperSprite*)Material.Object;
		spriteComp->SetSprite(sprite);
	}
}

// Called when the game starts or when spawned
void ACard::BeginPlay()
{
	Super::BeginPlay();
}

// Called every frame
void ACard::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}

void ACard::SetImage(const std::string& imgName)
{
	std::string texName = "/Game/Resources/card_images/" + imgName + "." + imgName;
	std::string resourceName = "/Game/Resources/card_images/" + imgName + "_sprite." + imgName + "_sprite";

	auto texFs = FString(texName.c_str());
	auto fs = FString(resourceName.c_str());

	auto* tex = static_cast<UTexture2D*>(StaticLoadObject(UTexture2D::StaticClass(), nullptr, *texFs, TEXT("")));

	FSpriteAssetInitParameters params;
	params.SetTextureAndFill(tex);

	auto* sprite = NewObject<UPaperSprite>(spriteComp, UPaperSprite::StaticClass());
	sprite->InitializeSprite(params);

	spriteComp->SetSprite(sprite);
}<|endoftext|>


<commit_before>
/**
 * @file TeamBallLocator.h
 *
 * Implementation of class TeamBallLocator
 */

#include "TeamBallLocator.h"

TeamBallLocator::TeamBallLocator()
{
  DEBUG_REQUEST_REGISTER("TeamBallLocator:draw_ball_on_field", "draw the team ball model on the field", false);
}

void TeamBallLocator::execute()
{
  msgData = getTeamMessage().data;

  for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=msgData.begin(); i != msgData.end(); ++i)
  {
    const TeamMessage::Data& msg = i->second;
    const unsigned int& playerNumber = i->first;

    // -1 means invalid ball
    if(msg.ballAge >= 0)
    {
      // collect messages
      Vector2dTS ballPosTS;
      ballPosTS.vec = msg.pose * msg.ballPosition;
      ballPosTS.t = msg.frameInfo.getTimeInSeconds(); // maybe +msg.BallAge ?
      ballPosHist.push_back(ballPosTS);

      // set time
      if (msg.frameInfo.getTimeInSeconds() > getTeamBallModel().time )
      {
        ASSERT(msg.frameInfo.getTimeInSeconds() >= 0);
        // are full seconds really the way to go?
        getTeamBallModel().time = (unsigned int)msg.frameInfo.getTimeInSeconds();
      }

      // goalie
      if(playerNumber == 1)
      {
        getTeamBallModel().goaliePositionOnField = ballPos;
        getTeamBallModel().goaliePosition = getRobotPose() / getTeamBallModel().goaliePositionOnField;
        getTeamBallModel().goalieTime = msg.frameInfo.getTime();
      }

      // striker
      if (msg.wasStriker)
      {
        getTeamBallModel().strikerPositionOnField = ballPos;
        getTeamBallModel().strikerPosition = getRobotPose() / getTeamBallModel().strikerPositionOnField;
        getTeamBallModel().strikerTime = msg.frameInfo.getTime();
      }
    }
  }

  // find oldest messages and erase them
  double maxTimeOffset = 1.0;
  sort(ballPosHist.begin(), ballPosHist.end());
  std::vector<Vector2dTS>::iterator cutOff;
  size_t cutOff = 0;
  // we are iterating through the sorted array from small (old) to high (new) times
  for(cutOff = ballPosHist.begin(); cutOff != ballPosHist.end(); cutOff++)
  {
    // take care: getTeamBallModel().time are unsigned int seconds
    if(cutOff->t >= getTeamBallModel().time - maxTimeOffset)
    {
      break;
    }
  }
  ballPosHist.erase(ballPosHist.begin(), cutOff);

  // median in x and y
  std::vector<double> xHist(ballPosHist.size());
  std::vector<double> yHist(ballPosHist.size());
  for(size_t i = 0; i < ballPosHist.size(); i++)
  {
    xHist.push_back(ballPosHist.vec.x);
    yHist.push_back(ballPosHist.vec.y);
  }
  sort(xHist.begin(), xHist.end());
  sort(yHist.begin(), yHist.end());
  Vector2d teamball;
  teamball.x = xHist[xHist.size()/2];
  teamball.y = yHist[yHist.size()/2];

  // write result and transform
  getTeamBallModel().positionOnField = teamball;
  getTeamBallModel().position = getRobotPose() / getTeamBallModel().positionOnField;

  DEBUG_REQUEST("TeamBallLocator:draw_ball_on_field",
    FIELD_DRAWING_CONTEXT;
    PEN("FF0000", 20);
    CIRCLE(getTeamBallModel().positionOnField.x, getTeamBallModel().positionOnField.y, 45);
    TEXT_DRAWING(getTeamBallModel().positionOnField.x, getTeamBallModel().positionOnField.y, ballPosHist.size());
  );
}
<commit_msg>added debig request to draw all used balls<commit_after>
/**
 * @file TeamBallLocator.h
 *
 * Implementation of class TeamBallLocator
 */

#include "TeamBallLocator.h"

TeamBallLocator::TeamBallLocator()
{
  DEBUG_REQUEST_REGISTER("TeamBallLocator:draw_ball_on_field", "draw the team ball model on the field", false);
  DEBUG_REQUEST_REGISTER("TeamBallLocator:draw_teamball_input", "draw all the balls uses for teamballw
  ", false);
}

void TeamBallLocator::execute()
{
  msgData = getTeamMessage().data;

  for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=msgData.begin(); i != msgData.end(); ++i)
  {
    const TeamMessage::Data& msg = i->second;
    const unsigned int& playerNumber = i->first;

    // -1 means invalid ball
    if(msg.ballAge >= 0)
    {
      // collect messages
      Vector2dTS ballPosTS;
      ballPosTS.vec = msg.pose * msg.ballPosition;
      ballPosTS.t = msg.frameInfo.getTimeInSeconds(); // maybe +msg.BallAge ?
      ballPosHist.push_back(ballPosTS);

      // set time
      if (msg.frameInfo.getTimeInSeconds() > getTeamBallModel().time )
      {
        ASSERT(msg.frameInfo.getTimeInSeconds() >= 0);
        // are full seconds really the way to go?
        getTeamBallModel().time = (unsigned int)msg.frameInfo.getTimeInSeconds();
      }

      // goalie
      if(playerNumber == 1)
      {
        getTeamBallModel().goaliePositionOnField = ballPos;
        getTeamBallModel().goaliePosition = getRobotPose() / getTeamBallModel().goaliePositionOnField;
        getTeamBallModel().goalieTime = msg.frameInfo.getTime();
      }

      // striker
      if (msg.wasStriker)
      {
        getTeamBallModel().strikerPositionOnField = ballPos;
        getTeamBallModel().strikerPosition = getRobotPose() / getTeamBallModel().strikerPositionOnField;
        getTeamBallModel().strikerTime = msg.frameInfo.getTime();
      }
    }
  }

  // find oldest messages and erase them
  double maxTimeOffset = 1.0;
  sort(ballPosHist.begin(), ballPosHist.end());
  std::vector<Vector2dTS>::iterator cutOff;
  size_t cutOff = 0;
  // we are iterating through the sorted array from small (old) to high (new) times
  for(cutOff = ballPosHist.begin(); cutOff != ballPosHist.end(); cutOff++)
  {
    // take care: getTeamBallModel().time are unsigned int seconds
    if(cutOff->t >= getTeamBallModel().time - maxTimeOffset)
    {
      break;
    }
  }
  ballPosHist.erase(ballPosHist.begin(), cutOff);

  DEBUG_REQUEST("TeamBallLocator:draw_teamball_input",
    FIELD_DRAWING_CONTEXT;
    PEN("FF0000", 20);
    for(size_t i = 0; i < ballPosHist.size(); i++)
    {
      CIRCLE(ballPosHist[i].vec.x, ballPosHist[i].vec.y, 50);
    }
  );

  // median in x and y
  std::vector<double> xHist(ballPosHist.size());
  std::vector<double> yHist(ballPosHist.size());
  for(size_t i = 0; i < ballPosHist.size(); i++)
  {
    xHist.push_back(ballPosHist.vec.x);
    yHist.push_back(ballPosHist.vec.y);
  }
  sort(xHist.begin(), xHist.end());
  sort(yHist.begin(), yHist.end());
  Vector2d teamball;
  teamball.x = xHist[xHist.size()/2];
  teamball.y = yHist[yHist.size()/2];

  // write result and transform
  getTeamBallModel().positionOnField = teamball;
  getTeamBallModel().position = getRobotPose() / getTeamBallModel().positionOnField;

  DEBUG_REQUEST("TeamBallLocator:draw_ball_on_field",
    FIELD_DRAWING_CONTEXT;
    PEN("FF0000", 20);
    CIRCLE(getTeamBallModel().positionOnField.x, getTeamBallModel().positionOnField.y, 45);
    TEXT_DRAWING(getTeamBallModel().positionOnField.x, getTeamBallModel().positionOnField.y, ballPosHist.size());
  );
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 HOLDER 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.
#include "../co_utils.h"
#include "../co_unittest.h"
#include <iostream>

class UtilsRef : public co::IntrusiveRef {
public:
  UtilsRef(void) {
    std::cout << "unittest.UtilsRef::UtilsRef" << std::endl;
  }

  ~UtilsRef(void) {
    std::cout << "unittest.UtilsRef::~UtilsRef" << std::endl;
  }
};

CO_TEST(Utils, co::test::FakeTest) {
  std::shared_ptr<UtilsRef> p1 = co::make_shared<UtilsRef>();
}
<commit_msg>chore(co.unittest.utils): updated test for utils functions<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 HOLDER 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.
#include "../co_utils.h"
#include "../co_unittest.h"
#include <iostream>

class UtilsRef : public co::IntrusiveRef {
public:
  UtilsRef(void) {
    std::cout << "unittest.UtilsRef::UtilsRef" << std::endl;
  }

  ~UtilsRef(void) {
    std::cout << "unittest.UtilsRef::~UtilsRef" << std::endl;
  }
};

CO_TEST(Utils, co::test::FakeTest) {
  std::shared_ptr<UtilsRef> p1 = co::make_shared<UtilsRef>();
  std::shared_ptr<UtilsRef> p2 = co::shared_from_this(p1.get());

  co::IntrusiveRefGuard guard1(p1.get());
  co::IntrusiveRefGuard guard2(p2.get());
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011-2013 Blender Foundation
 *
 * 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 <stdlib.h>

#include "background.h"
#include "camera.h"
#include "curves.h"
#include "device.h"
#include "film.h"
#include "integrator.h"
#include "light.h"
#include "mesh.h"
#include "object.h"
#include "osl.h"
#include "particles.h"
#include "scene.h"
#include "shader.h"
#include "svm.h"
#include "tables.h"

#include "util_foreach.h"
#include "util_progress.h"

CCL_NAMESPACE_BEGIN

Scene::Scene(const SceneParams& params_, const DeviceInfo& device_info_)
: params(params_)
{
	device = NULL;
	memset(&dscene.data, 0, sizeof(dscene.data));

	camera = new Camera();
	lookup_tables = new LookupTables();
	film = new Film();
	background = new Background();
	light_manager = new LightManager();
	mesh_manager = new MeshManager();
	object_manager = new ObjectManager();
	integrator = new Integrator();
	image_manager = new ImageManager();
	particle_system_manager = new ParticleSystemManager();
	curve_system_manager = new CurveSystemManager();

	/* OSL only works on the CPU */
	if(device_info_.type == DEVICE_CPU)
		shader_manager = ShaderManager::create(this, params.shadingsystem);
	else
		shader_manager = ShaderManager::create(this, SceneParams::SVM);

	if (device_info_.type == DEVICE_CPU)
		image_manager->set_extended_image_limits();
}

Scene::~Scene()
{
	free_memory(true);
}

void Scene::free_memory(bool final)
{
	foreach(Shader *s, shaders)
		delete s;
	foreach(Mesh *m, meshes)
		delete m;
	foreach(Object *o, objects)
		delete o;
	foreach(Light *l, lights)
		delete l;
	foreach(ParticleSystem *p, particle_systems)
		delete p;

	shaders.clear();
	meshes.clear();
	objects.clear();
	lights.clear();
	particle_systems.clear();

	if(device) {
		camera->device_free(device, &dscene);
		film->device_free(device, &dscene, this);
		background->device_free(device, &dscene);
		integrator->device_free(device, &dscene);

		object_manager->device_free(device, &dscene);
		mesh_manager->device_free(device, &dscene);
		shader_manager->device_free(device, &dscene, this);
		light_manager->device_free(device, &dscene);

		particle_system_manager->device_free(device, &dscene);
		curve_system_manager->device_free(device, &dscene);

		if(!params.persistent_data || final)
			image_manager->device_free(device, &dscene);

		lookup_tables->device_free(device, &dscene);
	}

	if(final) {
		delete lookup_tables;
		delete camera;
		delete film;
		delete background;
		delete integrator;
		delete object_manager;
		delete mesh_manager;
		delete shader_manager;
		delete light_manager;
		delete particle_system_manager;
		delete curve_system_manager;
		delete image_manager;
	}
}

void Scene::device_update(Device *device_, Progress& progress)
{
	if(!device)
		device = device_;

	/* The order of updates is important, because there's dependencies between
	 * the different managers, using data computed by previous managers.
	 *
	 * - Image manager uploads images used by shaders.
	 * - Camera may be used for adapative subdivison.
	 * - Displacement shader must have all shader data available.
	 * - Light manager needs lookup tables and final mesh data to compute emission CDF.
	 */

	image_manager->set_pack_images(device->info.pack_images);

	progress.set_status("Updating Shaders");
	shader_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Images");
	image_manager->device_update(device, &dscene, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Background");
	background->device_update(device, &dscene, this);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Camera");
	camera->device_update(device, &dscene, this);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Objects");
	object_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Hair Systems");
	curve_system_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Film");
	film->device_update(device, &dscene, this);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Lookup Tables");
	lookup_tables->device_update(device, &dscene);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Meshes");
	mesh_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Lights");
	light_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Particle Systems");
	particle_system_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Integrator");
	integrator->device_update(device, &dscene, this);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Device", "Writing constant memory");
	device->const_copy_to("__data", &dscene.data, sizeof(dscene.data));
}

Scene::MotionType Scene::need_motion(bool advanced_shading)
{
	if(integrator->motion_blur)
		return (advanced_shading)? MOTION_BLUR: MOTION_NONE;
	else if(Pass::contains(film->passes, PASS_MOTION))
		return MOTION_PASS;
	else
		return MOTION_NONE;
}

bool Scene::need_global_attribute(AttributeStandard std)
{
	if(std == ATTR_STD_UV)
		return Pass::contains(film->passes, PASS_UV);
	if(std == ATTR_STD_MOTION_PRE || std == ATTR_STD_MOTION_POST)
		return need_motion() == MOTION_PASS;

	return false;
}

void Scene::need_global_attributes(AttributeRequestSet& attributes)
{
	for(int std = ATTR_STD_NONE; std < ATTR_STD_NUM; std++)
		if(need_global_attribute((AttributeStandard)std))
			attributes.add((AttributeStandard)std);
}

bool Scene::need_update()
{
	return (need_reset() || film->need_update);
}

bool Scene::need_reset()
{
	return (background->need_update
		|| image_manager->need_update
		|| camera->need_update
		|| object_manager->need_update
		|| mesh_manager->need_update
		|| light_manager->need_update
		|| lookup_tables->need_update
		|| integrator->need_update
		|| shader_manager->need_update
		|| particle_system_manager->need_update
		|| curve_system_manager->need_update);
}

void Scene::reset()
{
	shader_manager->reset(this);
	shader_manager->add_default(this);

	/* ensure all objects are updated */
	camera->tag_update();
	film->tag_update(this);
	background->tag_update(this);
	integrator->tag_update(this);
}

void Scene::device_free()
{
	free_memory(false);
}

CCL_NAMESPACE_END

<commit_msg>Fix T39114: cycles lamp ray visibility not working.<commit_after>/*
 * Copyright 2011-2013 Blender Foundation
 *
 * 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 <stdlib.h>

#include "background.h"
#include "camera.h"
#include "curves.h"
#include "device.h"
#include "film.h"
#include "integrator.h"
#include "light.h"
#include "mesh.h"
#include "object.h"
#include "osl.h"
#include "particles.h"
#include "scene.h"
#include "shader.h"
#include "svm.h"
#include "tables.h"

#include "util_foreach.h"
#include "util_progress.h"

CCL_NAMESPACE_BEGIN

Scene::Scene(const SceneParams& params_, const DeviceInfo& device_info_)
: params(params_)
{
	device = NULL;
	memset(&dscene.data, 0, sizeof(dscene.data));

	camera = new Camera();
	lookup_tables = new LookupTables();
	film = new Film();
	background = new Background();
	light_manager = new LightManager();
	mesh_manager = new MeshManager();
	object_manager = new ObjectManager();
	integrator = new Integrator();
	image_manager = new ImageManager();
	particle_system_manager = new ParticleSystemManager();
	curve_system_manager = new CurveSystemManager();

	/* OSL only works on the CPU */
	if(device_info_.type == DEVICE_CPU)
		shader_manager = ShaderManager::create(this, params.shadingsystem);
	else
		shader_manager = ShaderManager::create(this, SceneParams::SVM);

	if (device_info_.type == DEVICE_CPU)
		image_manager->set_extended_image_limits();
}

Scene::~Scene()
{
	free_memory(true);
}

void Scene::free_memory(bool final)
{
	foreach(Shader *s, shaders)
		delete s;
	foreach(Mesh *m, meshes)
		delete m;
	foreach(Object *o, objects)
		delete o;
	foreach(Light *l, lights)
		delete l;
	foreach(ParticleSystem *p, particle_systems)
		delete p;

	shaders.clear();
	meshes.clear();
	objects.clear();
	lights.clear();
	particle_systems.clear();

	if(device) {
		camera->device_free(device, &dscene);
		film->device_free(device, &dscene, this);
		background->device_free(device, &dscene);
		integrator->device_free(device, &dscene);

		object_manager->device_free(device, &dscene);
		mesh_manager->device_free(device, &dscene);
		shader_manager->device_free(device, &dscene, this);
		light_manager->device_free(device, &dscene);

		particle_system_manager->device_free(device, &dscene);
		curve_system_manager->device_free(device, &dscene);

		if(!params.persistent_data || final)
			image_manager->device_free(device, &dscene);

		lookup_tables->device_free(device, &dscene);
	}

	if(final) {
		delete lookup_tables;
		delete camera;
		delete film;
		delete background;
		delete integrator;
		delete object_manager;
		delete mesh_manager;
		delete shader_manager;
		delete light_manager;
		delete particle_system_manager;
		delete curve_system_manager;
		delete image_manager;
	}
}

void Scene::device_update(Device *device_, Progress& progress)
{
	if(!device)
		device = device_;

	/* The order of updates is important, because there's dependencies between
	 * the different managers, using data computed by previous managers.
	 *
	 * - Image manager uploads images used by shaders.
	 * - Camera may be used for adapative subdivison.
	 * - Displacement shader must have all shader data available.
	 * - Light manager needs lookup tables and final mesh data to compute emission CDF.
	 * - Film needs light manager to run for use_light_visibility
	 * - Lookup tables are done a second time to handle film tables
	 */

	image_manager->set_pack_images(device->info.pack_images);

	progress.set_status("Updating Shaders");
	shader_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Images");
	image_manager->device_update(device, &dscene, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Background");
	background->device_update(device, &dscene, this);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Camera");
	camera->device_update(device, &dscene, this);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Objects");
	object_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Hair Systems");
	curve_system_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Lookup Tables");
	lookup_tables->device_update(device, &dscene);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Meshes");
	mesh_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Lights");
	light_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Particle Systems");
	particle_system_manager->device_update(device, &dscene, this, progress);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Film");
	film->device_update(device, &dscene, this);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Integrator");
	integrator->device_update(device, &dscene, this);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Lookup Tables");
	lookup_tables->device_update(device, &dscene);

	if(progress.get_cancel()) return;

	progress.set_status("Updating Device", "Writing constant memory");
	device->const_copy_to("__data", &dscene.data, sizeof(dscene.data));
}

Scene::MotionType Scene::need_motion(bool advanced_shading)
{
	if(integrator->motion_blur)
		return (advanced_shading)? MOTION_BLUR: MOTION_NONE;
	else if(Pass::contains(film->passes, PASS_MOTION))
		return MOTION_PASS;
	else
		return MOTION_NONE;
}

bool Scene::need_global_attribute(AttributeStandard std)
{
	if(std == ATTR_STD_UV)
		return Pass::contains(film->passes, PASS_UV);
	if(std == ATTR_STD_MOTION_PRE || std == ATTR_STD_MOTION_POST)
		return need_motion() == MOTION_PASS;

	return false;
}

void Scene::need_global_attributes(AttributeRequestSet& attributes)
{
	for(int std = ATTR_STD_NONE; std < ATTR_STD_NUM; std++)
		if(need_global_attribute((AttributeStandard)std))
			attributes.add((AttributeStandard)std);
}

bool Scene::need_update()
{
	return (need_reset() || film->need_update);
}

bool Scene::need_reset()
{
	return (background->need_update
		|| image_manager->need_update
		|| camera->need_update
		|| object_manager->need_update
		|| mesh_manager->need_update
		|| light_manager->need_update
		|| lookup_tables->need_update
		|| integrator->need_update
		|| shader_manager->need_update
		|| particle_system_manager->need_update
		|| curve_system_manager->need_update);
}

void Scene::reset()
{
	shader_manager->reset(this);
	shader_manager->add_default(this);

	/* ensure all objects are updated */
	camera->tag_update();
	film->tag_update(this);
	background->tag_update(this);
	integrator->tag_update(this);
}

void Scene::device_free()
{
	free_memory(false);
}

CCL_NAMESPACE_END

<|endoftext|>