<commit_before>/*************************************************************************
 *
 *  $RCSfile: AccessibleOutlineView.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: thb $ $Date: 2002-05-17 18:59:26 $
 *
 *  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 _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_
#include <com/sun/star/drawing/XDrawView.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_
#include <com/sun/star/document/XEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBLE_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULSTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _SFXFRAME_HXX
#include<sfx2/viewfrm.hxx>
#endif

#include <svx/AccessibleShape.hxx>

#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/unoapi.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include "sdwindow.hxx"
#include <vcl/svapp.hxx>

#ifndef _SD_SDWINDOW_HXX
#include "sdwindow.hxx"
#endif
#ifndef _SD_VIEWSHEL_HXX
#include "viewshel.hxx"
#endif
#ifndef _SD_OUTLNVSH_HXX
#include "outlnvsh.hxx"
#endif
#ifndef _SD_SDVIEW_HXX
#include "sdview.hxx"
#endif
#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_VIEW_HXX
#include "AccessibleOutlineView.hxx"
#endif
#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_EDITSOURCE_HXX
#include "AccessibleOutlineEditSource.hxx"
#endif

#include <memory>

using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;

namespace accessibility {

//=====  internal  ============================================================

AccessibleOutlineView::AccessibleOutlineView (
    SdWindow* pSdWindow,
    SdOutlineViewShell* pViewShell,
    const uno::Reference<frame::XController>& rxController,
    const uno::Reference<XAccessible>& rxParent)
    : AccessibleDocumentViewBase (pSdWindow, pViewShell, rxController, rxParent)
{
    // Beware! Here we leave the paths of the UNO API and descend into the
    // depths of the core.  Necessary for makeing the edit engine accessible.
    if( pViewShell && pSdWindow )
    {
        SdView* pView = pViewShell->GetView();

        if( pView && pView->ISA(SdOutlineView) )
        {
            OutlinerView* pOutlineView = static_cast< SdOutlineView* >(pView)->GetViewByWindow( pSdWindow );
            SdrOutliner* pOutliner = static_cast< SdOutlineView* >(pView)->GetOutliner();

            if( pOutlineView && pOutliner )
            {
                mpTextHelper =
                    ::std::auto_ptr< AccessibleTextHelper >( new AccessibleTextHelper(
                                                                 this,
                                                                 ::std::auto_ptr< SvxEditSource >( new AccessibleOutlineEditSource(
                                                                                *pOutliner, *pView, *pOutlineView, *pSdWindow ) ) ) );
            }
        }
    }
}

AccessibleOutlineView::~AccessibleOutlineView (void)
{
    OSL_TRACE ("~AccessibleOutlineView");
}

void AccessibleOutlineView::Init (void)
{
    AccessibleDocumentViewBase::Init ();
}

void AccessibleOutlineView::ViewForwarderChanged (ChangeType aChangeType,
    const IAccessibleViewForwarder* pViewForwarder)
{
    AccessibleDocumentViewBase::ViewForwarderChanged (aChangeType, pViewForwarder);

    UpdateChildren();
}

//=====  XAccessibleContext  ==================================================

sal_Int32 SAL_CALL
    AccessibleOutlineView::getAccessibleChildCount (void)
    throw (uno::RuntimeException)
{
    // forward
    if( mpTextHelper.get() )
        return mpTextHelper->GetChildCount();

    return 0;
}

uno::Reference<XAccessible> SAL_CALL
    AccessibleOutlineView::getAccessibleChild (long nIndex)
    throw (::com::sun::star::uno::RuntimeException)
{
    // forward
    if( mpTextHelper.get() )
    {
        // Forward request to children manager.
        return mpTextHelper->GetChild(nIndex);
    }
    else
        throw lang::IndexOutOfBoundsException (
            ::rtl::OUString::createFromAscii ("no accessible child with index ") + nIndex,
            static_cast<uno::XWeak*>(this));
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessibleOutlineView::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleOutlineView"));
}

//=====  XEventListener  ======================================================

void SAL_CALL
    AccessibleOutlineView::disposing (const lang::EventObject& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::disposing (rEventObject);

    // dispose children
    mpTextHelper.reset();
}

//=====  XFrameActionListener  ================================================

void SAL_CALL
    AccessibleOutlineView::frameAction (const frame::FrameActionEvent& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::frameAction (rEventObject);

    if (rEventObject.Action == frame::FrameAction_COMPONENT_REATTACHED)
        UpdateChildren();
}

//=====  XPropertyChangeListener  =============================================

void SAL_CALL
    AccessibleOutlineView::propertyChange (const beans::PropertyChangeEvent& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::propertyChange (rEventObject);

    OSL_TRACE ("AccessibleOutlineView::propertyChange");
    if (rEventObject.PropertyName == ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("CurrentPage")))
    {
        OSL_TRACE ("    current page changed");

        // The current page changed. Update the children accordingly.
        UpdateChildren();
    }
    else if (rEventObject.PropertyName == ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("VisibleArea")))
    {
        OSL_TRACE ("    visible area changed");

        // The visible area changed. Update the children accordingly.
        UpdateChildren();
    }
    else
    {
        OSL_TRACE ("  unhandled");
    }
    OSL_TRACE ("  done");
}

/// Create a name for this view.
::rtl::OUString
    AccessibleOutlineView::CreateAccessibleName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString (
        RTL_CONSTASCII_USTRINGPARAM("AccessibleOutlineView"));
}

/** Create a description for this view.  Use the model's description or URL
    if a description is not available.
*/
::rtl::OUString
    AccessibleOutlineView::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    rtl::OUString sDescription;

    sDescription = ::rtl::OUString (
        RTL_CONSTASCII_USTRINGPARAM("Accessible Draw Document Outline"));

    return sDescription;
}

void AccessibleOutlineView::UpdateChildren()
{
    // Update visible children
    if( mpTextHelper.get() )
        mpTextHelper->UpdateChildren();
}

} // end of namespace accessibility
<commit_msg>#100178# Removed call of AccessibleDocumentViewBase::frameAction which does not exist any longer.<commit_after>/*************************************************************************
 *
 *  $RCSfile: AccessibleOutlineView.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: af $ $Date: 2002-06-12 12:34:41 $
 *
 *  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 _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_
#include <com/sun/star/drawing/XDrawView.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_
#include <com/sun/star/document/XEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBLE_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULSTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _SFXFRAME_HXX
#include<sfx2/viewfrm.hxx>
#endif

#include <svx/AccessibleShape.hxx>

#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/unoapi.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include "sdwindow.hxx"
#include <vcl/svapp.hxx>

#ifndef _SD_SDWINDOW_HXX
#include "sdwindow.hxx"
#endif
#ifndef _SD_VIEWSHEL_HXX
#include "viewshel.hxx"
#endif
#ifndef _SD_OUTLNVSH_HXX
#include "outlnvsh.hxx"
#endif
#ifndef _SD_SDVIEW_HXX
#include "sdview.hxx"
#endif
#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_VIEW_HXX
#include "AccessibleOutlineView.hxx"
#endif
#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_EDITSOURCE_HXX
#include "AccessibleOutlineEditSource.hxx"
#endif

#include <memory>

using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;

namespace accessibility {

//=====  internal  ============================================================

AccessibleOutlineView::AccessibleOutlineView (
    SdWindow* pSdWindow,
    SdOutlineViewShell* pViewShell,
    const uno::Reference<frame::XController>& rxController,
    const uno::Reference<XAccessible>& rxParent)
    : AccessibleDocumentViewBase (pSdWindow, pViewShell, rxController, rxParent)
{
    // Beware! Here we leave the paths of the UNO API and descend into the
    // depths of the core.  Necessary for makeing the edit engine accessible.
    if( pViewShell && pSdWindow )
    {
        SdView* pView = pViewShell->GetView();

        if( pView && pView->ISA(SdOutlineView) )
        {
            OutlinerView* pOutlineView = static_cast< SdOutlineView* >(pView)->GetViewByWindow( pSdWindow );
            SdrOutliner* pOutliner = static_cast< SdOutlineView* >(pView)->GetOutliner();

            if( pOutlineView && pOutliner )
            {
                mpTextHelper =
                    ::std::auto_ptr< AccessibleTextHelper >( new AccessibleTextHelper(
                                                                 this,
                                                                 ::std::auto_ptr< SvxEditSource >( new AccessibleOutlineEditSource(
                                                                                *pOutliner, *pView, *pOutlineView, *pSdWindow ) ) ) );
            }
        }
    }
}

AccessibleOutlineView::~AccessibleOutlineView (void)
{
    OSL_TRACE ("~AccessibleOutlineView");
}

void AccessibleOutlineView::Init (void)
{
    AccessibleDocumentViewBase::Init ();
}

void AccessibleOutlineView::ViewForwarderChanged (ChangeType aChangeType,
    const IAccessibleViewForwarder* pViewForwarder)
{
    AccessibleDocumentViewBase::ViewForwarderChanged (aChangeType, pViewForwarder);

    UpdateChildren();
}

//=====  XAccessibleContext  ==================================================

sal_Int32 SAL_CALL
    AccessibleOutlineView::getAccessibleChildCount (void)
    throw (uno::RuntimeException)
{
    // forward
    if( mpTextHelper.get() )
        return mpTextHelper->GetChildCount();

    return 0;
}

uno::Reference<XAccessible> SAL_CALL
    AccessibleOutlineView::getAccessibleChild (long nIndex)
    throw (::com::sun::star::uno::RuntimeException)
{
    // forward
    if( mpTextHelper.get() )
    {
        // Forward request to children manager.
        return mpTextHelper->GetChild(nIndex);
    }
    else
        throw lang::IndexOutOfBoundsException (
            ::rtl::OUString::createFromAscii ("no accessible child with index ") + nIndex,
            static_cast<uno::XWeak*>(this));
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessibleOutlineView::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleOutlineView"));
}

//=====  XEventListener  ======================================================

void SAL_CALL
    AccessibleOutlineView::disposing (const lang::EventObject& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::disposing (rEventObject);

    // dispose children
    mpTextHelper.reset();
}

//=====  XFrameActionListener  ================================================

void SAL_CALL
    AccessibleOutlineView::frameAction (const frame::FrameActionEvent& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    //    AccessibleDocumentViewBase::frameAction (rEventObject);

    if (rEventObject.Action == frame::FrameAction_COMPONENT_REATTACHED)
        UpdateChildren();
}

//=====  XPropertyChangeListener  =============================================

void SAL_CALL
    AccessibleOutlineView::propertyChange (const beans::PropertyChangeEvent& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::propertyChange (rEventObject);

    OSL_TRACE ("AccessibleOutlineView::propertyChange");
    if (rEventObject.PropertyName == ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("CurrentPage")))
    {
        OSL_TRACE ("    current page changed");

        // The current page changed. Update the children accordingly.
        UpdateChildren();
    }
    else if (rEventObject.PropertyName == ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("VisibleArea")))
    {
        OSL_TRACE ("    visible area changed");

        // The visible area changed. Update the children accordingly.
        UpdateChildren();
    }
    else
    {
        OSL_TRACE ("  unhandled");
    }
    OSL_TRACE ("  done");
}

/// Create a name for this view.
::rtl::OUString
    AccessibleOutlineView::CreateAccessibleName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString (
        RTL_CONSTASCII_USTRINGPARAM("AccessibleOutlineView"));
}

/** Create a description for this view.  Use the model's description or URL
    if a description is not available.
*/
::rtl::OUString
    AccessibleOutlineView::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    rtl::OUString sDescription;

    sDescription = ::rtl::OUString (
        RTL_CONSTASCII_USTRINGPARAM("Accessible Draw Document Outline"));

    return sDescription;
}

void AccessibleOutlineView::UpdateChildren()
{
    // Update visible children
    if( mpTextHelper.get() )
        mpTextHelper->UpdateChildren();
}

} // end of namespace accessibility
<|endoftext|>


<commit_before>#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>

#include <rviz/ogre_helpers/arrow.h>
#include <rviz/ogre_helpers/shape.h>
#include <rviz/display_context.h>
#include <rviz/display_factory.h>

#include<tf2/LinearMath/Quaternion.h>

#include "reachability_map_visual.h"
#include <iterator>

namespace workspace_visualization
{

ReachMapVisual::ReachMapVisual( Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node, rviz::DisplayContext* display_context)
{
  scene_manager_ = scene_manager;
  frame_node_ = parent_node->createChildSceneNode();

  //arrow_.reset(new rviz::Arrow( scene_manager_, frame_node_ ));
}

ReachMapVisual::~ReachMapVisual()
{
  scene_manager_->destroySceneNode( frame_node_ );
}

void ReachMapVisual::setMessage( const map_creator::WorkSpace::ConstPtr& msg, bool do_display_arrow, bool do_display_sphere, int low_ri, int high_ri, int shape_choice, int disect_choice)
{
 int low_SphereSize, up_SphereSize;

  switch(disect_choice){
    case 0: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size();
        break;}
    case 1: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size()/2;
        break;}
    case 2: {low_SphereSize = msg->WsSpheres.size()/2;
        up_SphereSize = msg->WsSpheres.size();
        break;}
    case 3: {low_SphereSize = msg->WsSpheres.size()/2.2;
        up_SphereSize = msg->WsSpheres.size()/1.8;
        break;}
    case 4: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size()/1.1;
        break;}
   }

  if(do_display_arrow){
  boost::shared_ptr<rviz::Arrow> pose_arrow;
  for (size_t i = low_SphereSize; i < up_SphereSize; ++i) {
	for(size_t j=0;j < msg->WsSpheres[i].poses.size(); ++j){
	if(low_ri<int(msg->WsSpheres[i].ri) && int(msg->WsSpheres[i].ri)<=high_ri){

  pose_arrow.reset(new rviz::Arrow( scene_manager_, frame_node_ ));

  Ogre::Vector3 position_(msg->WsSpheres[i].poses[j].position.x,
                         msg->WsSpheres[i].poses[j].position.y,
                         msg->WsSpheres[i].poses[j].position.z);
  tf2::Quaternion quat(msg->WsSpheres[i].poses[j].orientation.x,
                               msg->WsSpheres[i].poses[j].orientation.y,
                               msg->WsSpheres[i].poses[j].orientation.z,
                               msg->WsSpheres[i].poses[j].orientation.w);

  tf2::Quaternion q2;
  q2.setRPY(0,-M_PI/2,0); //Arrows are pointed as -z direction. So rotating it is necessary

  quat*=(q2);
  quat.normalize();
  Ogre::Quaternion orientation_(quat.w(), quat.x(), quat.y(), quat.z());

  if(position_.isNaN() || orientation_.isNaN()){
    ROS_WARN("received invalid pose");
    return;
  }

  pose_arrow->setPosition(position_);
  pose_arrow->setOrientation(orientation_);

  arrow_.push_back(pose_arrow);
    }
  }
  }
 }
  if(do_display_sphere){

  boost::shared_ptr<rviz::Shape> sphere_center;
  int colorRI;

  for (size_t i = low_SphereSize; i < up_SphereSize; ++i) {
    if(low_ri<=int(msg->WsSpheres[i].ri) && int(msg->WsSpheres[i].ri<=high_ri)){

  switch(shape_choice){
    case 0: {
	sphere_center.reset(new rviz::Shape(rviz::Shape::Sphere, scene_manager_,frame_node_ ));
        break;}
    case 1: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cylinder, scene_manager_,frame_node_ ));
        break;}
    case 2: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cone, scene_manager_,frame_node_ ));
        break;}
    case 3: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cube, scene_manager_,frame_node_ ));
        break;}

   }

  Ogre::Vector3 position_sphere(msg->WsSpheres[i].point.x,
                         msg->WsSpheres[i].point.y,
                         msg->WsSpheres[i].point.z);
  Ogre::Quaternion orientation_sphere(0,0,0,1);
  colorRI = msg->WsSpheres[i].ri;
  if(position_sphere.isNaN()){
    ROS_WARN("received invalid sphere coordinate");
    return;
    }
  sphere_center->setPosition(position_sphere);
  sphere_center->setOrientation(orientation_sphere);

  sphere_.push_back(sphere_center);
  colorRI_.push_back(colorRI);

   }
  }
 }
}

void ReachMapVisual::setFramePosition( const Ogre::Vector3& position )
{
  frame_node_->setPosition( position );
}

void ReachMapVisual::setFrameOrientation( const Ogre::Quaternion& orientation )
{
  frame_node_->setOrientation( orientation );
}

void ReachMapVisual::setColorArrow( float r, float g, float b, float a )
{
  for (int i=0;i<arrow_.size();++i)
  {
     arrow_[i]->setColor( r, g, b, a );
  }
}

void ReachMapVisual::setColorSphere( float r, float g, float b, float a )
{
  for (int i=0;i<sphere_.size();++i)
  {
     sphere_[i]->setColor( r, g, b, a );
  }
}

void ReachMapVisual::setColorSpherebyRI(float alpha )
{

  for (int i=0;i<sphere_.size();++i)
  {
     if(colorRI_[i]>=90){
     	sphere_[i]->setColor( 0, 0, 255, alpha );
     }
     else if(colorRI_[i]<90 && colorRI_[i]>=50 ){
     	sphere_[i]->setColor( 0, 255, 255, alpha );
     }
     else if(colorRI_[i]<50 && colorRI_[i]>=30 ){
     	sphere_[i]->setColor( 0, 255, 0, alpha );
     }
     else if(colorRI_[i]<30 && colorRI_[i]>=5 ){
     	sphere_[i]->setColor( 255, 255, 0, alpha );
     }
     else{
	sphere_[i]->setColor( 255, 0, 0, alpha );
     }
  }
}

void ReachMapVisual::setSizeArrow( float l )
{
  for (int i=0;i<arrow_.size();++i)
  {
     arrow_[i]->setScale( Ogre::Vector3(l, l, l));
  }
}

void ReachMapVisual::setSizeSphere( float l )
{
  for (int i=0;i<sphere_.size();++i)
  {
     sphere_[i]->setScale( Ogre::Vector3(l, l, l));
  }
}

}//end namespace workspace_visualization
<commit_msg>Update reachability_map_visual.cpp<commit_after>#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>

#include <rviz/ogre_helpers/arrow.h>
#include <rviz/ogre_helpers/shape.h>
#include <rviz/display_context.h>
#include <rviz/display_factory.h>

#include<tf2/LinearMath/Quaternion.h>

#include "reachability_map_visual.h"
#include <iterator>

namespace workspace_visualization
{

ReachMapVisual::ReachMapVisual( Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node, rviz::DisplayContext* display_context)
{
  scene_manager_ = scene_manager;
  frame_node_ = parent_node->createChildSceneNode();

  //arrow_.reset(new rviz::Arrow( scene_manager_, frame_node_ ));
}

ReachMapVisual::~ReachMapVisual()
{
  scene_manager_->destroySceneNode( frame_node_ );
}

void ReachMapVisual::setMessage( const map_creator::WorkSpace::ConstPtr& msg, bool do_display_arrow, bool do_display_sphere, int low_ri, int high_ri, int shape_choice, int disect_choice)
{
 int low_SphereSize, up_SphereSize;
//TODO: Not a very delicate process to dissect the workspace. Implement a way to provide a range and allow the user to select an axis and an upper/lower bound to slice with
  switch(disect_choice){
    case 0: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size();
        break;}
    case 1: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size()/2;
        break;}
    case 2: {low_SphereSize = msg->WsSpheres.size()/2;
        up_SphereSize = msg->WsSpheres.size();
        break;}
    case 3: {low_SphereSize = msg->WsSpheres.size()/2.2;
        up_SphereSize = msg->WsSpheres.size()/1.8;
        break;}
    case 4: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size()/1.1;
        break;}
   }

  if(do_display_arrow){
  boost::shared_ptr<rviz::Arrow> pose_arrow;
  for (size_t i = low_SphereSize; i < up_SphereSize; ++i) {
	for(size_t j=0;j < msg->WsSpheres[i].poses.size(); ++j){
	if(low_ri<int(msg->WsSpheres[i].ri) && int(msg->WsSpheres[i].ri)<=high_ri){

  pose_arrow.reset(new rviz::Arrow( scene_manager_, frame_node_ ));

  Ogre::Vector3 position_(msg->WsSpheres[i].poses[j].position.x,
                         msg->WsSpheres[i].poses[j].position.y,
                         msg->WsSpheres[i].poses[j].position.z);
  tf2::Quaternion quat(msg->WsSpheres[i].poses[j].orientation.x,
                               msg->WsSpheres[i].poses[j].orientation.y,
                               msg->WsSpheres[i].poses[j].orientation.z,
                               msg->WsSpheres[i].poses[j].orientation.w);

  tf2::Quaternion q2;
  q2.setRPY(0,-M_PI/2,0); //Arrows are pointed as -z direction. So rotating it is necessary

  quat*=(q2);
  quat.normalize();
  Ogre::Quaternion orientation_(quat.w(), quat.x(), quat.y(), quat.z());

  if(position_.isNaN() || orientation_.isNaN()){
    ROS_WARN("received invalid pose");
    return;
  }

  pose_arrow->setPosition(position_);
  pose_arrow->setOrientation(orientation_);

  arrow_.push_back(pose_arrow);
    }
  }
  }
 }
  if(do_display_sphere){

  boost::shared_ptr<rviz::Shape> sphere_center;
  int colorRI;

  for (size_t i = low_SphereSize; i < up_SphereSize; ++i) {
    if(low_ri<=int(msg->WsSpheres[i].ri) && int(msg->WsSpheres[i].ri<=high_ri)){

  switch(shape_choice){
    case 0: {
	sphere_center.reset(new rviz::Shape(rviz::Shape::Sphere, scene_manager_,frame_node_ ));
        break;}
    case 1: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cylinder, scene_manager_,frame_node_ ));
        break;}
    case 2: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cone, scene_manager_,frame_node_ ));
        break;}
    case 3: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cube, scene_manager_,frame_node_ ));
        break;}

   }

  Ogre::Vector3 position_sphere(msg->WsSpheres[i].point.x,
                         msg->WsSpheres[i].point.y,
                         msg->WsSpheres[i].point.z);
  Ogre::Quaternion orientation_sphere(0,0,0,1);
  colorRI = msg->WsSpheres[i].ri;
  if(position_sphere.isNaN()){
    ROS_WARN("received invalid sphere coordinate");
    return;
    }
  sphere_center->setPosition(position_sphere);
  sphere_center->setOrientation(orientation_sphere);

  sphere_.push_back(sphere_center);
  colorRI_.push_back(colorRI);

   }
  }
 }
}

void ReachMapVisual::setFramePosition( const Ogre::Vector3& position )
{
  frame_node_->setPosition( position );
}

void ReachMapVisual::setFrameOrientation( const Ogre::Quaternion& orientation )
{
  frame_node_->setOrientation( orientation );
}

void ReachMapVisual::setColorArrow( float r, float g, float b, float a )
{
  for (int i=0;i<arrow_.size();++i)
  {
     arrow_[i]->setColor( r, g, b, a );
  }
}

void ReachMapVisual::setColorSphere( float r, float g, float b, float a )
{
  for (int i=0;i<sphere_.size();++i)
  {
     sphere_[i]->setColor( r, g, b, a );
  }
}

void ReachMapVisual::setColorSpherebyRI(float alpha )
{

  for (int i=0;i<sphere_.size();++i)
  {
     if(colorRI_[i]>=90){
     	sphere_[i]->setColor( 0, 0, 255, alpha );
     }
     else if(colorRI_[i]<90 && colorRI_[i]>=50 ){
     	sphere_[i]->setColor( 0, 255, 255, alpha );
     }
     else if(colorRI_[i]<50 && colorRI_[i]>=30 ){
     	sphere_[i]->setColor( 0, 255, 0, alpha );
     }
     else if(colorRI_[i]<30 && colorRI_[i]>=5 ){
     	sphere_[i]->setColor( 255, 255, 0, alpha );
     }
     else{
	sphere_[i]->setColor( 255, 0, 0, alpha );
     }
  }
}

void ReachMapVisual::setSizeArrow( float l )
{
  for (int i=0;i<arrow_.size();++i)
  {
     arrow_[i]->setScale( Ogre::Vector3(l, l, l));
  }
}

void ReachMapVisual::setSizeSphere( float l )
{
  for (int i=0;i<sphere_.size();++i)
  {
     sphere_[i]->setScale( Ogre::Vector3(l, l, l));
  }
}

}//end namespace workspace_visualization
<|endoftext|>


<commit_before>//
//  Landscape.cpp
//
//  Created by Soso Limited on 5/26/15.
//
//

#include "Landscape.h"

#include "cinder/Log.h"

using namespace soso;
using namespace cinder;

namespace {

struct alignas(16) Vertex {
	vec3	position;
	vec3	normal;
	vec2	tex_coord;
	vec2	color_tex_coord;
	float deform_scaling;
	float frame_offset;
};

const auto kVertexLayout = ([] {
		auto layout = geom::BufferLayout();
		layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) );
		layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) );
		layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) );
		layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) );
		layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_scaling) );
		layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) );
		return layout;
	} ());

const auto kVertexMapping = ([] {
		return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" } };
	} ());

// Load a shader and handle exceptions. Return nullptr on failure.
gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment )
{
	try {
		auto shader_format = gl::GlslProg::Format()
			.vertex( app::loadAsset( iVertex ) )
			.fragment( app::loadAsset( iFragment ) );

		return gl::GlslProg::create( shader_format );
	}
	catch( ci::Exception &exc ) {
		CI_LOG_E( "Error loading shader: " << exc.what() );
	}

	return nullptr;
}

void addRectangle( std::vector<Vertex> &vertices, const ci::vec3 &iCenter, float iWidth, float iHeight, float iFrameOffset )
{
	auto right = vec3( iWidth / 2.0f, 0, 0 );
	auto left = - right;
	auto down = vec3( 0, 0, iHeight / 2.0f );
	auto up = - down;

	auto ul = iCenter + (left + up);
	auto ur = iCenter + (right + up);
	auto br = iCenter + (right + down);
	auto bl = iCenter + (left + down);

	auto normal = vec3( 0, 1, 0 );
	auto deform_scaling = 0.0f;

	vertices.insert( vertices.end(), {
		Vertex{ ul, normal, vec2(0, 0), vec2(0, 0), deform_scaling, iFrameOffset },
		Vertex{ ur, normal, vec2(1, 0), vec2(1, 0), deform_scaling, iFrameOffset },
		Vertex{ br, normal, vec2(1, 1), vec2(1, 1), deform_scaling, iFrameOffset },

		Vertex{ ul, normal, vec2(0, 0), vec2(0, 0), deform_scaling, iFrameOffset },
		Vertex{ br, normal, vec2(1, 1), vec2(1, 1), deform_scaling, iFrameOffset },
		Vertex{ bl, normal, vec2(0, 1), vec2(0, 1), deform_scaling, iFrameOffset }
	} );
}

} // namespace

void Landscape::setup()
{
	auto shader = loadShader( "landscape.vs", "landscape.fs" );

	std::vector<Vertex> vertices;

	auto dims = ivec2( 15 );
	auto offset = - vec2(dims - 1) * vec2(0.5f);
	auto max_dist = length(vec2(dims)) * 0.5f;

	for( auto y = 0; y < dims.y; y += 1 ) {
		for( auto x = 0; x < dims.x; x += 1 ) {
			auto pos = offset + vec2(x ,y);
			auto d_norm = floor( glm::length( pos ) ) / max_dist;
			auto time_offset = mix( 0.0f, (float)dims.x / 64.0f, d_norm );

			addRectangle( vertices, vec3( pos.x, -8.0f, pos.y ), 1.0f, 1.0f, time_offset );
		}
	}

	auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW );
	auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} );
	batch = gl::Batch::create( mesh, shader, kVertexMapping );
}

void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uClearTexture", iClearUnit );
	shader->uniform( "uBlurredTexture", iBlurredUnit );
}

void Landscape::draw( float iFrameOffset )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uCurrentFrame", iFrameOffset );

	batch->draw();
}
<commit_msg>Rectangles in terms of quads.<commit_after>//
//  Landscape.cpp
//
//  Created by Soso Limited on 5/26/15.
//
//

#include "Landscape.h"

#include "cinder/Log.h"

using namespace soso;
using namespace cinder;

namespace {

struct alignas(16) Vertex {
	vec3	position;
	vec3	normal;
	vec2	tex_coord;
	vec2	color_tex_coord;
	float deform_scaling;
	float frame_offset;
};

const auto kVertexLayout = ([] {
		auto layout = geom::BufferLayout();
		layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) );
		layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) );
		layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) );
		layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) );
		layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_scaling) );
		layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) );
		return layout;
	} ());

const auto kVertexMapping = ([] {
		return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" } };
	} ());

// Load a shader and handle exceptions. Return nullptr on failure.
gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment )
{
	try {
		auto shader_format = gl::GlslProg::Format()
			.vertex( app::loadAsset( iVertex ) )
			.fragment( app::loadAsset( iFragment ) );

		return gl::GlslProg::create( shader_format );
	}
	catch( ci::Exception &exc ) {
		CI_LOG_E( "Error loading shader: " << exc.what() );
	}

	return nullptr;
}

void addQuad( std::vector<Vertex> &vertices, const vec3 &a, const vec3 &b, const vec3 &c, const vec3 &d, float time_top, float time_bottom )
{
	auto normal = vec3( 0, 1, 0 );
	auto deform_scaling = 0.0f;

	vertices.insert( vertices.end(), {
		Vertex{ a, normal, vec2(0, 0), vec2(0, 0), deform_scaling, time_top },
		Vertex{ b, normal, vec2(1, 0), vec2(1, 0), deform_scaling, time_top },
		Vertex{ c, normal, vec2(1, 1), vec2(1, 1), deform_scaling, time_bottom },

		Vertex{ a, normal, vec2(0, 0), vec2(0, 0), deform_scaling, time_top },
		Vertex{ c, normal, vec2(1, 1), vec2(1, 1), deform_scaling, time_bottom },
		Vertex{ d, normal, vec2(0, 1), vec2(0, 1), deform_scaling, time_bottom }
	} );

}

void addRectangle( std::vector<Vertex> &vertices, const ci::vec3 &iCenter, float iWidth, float iHeight, float iFrameOffset )
{
	auto right = vec3( iWidth / 2.0f, 0, 0 );
	auto left = - right;
	auto down = vec3( 0, 0, iHeight / 2.0f );
	auto up = - down;

	auto ul = iCenter + (left + up);
	auto ur = iCenter + (right + up);
	auto br = iCenter + (right + down);
	auto bl = iCenter + (left + down);
	addQuad( vertices, ul, ur, br, bl, iFrameOffset, iFrameOffset );
}

} // namespace

void Landscape::setup()
{
	auto shader = loadShader( "landscape.vs", "landscape.fs" );

	std::vector<Vertex> vertices;

	auto dims = ivec2( 15 );
	auto offset = - vec2(dims - 1) * vec2(0.5f);
	auto max_dist = length(vec2(dims)) * 0.5f;

	for( auto y = 0; y < dims.y; y += 1 ) {
		for( auto x = 0; x < dims.x; x += 1 ) {
			auto pos = offset + vec2(x ,y);
			auto d_norm = floor( glm::length( pos ) ) / max_dist;
			auto time_offset = mix( 0.0f, (float)dims.x / 64.0f, d_norm );

			addRectangle( vertices, vec3( pos.x, -8.0f, pos.y ), 1.0f, 1.0f, time_offset );
		}
	}

	auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW );
	auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} );
	batch = gl::Batch::create( mesh, shader, kVertexMapping );
}

void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uClearTexture", iClearUnit );
	shader->uniform( "uBlurredTexture", iBlurredUnit );
}

void Landscape::draw( float iFrameOffset )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uCurrentFrame", iFrameOffset );

	batch->draw();
}
<|endoftext|>


<commit_before>#include <osgProducer/Viewer>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osgTerrain/DataSet>

#include <osgGA/NodeTrackerManipulator>

class GraphicsContext {
    public:
        GraphicsContext()
        {
            rs = new Producer::RenderSurface;
            rs->setWindowRectangle(0,0,1,1);
            rs->useBorder(false);
            rs->useConfigEventThread(false);
            rs->realize();
        }

        virtual ~GraphicsContext()
        {
        }

    private:
        Producer::ref_ptr<Producer::RenderSurface> rs;
};

osg::Node* createEarth()
{
    osg::ref_ptr<osg::Node> scene;

    {
        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");

        // make osgTerrain::DataSet quieter..
        osgTerrain::DataSet::setNotifyOffset(1);

        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;

        // register the source imagery
        {
            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);

	    source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));

 	    source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);

            dataSet->addSource(source);
        }

        // set up destination database paramters.
        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
        dataSet->setConvertFromGeographicToGeocentric(true);
        dataSet->setDestinationName("test.osg");

        // load the source data and record sizes.
        dataSet->loadSources();

        GraphicsContext context;
        dataSet->createDestination(30);

        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
        else dataSet->writeDestination();

        scene = dataSet->getDestinationRootNode();
    }

    return scene.release();

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback():
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0)
         {}

    void updateParameters()
    {
        _latitude -= ((2.0*osg::PI)/360.0)/20.0;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrixd matrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
                    }

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrixd::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCullSettings().setNearFarRatio(0.00001f);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osg::ref_ptr<osg::Node> root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {
        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 30000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback;

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);

            unsigned int num = viewer.addCameraManipulator(tm);
            viewer.selectCameraManipulator(num);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }
    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<commit_msg>Added pragma to shut VS 6 up.<commit_after>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgProducer/Viewer>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osgTerrain/DataSet>

#include <osgGA/NodeTrackerManipulator>

class GraphicsContext {
    public:
        GraphicsContext()
        {
            rs = new Producer::RenderSurface;
            rs->setWindowRectangle(0,0,1,1);
            rs->useBorder(false);
            rs->useConfigEventThread(false);
            rs->realize();
        }

        virtual ~GraphicsContext()
        {
        }

    private:
        Producer::ref_ptr<Producer::RenderSurface> rs;
};

osg::Node* createEarth()
{
    osg::ref_ptr<osg::Node> scene;

    {
        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");

        // make osgTerrain::DataSet quieter..
        osgTerrain::DataSet::setNotifyOffset(1);

        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;

        // register the source imagery
        {
            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);

	    source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));

 	    source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);

            dataSet->addSource(source);
        }

        // set up destination database paramters.
        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
        dataSet->setConvertFromGeographicToGeocentric(true);
        dataSet->setDestinationName("test.osg");

        // load the source data and record sizes.
        dataSet->loadSources();

        GraphicsContext context;
        dataSet->createDestination(30);

        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
        else dataSet->writeDestination();

        scene = dataSet->getDestinationRootNode();
    }

    return scene.release();

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback():
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0)
         {}

    void updateParameters()
    {
        _latitude -= ((2.0*osg::PI)/360.0)/20.0;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrixd matrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
                    }

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrixd::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCullSettings().setNearFarRatio(0.00001f);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osg::ref_ptr<osg::Node> root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {
        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 30000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback;

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);

            unsigned int num = viewer.addCameraManipulator(tm);
            viewer.selectCameraManipulator(num);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }
    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<|endoftext|>


<commit_before>#include "SymbolFactory.h"
#include "SymbolFile.h"

#include "GUM_ImageSymbol.h"
#include "ImageSymLoader.h"
#include "ProxyImage.h"
#include "Scale9SymLoader.h"
#include "IconSymLoader.h"
#include "TextureSymLoader.h"
#include "GUM_TextboxSymbol.h"
#include "TextboxLoader.h"
#include "ComplexSymLoader.h"
#include "AnimSymLoader.h"
#include "Anim2SymLoader.h"
#include "P3dSymLoader.h"
#include "P2dSymLoader.h"
#include "ShapeSymLoader.h"
#include "MeshSymLoader.h"
#include "MaskSymLoader.h"
#include "TrailSymLoader.h"
#include "SkeletonSymLoader.h"

#include <simp/NodeFactory.h>
#include <simp/simp_types.h>
#include <simp/NodePicture.h>
#include <timp/PkgMgr.h>
#include <timp/TIMP_Package.h>

#include <sprite2/AnchorSymbol.h>
#include <sprite2/Scale9Symbol.h>
#include <sprite2/IconSymbol.h>
#include <sprite2/TextureSymbol.h>
#include <sprite2/ComplexSymbol.h>
#include <sprite2/AnimSymbol.h>
#include <sprite2/Anim2Symbol.h>
#include <sprite2/Particle3dSymbol.h>
#include <sprite2/Particle2dSymbol.h>
#include <sprite2/ShapeSymbol.h>
#include <sprite2/MeshSymbol.h>
#include <sprite2/MaskSymbol.h>
#include <sprite2/TrailSymbol.h>
#include <sprite2/SkeletonSymbol.h>
#include <sprite2/SymType.h>
#include <sprite2/CacheMatVisitor.h>

#include <fstream>

#include <assert.h>

namespace gum
{

SINGLETON_DEFINITION(SymbolFactory);

SymbolFactory::SymbolFactory()
	: m_anchor_sym(NULL)
{
}

s2::Symbol* SymbolFactory::Create(const std::string& filepath, bool flatten, int type) const
{
	s2::Symbol* ret = NULL;

	if (type == s2::SYM_UNKNOWN) {
		type = SymbolFile::Instance()->Type(filepath);
	}
	switch (type)
	{
	case s2::SYM_IMAGE:
		{
			ImageSymbol* sym = new ImageSymbol;
			ImageSymLoader loader(sym);
			loader.Load(filepath, false);
			ret = sym;
		}
		break;
	case s2::SYM_SCALE9:
		{
			s2::Scale9Symbol* sym = new s2::Scale9Symbol();
			Scale9SymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_ICON:
		{
			s2::IconSymbol* sym = new s2::IconSymbol();
			IconSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_TEXTURE:
		{
			s2::TextureSymbol* sym = new s2::TextureSymbol;
			TextureSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_TEXTBOX:
		{
			TextboxSymbol* sym = new TextboxSymbol();
			TextboxLoader loader(sym->GetTextbox());
			Json::Value val;
			Json::Reader reader;
			std::locale::global(std::locale(""));
			std::ifstream fin(filepath.c_str());
			std::locale::global(std::locale("C"));
			reader.parse(fin, val);
			fin.close();
			loader.LoadJson(val);
			ret = sym;
		}
		break;
	case s2::SYM_COMPLEX:
		{
			s2::ComplexSymbol* sym = new s2::ComplexSymbol();
			ComplexSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_ANIMATION:
		{
			s2::AnimSymbol* sym = new s2::AnimSymbol();
			AnimSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_ANIM2:
		{
			s2::Anim2Symbol* sym = new s2::Anim2Symbol;
			Anim2SymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_PARTICLE3D:
		{
			s2::Particle3dSymbol* sym = new s2::Particle3dSymbol;
			P3dSymLoader loader(flatten);
			loader.LoadJson(filepath);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case s2::SYM_PARTICLE2D:
		{
			s2::Particle2dSymbol* sym = new s2::Particle2dSymbol;
			P2dSymLoader loader(flatten);
			loader.LoadJson(filepath);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case s2::SYM_SHAPE:
		{
			s2::ShapeSymbol* sym = new s2::ShapeSymbol;
			ShapeSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_MASK:
		{
			s2::MaskSymbol* sym = new s2::MaskSymbol;
			MaskSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_TRAIL:
		{
			s2::TrailSymbol* sym = new s2::TrailSymbol;
			TrailSymLoader loader(flatten);
			loader.LoadJson(filepath);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case s2::SYM_SKELETON:
		{
			s2::SkeletonSymbol* sym = new s2::SkeletonSymbol;
			SkeletonSymLoader loader(sym);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	default:
		assert(0);
	}

	return ret;
}

s2::Symbol* SymbolFactory::Create(uint32_t id, bool flatten) const
{
	if (id == 0xffffffff) {
		if (!m_anchor_sym) {
			m_anchor_sym = new s2::AnchorSymbol();
		}
		return m_anchor_sym;
	}

	s2::Symbol* ret = NULL;

	int type;
	const void* data = simp::NodeFactory::Instance()->Create(id, &type);
	if(!data) {
		return NULL;
	}
	switch (type)
	{
	case simp::TYPE_IMAGE:
		{
			const simp::NodePicture* pic = (const simp::NodePicture*)data;
			sm::vec2 offset(pic->offx * 0.5f, pic->offy * 0.5f);
			ImageSymbol* sym = NULL;
			if (pic->texid < simp::NodePicture::MAX_IN_PKG)
			{
				int pkg_id = simp::NodeID::GetPkgID(id);
				const timp::Package* pkg = timp::PkgMgr::Instance()->Query(pkg_id);
				std::string filepath = pkg->GetTexPath(pic->texid, 0);

				sym = new ImageSymbol(id);
				ImageSymLoader loader(sym);

				bool async = true;
				loader.Load(filepath, async);
				const timp::Package::TextureDesc& tex = pkg->GetTexDesc(pic->texid);
				Image* img = const_cast<Image*>(sym->GetImage());
				if (img && async) {
					img->AsyncLoad(tex.type, tex.w, tex.h);
				}

				sym->SetRegion(
					sm::ivec2(pic->region[0], pic->region[1]),
					sm::ivec2(pic->region[2], pic->region[3]),
					offset,
					pic->lod);
			}
			else
			{
				std::string filepath = ProxyImage::GetFilepath(pic->texid - simp::NodePicture::MAX_IN_PKG);
				Image* img = ImageMgr::Instance()->Query(filepath);
				assert(img);

				sym = new ImageSymbol(id);
				sym->SetImage(img);
				sym->SetRegion(
					sm::ivec2(pic->region[0], pic->region[1]),
					sm::ivec2(pic->region[2], pic->region[3]),
					offset,
					pic->lod);
			}
			ret = sym;
		}
		break;
	case simp::TYPE_SCALE9:
		{
			s2::Scale9Symbol* sym = new s2::Scale9Symbol(id);
			Scale9SymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeScale9*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_ICON:
		{
			s2::IconSymbol* sym = new s2::IconSymbol(id);
			IconSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeIcon*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_TEXTURE:
		{
			s2::TextureSymbol* sym = new s2::TextureSymbol(id);
			TextureSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeTexture*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_LABEL:
		{
			TextboxSymbol* sym = new TextboxSymbol(id);
			TextboxLoader loader(sym->GetTextbox());
			loader.LoadBin((const simp::NodeLabel*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_COMPLEX:
		{
			s2::ComplexSymbol* sym = new s2::ComplexSymbol(id);
			ComplexSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeComplex*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_ANIMATION:
		{
			s2::AnimSymbol* sym = new s2::AnimSymbol(id);
			AnimSymLoader loader(sym, flatten, NULL, NULL);
			loader.LoadBin((const simp::NodeAnimation*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_ANIM2:
		{
			s2::Anim2Symbol* sym = new s2::Anim2Symbol(id);
			Anim2SymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeAnim2*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_PARTICLE3D:
		{
			s2::Particle3dSymbol* sym = new s2::Particle3dSymbol(id);
			P3dSymLoader loader(flatten);
			loader.LoadBin((const simp::NodeParticle3d*)data);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case simp::TYPE_PARTICLE2D:
		{
			s2::Particle2dSymbol* sym = new s2::Particle2dSymbol(id);
			P2dSymLoader loader(flatten);
			loader.LoadBin((const simp::NodeParticle2d*)data);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case simp::TYPE_SHAPE:
		{
			s2::ShapeSymbol* sym = new s2::ShapeSymbol(id);
			ShapeSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeShape*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_MESH:
		{
			s2::MeshSymbol* sym = new s2::MeshSymbol(id);
			MeshSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeMesh*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_MASK:
		{
			s2::MaskSymbol* sym = new s2::MaskSymbol(id);
			MaskSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeMask*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_TRAIL:
		{
			s2::TrailSymbol* sym = new s2::TrailSymbol(id);
			TrailSymLoader loader(flatten);
			loader.LoadBin((const simp::NodeTrail*)data);
			loader.Store(sym);
			ret = sym;
		}
		break;
	default:
		assert(0);
	}

#ifdef S2_SPR_CACHE_LOCAL_MAT_SHARE
 	if (ret && type != simp::TYPE_SCALE9 && type != simp::TYPE_ANIMATION) {
 		ret->Traverse(s2::CacheMatVisitor());
 	}
#endif // S2_SPR_CACHE_LOCAL_MAT_SHARE

	return ret;
}

s2::Symbol* SymbolFactory::Create(const std::string& pkg_name, const std::string& node_name, bool flatten) const
{
	uint32_t id = simp::NodeFactory::Instance()->GetNodeID(pkg_name, node_name);
	if (id != 0xffffffff) {
		return Create(id, flatten);
	} else {
		return NULL;
	}
}

}<commit_msg>add mesh sym create<commit_after>#include "SymbolFactory.h"
#include "SymbolFile.h"

#include "GUM_ImageSymbol.h"
#include "ImageSymLoader.h"
#include "ProxyImage.h"
#include "Scale9SymLoader.h"
#include "IconSymLoader.h"
#include "TextureSymLoader.h"
#include "GUM_TextboxSymbol.h"
#include "TextboxLoader.h"
#include "ComplexSymLoader.h"
#include "AnimSymLoader.h"
#include "Anim2SymLoader.h"
#include "P3dSymLoader.h"
#include "P2dSymLoader.h"
#include "ShapeSymLoader.h"
#include "MeshSymLoader.h"
#include "MaskSymLoader.h"
#include "TrailSymLoader.h"
#include "SkeletonSymLoader.h"

#include <simp/NodeFactory.h>
#include <simp/simp_types.h>
#include <simp/NodePicture.h>
#include <timp/PkgMgr.h>
#include <timp/TIMP_Package.h>

#include <sprite2/AnchorSymbol.h>
#include <sprite2/Scale9Symbol.h>
#include <sprite2/IconSymbol.h>
#include <sprite2/TextureSymbol.h>
#include <sprite2/ComplexSymbol.h>
#include <sprite2/AnimSymbol.h>
#include <sprite2/Anim2Symbol.h>
#include <sprite2/Particle3dSymbol.h>
#include <sprite2/Particle2dSymbol.h>
#include <sprite2/ShapeSymbol.h>
#include <sprite2/MeshSymbol.h>
#include <sprite2/MaskSymbol.h>
#include <sprite2/TrailSymbol.h>
#include <sprite2/SkeletonSymbol.h>
#include <sprite2/SymType.h>
#include <sprite2/CacheMatVisitor.h>

#include <fstream>

#include <assert.h>

namespace gum
{

SINGLETON_DEFINITION(SymbolFactory);

SymbolFactory::SymbolFactory()
	: m_anchor_sym(NULL)
{
}

s2::Symbol* SymbolFactory::Create(const std::string& filepath, bool flatten, int type) const
{
	s2::Symbol* ret = NULL;

	if (type == s2::SYM_UNKNOWN) {
		type = SymbolFile::Instance()->Type(filepath);
	}
	switch (type)
	{
	case s2::SYM_IMAGE:
		{
			ImageSymbol* sym = new ImageSymbol;
			ImageSymLoader loader(sym);
			loader.Load(filepath, false);
			ret = sym;
		}
		break;
	case s2::SYM_SCALE9:
		{
			s2::Scale9Symbol* sym = new s2::Scale9Symbol();
			Scale9SymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_ICON:
		{
			s2::IconSymbol* sym = new s2::IconSymbol();
			IconSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_TEXTURE:
		{
			s2::TextureSymbol* sym = new s2::TextureSymbol;
			TextureSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_TEXTBOX:
		{
			TextboxSymbol* sym = new TextboxSymbol();
			TextboxLoader loader(sym->GetTextbox());
			Json::Value val;
			Json::Reader reader;
			std::locale::global(std::locale(""));
			std::ifstream fin(filepath.c_str());
			std::locale::global(std::locale("C"));
			reader.parse(fin, val);
			fin.close();
			loader.LoadJson(val);
			ret = sym;
		}
		break;
	case s2::SYM_COMPLEX:
		{
			s2::ComplexSymbol* sym = new s2::ComplexSymbol();
			ComplexSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_ANIMATION:
		{
			s2::AnimSymbol* sym = new s2::AnimSymbol();
			AnimSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_ANIM2:
		{
			s2::Anim2Symbol* sym = new s2::Anim2Symbol;
			Anim2SymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_PARTICLE3D:
		{
			s2::Particle3dSymbol* sym = new s2::Particle3dSymbol;
			P3dSymLoader loader(flatten);
			loader.LoadJson(filepath);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case s2::SYM_PARTICLE2D:
		{
			s2::Particle2dSymbol* sym = new s2::Particle2dSymbol;
			P2dSymLoader loader(flatten);
			loader.LoadJson(filepath);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case s2::SYM_SHAPE:
		{
			s2::ShapeSymbol* sym = new s2::ShapeSymbol;
			ShapeSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_MESH:
		{
			s2::MeshSymbol* sym = new s2::MeshSymbol;
			MeshSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_MASK:
		{
			s2::MaskSymbol* sym = new s2::MaskSymbol;
			MaskSymLoader loader(sym, flatten);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	case s2::SYM_TRAIL:
		{
			s2::TrailSymbol* sym = new s2::TrailSymbol;
			TrailSymLoader loader(flatten);
			loader.LoadJson(filepath);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case s2::SYM_SKELETON:
		{
			s2::SkeletonSymbol* sym = new s2::SkeletonSymbol;
			SkeletonSymLoader loader(sym);
			loader.LoadJson(filepath);
			ret = sym;
		}
		break;
	default:
		assert(0);
	}

	return ret;
}

s2::Symbol* SymbolFactory::Create(uint32_t id, bool flatten) const
{
	if (id == 0xffffffff) {
		if (!m_anchor_sym) {
			m_anchor_sym = new s2::AnchorSymbol();
		}
		return m_anchor_sym;
	}

	s2::Symbol* ret = NULL;

	int type;
	const void* data = simp::NodeFactory::Instance()->Create(id, &type);
	if(!data) {
		return NULL;
	}
	switch (type)
	{
	case simp::TYPE_IMAGE:
		{
			const simp::NodePicture* pic = (const simp::NodePicture*)data;
			sm::vec2 offset(pic->offx * 0.5f, pic->offy * 0.5f);
			ImageSymbol* sym = NULL;
			if (pic->texid < simp::NodePicture::MAX_IN_PKG)
			{
				int pkg_id = simp::NodeID::GetPkgID(id);
				const timp::Package* pkg = timp::PkgMgr::Instance()->Query(pkg_id);
				std::string filepath = pkg->GetTexPath(pic->texid, 0);

				sym = new ImageSymbol(id);
				ImageSymLoader loader(sym);

				bool async = true;
				loader.Load(filepath, async);
				const timp::Package::TextureDesc& tex = pkg->GetTexDesc(pic->texid);
				Image* img = const_cast<Image*>(sym->GetImage());
				if (img && async) {
					img->AsyncLoad(tex.type, tex.w, tex.h);
				}

				sym->SetRegion(
					sm::ivec2(pic->region[0], pic->region[1]),
					sm::ivec2(pic->region[2], pic->region[3]),
					offset,
					pic->lod);
			}
			else
			{
				std::string filepath = ProxyImage::GetFilepath(pic->texid - simp::NodePicture::MAX_IN_PKG);
				Image* img = ImageMgr::Instance()->Query(filepath);
				assert(img);

				sym = new ImageSymbol(id);
				sym->SetImage(img);
				sym->SetRegion(
					sm::ivec2(pic->region[0], pic->region[1]),
					sm::ivec2(pic->region[2], pic->region[3]),
					offset,
					pic->lod);
			}
			ret = sym;
		}
		break;
	case simp::TYPE_SCALE9:
		{
			s2::Scale9Symbol* sym = new s2::Scale9Symbol(id);
			Scale9SymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeScale9*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_ICON:
		{
			s2::IconSymbol* sym = new s2::IconSymbol(id);
			IconSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeIcon*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_TEXTURE:
		{
			s2::TextureSymbol* sym = new s2::TextureSymbol(id);
			TextureSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeTexture*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_LABEL:
		{
			TextboxSymbol* sym = new TextboxSymbol(id);
			TextboxLoader loader(sym->GetTextbox());
			loader.LoadBin((const simp::NodeLabel*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_COMPLEX:
		{
			s2::ComplexSymbol* sym = new s2::ComplexSymbol(id);
			ComplexSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeComplex*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_ANIMATION:
		{
			s2::AnimSymbol* sym = new s2::AnimSymbol(id);
			AnimSymLoader loader(sym, flatten, NULL, NULL);
			loader.LoadBin((const simp::NodeAnimation*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_ANIM2:
		{
			s2::Anim2Symbol* sym = new s2::Anim2Symbol(id);
			Anim2SymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeAnim2*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_PARTICLE3D:
		{
			s2::Particle3dSymbol* sym = new s2::Particle3dSymbol(id);
			P3dSymLoader loader(flatten);
			loader.LoadBin((const simp::NodeParticle3d*)data);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case simp::TYPE_PARTICLE2D:
		{
			s2::Particle2dSymbol* sym = new s2::Particle2dSymbol(id);
			P2dSymLoader loader(flatten);
			loader.LoadBin((const simp::NodeParticle2d*)data);
			loader.Store(sym);
			ret = sym;
		}
		break;
	case simp::TYPE_SHAPE:
		{
			s2::ShapeSymbol* sym = new s2::ShapeSymbol(id);
			ShapeSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeShape*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_MESH:
		{
			s2::MeshSymbol* sym = new s2::MeshSymbol(id);
			MeshSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeMesh*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_MASK:
		{
			s2::MaskSymbol* sym = new s2::MaskSymbol(id);
			MaskSymLoader loader(sym, flatten);
			loader.LoadBin((const simp::NodeMask*)data);
			ret = sym;
		}
		break;
	case simp::TYPE_TRAIL:
		{
			s2::TrailSymbol* sym = new s2::TrailSymbol(id);
			TrailSymLoader loader(flatten);
			loader.LoadBin((const simp::NodeTrail*)data);
			loader.Store(sym);
			ret = sym;
		}
		break;
	default:
		assert(0);
	}

#ifdef S2_SPR_CACHE_LOCAL_MAT_SHARE
 	if (ret && type != simp::TYPE_SCALE9 && type != simp::TYPE_ANIMATION) {
 		ret->Traverse(s2::CacheMatVisitor());
 	}
#endif // S2_SPR_CACHE_LOCAL_MAT_SHARE

	return ret;
}

s2::Symbol* SymbolFactory::Create(const std::string& pkg_name, const std::string& node_name, bool flatten) const
{
	uint32_t id = simp::NodeFactory::Instance()->GetNodeID(pkg_name, node_name);
	if (id != 0xffffffff) {
		return Create(id, flatten);
	} else {
		return NULL;
	}
}

}<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <time.h>

#include "../Neural_Networks.h"

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **target_output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	int batch_size		= 60;
	int number_iterations = 50;
	int number_threads;
	int number_training	= 60000;
	int number_test		= 10000;

	float **input = new float*[number_training + number_test];
	float **target_output = new float*[number_training + number_test];

	double epsilon		 = 0.001;
	double learning_rate = 0.005;
	double decay_rate	 = 0.977;

	string path;

	vector<int> number_nodes = { 784, 10 };

	vector<Layer*> layer;

	// train from scratch *****************
	Neural_Networks NN = Neural_Networks();

	layer.push_back(NN.Add(new Layer("MNIST",	1, 28, 28)));
	layer.push_back(NN.Add(new Layer("BN,ReLU", 24, 24, 24)));	// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("",		24, 12, 12)));
	layer.push_back(NN.Add(new Layer("BN,ReLU", 24, 8, 8)));	// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("BN,ReLU", 48, 8, 8)));	// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("",		48, 4, 4)));
	layer.push_back(NN.Add(new Layer("BN,ReLU", 192)));			// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("CE,softmax", 10)));		// cross-entropy loss, softmax activation

	layer[1]->Connect(layer[0], "W");		// 5x5 convolution
	layer[2]->Connect(layer[1], "P,max");	// 2x2 max pooling
	layer[3]->Connect(layer[2], "W,DS");	// 5x5 depthwise separable convolution
	layer[4]->Connect(layer[3], "W");		// 1x1 convolution
	layer[5]->Connect(layer[4], "P,max");	// 2x2 max pooling
	layer[6]->Connect(layer[5], "W");		// fully connected
	layer[7]->Connect(layer[6], "W");		// fully connected

	srand(0); NN.Initialize(0.01);
	// ************************************

	// or load pretrained model
	// Neural_Networks NN = Neural_Networks("MNIST_CNN.txt");

	cout << "The number of threads : ";
	cin >> number_threads;
	cin.ignore();

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		input[h] = new float[number_nodes.front()];
		target_output[h] = new float[number_nodes.back()];
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output);

	omp_set_num_threads(number_threads);

	for (int g = 0, time = clock(); g < number_iterations; g++) {
		int score[2] = { 0, };

		float **output = new float*[batch_size];

		double loss = NN.Train(batch_size, number_training, input, target_output, learning_rate, epsilon);

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[number_nodes.back()];
		}
		for (int i = 0, h = 0; i < number_training + number_test; i++) {
			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Test(h, &input[i - h + 1], output);

				for (int g = 0, argmax; g < h; g++) {
					double max = 0;

					for (int j = 0; j < number_nodes.back(); j++) {
						if (max < output[g][j]) {
							max = output[g][argmax = j];
						}
					}
					score[(i - h + g + 1 < number_training) ? (0) : (1)] += (int)target_output[i - h + g + 1][argmax];
				}
				h = 0;
			}
		}
		printf("."); NN.Save("NN.txt");

		printf("score: %d / %d, %d / %d  loss: %lf  step %d  %.2lf sec\n", score[0], number_training, score[1], number_test, loss, g + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
		learning_rate *= decay_rate;

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] output;
	}

	for (int h = 0; h < number_training + number_test; h++) {
		delete[] input[h];
		delete[] target_output[h];
	}
	delete[] input;
	delete[] target_output;

	return 0;
}
<commit_msg>Update MNIST_CNN.cpp<commit_after>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <time.h>

#include "../Neural_Networks.h"

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **target_output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	int batch_size		= 60;
	int number_iterations = 50;
	int number_threads;
	int number_training	= 60000;
	int number_test		= 10000;

	float **input = new float*[number_training + number_test];
	float **target_output = new float*[number_training + number_test];

	double learning_rate = 0.005;
	double decay_rate	 = 0.977;

	string path;

	vector<int> number_nodes = { 784, 10 };

	vector<Layer*> layer;

	// train from scratch *****************
	Neural_Networks NN = Neural_Networks();

	layer.push_back(NN.Add(new Layer("MNIST",	1, 28, 28)));
	layer.push_back(NN.Add(new Layer("BN,ReLU", 24, 24, 24)));	// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("",		24, 12, 12)));
	layer.push_back(NN.Add(new Layer("BN,ReLU", 24, 8, 8)));	// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("BN,ReLU", 48, 8, 8)));	// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("",		48, 4, 4)));
	layer.push_back(NN.Add(new Layer("BN,ReLU", 192)));			// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("CE,softmax", 10)));		// cross-entropy loss, softmax activation

	layer[1]->Connect(layer[0], "W");		// 5x5 convolution
	layer[2]->Connect(layer[1], "P,max");	// 2x2 max pooling
	layer[3]->Connect(layer[2], "W,DS");	// 5x5 depthwise separable convolution
	layer[4]->Connect(layer[3], "W");		// 1x1 convolution
	layer[5]->Connect(layer[4], "P,max");	// 2x2 max pooling
	layer[6]->Connect(layer[5], "W");		// fully connected
	layer[7]->Connect(layer[6], "W");		// fully connected

	srand(0); NN.Initialize(0.01);
	// ************************************

	// or load pretrained model
	// Neural_Networks NN = Neural_Networks("MNIST_CNN.txt");

	cout << "The number of threads : ";
	cin >> number_threads;
	cin.ignore();

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		input[h] = new float[number_nodes.front()];
		target_output[h] = new float[number_nodes.back()];
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output);

	omp_set_num_threads(number_threads);

	for (int g = 0, time = clock(); g < number_iterations; g++) {
		int score[2] = { 0, };

		float **output = new float*[batch_size];

		double loss = NN.Train(batch_size, number_training, input, target_output, learning_rate);

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[number_nodes.back()];
		}
		for (int i = 0, h = 0; i < number_training + number_test; i++) {
			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Test(h, &input[i - h + 1], output);

				for (int g = 0, argmax; g < h; g++) {
					double max = 0;

					for (int j = 0; j < number_nodes.back(); j++) {
						if (max < output[g][j]) {
							max = output[g][argmax = j];
						}
					}
					score[(i - h + g + 1 < number_training) ? (0) : (1)] += (int)target_output[i - h + g + 1][argmax];
				}
				h = 0;
			}
		}
		printf("."); NN.Save("NN.txt");

		printf("score: %d / %d, %d / %d  loss: %lf  step %d  %.2lf sec\n", score[0], number_training, score[1], number_test, loss, g + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
		learning_rate *= decay_rate;

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] output;
	}

	for (int h = 0; h < number_training + number_test; h++) {
		delete[] input[h];
		delete[] target_output[h];
	}
	delete[] input;
	delete[] target_output;

	return 0;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#pragma comment(lib, "netapi32.lib")

#define _WIN32_DCOM
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
// clang-format off
#include <LM.h>
// clang-format on
#include <Shlobj.h>

#include <osquery/core.h>
#include <osquery/tables.h>
#include <osquery/logger.h>

#include "osquery/core/windows/wmi.h"

namespace osquery {
namespace tables {

QueryData genUsers(QueryContext& context) {
  QueryData results;

  // USER_INFO_3 conains generic user information
  LPUSER_INFO_3 pUserBuffer = nullptr;
  DWORD dwGenericUserLevel = 3;
  DWORD dwPreferredMaxLength = MAX_PREFERRED_LENGTH;
  DWORD dwEntriesRead = 0;
  DWORD dwTotalEntries = 0;
  DWORD dwResumeHandle = 0;
  NET_API_STATUS nEnumStatus;

  nEnumStatus = NetUserEnum(nullptr,
                            dwGenericUserLevel,
                            FILTER_NORMAL_ACCOUNT,
                            (LPBYTE*)&pUserBuffer,
                            dwPreferredMaxLength,
                            &dwEntriesRead,
                            &dwTotalEntries,
                            &dwResumeHandle);

  // We save the original pointer to the USER_INFO_3 buff for mem management
  LPUSER_INFO_3 pUserIterationBuffer = pUserBuffer;
  if (pUserIterationBuffer == nullptr || nEnumStatus != NERR_Success) {
    if (pUserBuffer != nullptr) {
      NetApiBufferFree(pUserBuffer);
    }
    return results;
  }

  for (DWORD i = 0; i < dwEntriesRead; i++) {
    Row r;
    r["username"] = wstringToString(pUserIterationBuffer->usri3_name);
    r["description"] = wstringToString(pUserIterationBuffer->usri3_comment);
    r["uid"] = BIGINT(pUserIterationBuffer->usri3_user_id);
    r["gid"] = BIGINT(pUserIterationBuffer->usri3_primary_group_id);
    r["uid_signed"] = r["uid"];
    r["gid_signed"] = r["gid"];
    r["shell"] = "C:\\Windows\\system32\\cmd.exe";

    // USER_INFO_23 contains detailed info, like the user Sid
    DWORD dwDetailedUserLevel = 23;
    LPUSER_INFO_23 pSidUserBuffer = nullptr;
    NET_API_STATUS nStatus;
    nStatus = NetUserGetInfo(nullptr,
                             pUserIterationBuffer->usri3_name,
                             dwDetailedUserLevel,
                             (LPBYTE*)&pSidUserBuffer);
    if (nStatus != NERR_Success) {
      if (pSidUserBuffer != nullptr) {
        NetApiBufferFree(pSidUserBuffer);
        pSidUserBuffer = nullptr;
      }
      continue;
    }

    LPTSTR sStringSid = nullptr;
    auto ret =
        ConvertSidToStringSid(pSidUserBuffer->usri23_user_sid, &sStringSid);
    if (ret == 0) {
      if (pSidUserBuffer != nullptr) {
        NetApiBufferFree(pSidUserBuffer);
      }
      continue;
    }
    r["uuid"] = sStringSid;
    std::string query = "SELECT LocalPath FROM Win32_UserProfile where SID=\"" +
                        std::string(sStringSid) + "\"";
    WmiRequest wmiRequest(query);
    std::vector<WmiResultItem>& wmiResults = wmiRequest.results();
    if (wmiResults.size() != 0) {
      wmiResults[0].GetString("LocalPath", r["directory"]);
    }
    LocalFree(sStringSid);
    NetApiBufferFree(pSidUserBuffer);

    results.push_back(r);
    pUserIterationBuffer++;
  }
  NetApiBufferFree(pUserBuffer);

  if (nEnumStatus == ERROR_MORE_DATA) {
    LOG(WARNING)
        << "NetUserEnum contains more data: users table may be incomplete";
  }

  return results;
}
}
}
<commit_msg>[Fix #2733] Updated users table to parse all user profiles (#2737)<commit_after>/*
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#define _WIN32_DCOM
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
// clang-format off
#include <LM.h>
// clang-format on

#include <osquery/core.h>
#include <osquery/tables.h>
#include <osquery/logger.h>

#include "osquery/core/windows/wmi.h"
#include "osquery/core/conversions.h"

namespace osquery {
namespace tables {

QueryData genUsers(QueryContext& context) {
  QueryData results;

  WmiRequest req("select * from Win32_UserProfile");
  if (!req.getStatus().ok()) {
    return results;
  }

  auto& wmiResults = req.results();
  for (const auto& res : wmiResults) {
    Row r;

    std::string sidString;
    res.GetString("LocalPath", r["directory"]);
    res.GetString("SID", sidString);
    r["uuid"] = sidString;

    PSID sid;
    auto ret = ConvertStringSidToSidA(sidString.c_str(), &sid);
    if (ret == 0) {
      TLOG << "Convert SID to string failed with: " << GetLastError();
    }

    wchar_t accntName[UNLEN] = {0};
    wchar_t domName[DNLEN] = {0};
    unsigned long accntNameLen = UNLEN;
    unsigned long domNameLen = DNLEN;
    SID_NAME_USE eUse;

    /// MSDN guaruntees the string values returned is null terminated.
    ret = LookupAccountSidW(
        nullptr, sid, accntName, &accntNameLen, domName, &domNameLen, &eUse);
    if (ret != 0) {
      r["username"] = wstringToString(accntName);
    } else {
      TLOG << "Lookup Account by SID failed with: " << GetLastError();
    }

    /// USER_INFO_3 contains detailed info, like the uid
    unsigned long dwDetailedUserLevel = 3;
    LPUSER_INFO_3 pUserInfoBuffer = nullptr;

    NET_API_STATUS nStatus;
    nStatus = NetUserGetInfo(nullptr,
                             accntName,
                             dwDetailedUserLevel,
                             reinterpret_cast<LPBYTE*>(&pUserInfoBuffer));

    if (nStatus == NERR_Success) {
      r["uid"] = INTEGER(pUserInfoBuffer->usri3_user_id);
      r["uid_signed"] = INTEGER(pUserInfoBuffer->usri3_user_id);
      r["gid"] = INTEGER(pUserInfoBuffer->usri3_primary_group_id);
      r["gid_signed"] = INTEGER(pUserInfoBuffer->usri3_primary_group_id);
      r["description"] =
          SQL_TEXT(wstringToString(pUserInfoBuffer->usri3_comment));
    } else {
      /// If NetUserGetInfo fails parse the uid manually
      auto sidTokens = osquery::split(sidString, "-");
      if (sidTokens.size() == 8) {
        r["uid"] = INTEGER(sidTokens.back());
        r["uid_signed"] = INTEGER(sidTokens.back());
      }
    }

    /// Note: there may be a way to get the users prefered shell
    r["shell"] = "C:\\Windows\\system32\\cmd.exe";
    results.push_back(r);

    if (pUserInfoBuffer != nullptr) {
      NetApiBufferFree(pUserInfoBuffer);
      pUserInfoBuffer = nullptr;
    }
  }
  return results;
}
}
}
<|endoftext|>