<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef FEATURE_FACTORY_HPP
#define FEATURE_FACTORY_HPP

#include <mapnik/feature.hpp>

namespace mapnik
{
struct feature_factory
{
    static Feature* create (int fid)
    {
        return new Feature(fid);
    }
};
}

#endif //FEATURE_FACTORY_HPP
<commit_msg>+ use boost::make_shared to improve shared_ptr   allocation locality<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef FEATURE_FACTORY_HPP
#define FEATURE_FACTORY_HPP

#include <mapnik/feature.hpp>
#include <boost/make_shared.hpp>
//#include <boost/pool/pool_alloc.hpp>

namespace mapnik
{
struct feature_factory
{
    static boost::shared_ptr<Feature> create (int fid)
    {
        //return boost::allocate_shared<Feature>(boost::pool_allocator<Feature>(),fid);
        //return boost::allocate_shared<Feature>(boost::fast_pool_allocator<Feature>(),fid);
        return boost::make_shared<Feature>(fid);
    }

};
}

#endif //FEATURE_FACTORY_HPP
<|endoftext|>


<commit_before>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>

#pragma once

#include <string>
#include <functional>

#include <boost/config.hpp>

#include <windows.h>
#include <tlhelp32.h>

namespace hadesmem
{

class Process;

#if defined(HADESMEM_GCC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)

class Module
{
public:
  Module(Process const& process, HMODULE handle);

  Module(Process const& process, std::wstring const& path);

  Module(Process const& process, MODULEENTRY32 const& entry);

  HMODULE GetHandle() const BOOST_NOEXCEPT;

  DWORD GetSize() const BOOST_NOEXCEPT;

  std::wstring GetName() const BOOST_NOEXCEPT;

  std::wstring GetPath() const BOOST_NOEXCEPT;

  FARPROC FindProcedure(std::string const& Name) const;

  FARPROC FindProcedure(WORD Ordinal) const;

  bool operator==(Module const& other) const BOOST_NOEXCEPT;

  bool operator!=(Module const& other) const BOOST_NOEXCEPT;

  bool operator<(Module const& other) const BOOST_NOEXCEPT;

  bool operator<=(Module const& other) const BOOST_NOEXCEPT;

  bool operator>(Module const& other) const BOOST_NOEXCEPT;

  bool operator>=(Module const& other) const BOOST_NOEXCEPT;

private:
  void Initialize(HMODULE handle);

  void Initialize(std::wstring const& path);

  void Initialize(MODULEENTRY32 const& entry);

  void InitializeIf(std::function<bool (MODULEENTRY32 const&)> const& check_func);

  FARPROC FindProcedureInternal(LPCSTR name) const;

  Process const* process_;
  HMODULE handle_;
  DWORD size_;
  std::wstring name_;
  std::wstring path_;
};

#if defined(HADESMEM_GCC)
#pragma GCC diagnostic pop
#endif // #if defined(HADESMEM_GCC)

}
<commit_msg>* [module] Explained warning being suppressed.<commit_after>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>

#pragma once

#include <string>
#include <functional>

#include <boost/config.hpp>

#include <windows.h>
#include <tlhelp32.h>

namespace hadesmem
{

class Process;

// hadesmem::Module causes the following warning under GCC:
// error: 'class hadesmem::Module' has pointer data members
// but does not override 'hadesmem::Module(const hadesmem::Module&)'
// or 'operator=(const hadesmem::Module&)' [-Werror=effc++]
// This can be ignored because the pointer data members are non-owning
// and shared pointers.
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)

class Module
{
public:
  Module(Process const& process, HMODULE handle);

  Module(Process const& process, std::wstring const& path);

  Module(Process const& process, MODULEENTRY32 const& entry);

  HMODULE GetHandle() const BOOST_NOEXCEPT;

  DWORD GetSize() const BOOST_NOEXCEPT;

  std::wstring GetName() const BOOST_NOEXCEPT;

  std::wstring GetPath() const BOOST_NOEXCEPT;

  FARPROC FindProcedure(std::string const& Name) const;

  FARPROC FindProcedure(WORD Ordinal) const;

  bool operator==(Module const& other) const BOOST_NOEXCEPT;

  bool operator!=(Module const& other) const BOOST_NOEXCEPT;

  bool operator<(Module const& other) const BOOST_NOEXCEPT;

  bool operator<=(Module const& other) const BOOST_NOEXCEPT;

  bool operator>(Module const& other) const BOOST_NOEXCEPT;

  bool operator>=(Module const& other) const BOOST_NOEXCEPT;

private:
  void Initialize(HMODULE handle);

  void Initialize(std::wstring const& path);

  void Initialize(MODULEENTRY32 const& entry);

  void InitializeIf(std::function<bool (MODULEENTRY32 const&)> const& check_func);

  FARPROC FindProcedureInternal(LPCSTR name) const;

  Process const* process_;
  HMODULE handle_;
  DWORD size_;
  std::wstring name_;
  std::wstring path_;
};

#if defined(HADESMEM_GCC)
#pragma GCC diagnostic pop
#endif // #if defined(HADESMEM_GCC)

}
<|endoftext|>


<commit_before>#pragma once

#include <quote/pp/cat.hpp>
#include <quote/pp/size.hpp>
#include <quote/pp/tuple_element.hpp>
#include <quote/pp/tuple_cons.hpp>
#include <quote/pp/tuple_car.hpp>
#include <quote/pp/tuple_cdr.hpp>

#if !defined(QUOTE_PP_TUPLE_FOREACH)
#  define QUOTE_PP_TUPLE_FOREACH(macro, data, tuple) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_FOREACH_I_, QUOTE_PP_SIZE tuple)(macro, data, tuple)
#endif

#define QUOTE_PP_TUPLE_FOREACH_I_0(macro, data, tuple) ()

#define QUOTE_PP_TUPLE_FOREACH_I_1(macro, data, tuple) \
	QUOTE_PP_TUPLE_FOREACH_II_1(macro, data, QUOTE_PP_TUPLE_ELEMENT(0, tuple))
#define QUOTE_PP_TUPLE_FOREACH_II_1(macro, data, elm) \
	 QUOTE_PP_TUPLE_FOREACH_III_1(macro, data, elm)
#define QUOTE_PP_TUPLE_FOREACH_III_1(macro, data, elm) \
	 (macro(data, elm))

#define QUOTE_PP_TUPLE_FOREACH_I_2(macro, data, tuple) \
	QUOTE_PP_TUPLE_FOREACH_II_2(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple))
#define QUOTE_PP_TUPLE_FOREACH_II_2(macro, data, elm, rest) \
	QUOTE_PP_TUPLE_FOREACH_III_2(macro, data, elm, rest)
#define QUOTE_PP_TUPLE_FOREACH_III_2(macro, data, elm, rest) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \
		macro(data, elm), \
		QUOTE_PP_TUPLE_FOREACH_I_1(macro, data, rest)),)

#define QUOTE_PP_TUPLE_FOREACH_I_3(macro, data, tuple) \
	QUOTE_PP_TUPLE_FOREACH_II_3(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple))
#define QUOTE_PP_TUPLE_FOREACH_II_3(macro, data, elm, rest) \
	QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest)
#define QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \
		macro(data, elm), \
		QUOTE_PP_TUPLE_FOREACH_I_2(macro, data, rest)),)

#define QUOTE_PP_TUPLE_FOREACH_I_4(macro, data, tuple) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \
		macro(data, QUOTE_PP_TUPLE_ELEMENT(0, tuple)), \
		QUOTE_PP_TUPLE_FOREACH_I_3(macro, data, QUOTE_PP_TUPLE_CDR(tuple))),)

#define QUOTE_PP_TUPLE_FOREACH_I_5(macro, data, tuple) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \
		macro(data, QUOTE_PP_TUPLE_ELEMENT(0, tuple)), \
		QUOTE_PP_TUPLE_FOREACH_I_4(macro, data, QUOTE_PP_TUPLE_CDR(tuple))),)
<commit_msg>fix QUOTE_PP_TUPLE_FOREACH<commit_after>#pragma once

#include <quote/pp/cat.hpp>
#include <quote/pp/size.hpp>
#include <quote/pp/tuple_element.hpp>
#include <quote/pp/tuple_cons.hpp>
#include <quote/pp/tuple_car.hpp>
#include <quote/pp/tuple_cdr.hpp>

#if !defined(QUOTE_PP_TUPLE_FOREACH)
#  define QUOTE_PP_TUPLE_FOREACH(macro, data, tuple) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_FOREACH_I_, QUOTE_PP_SIZE tuple)(macro, data, tuple)
#endif

#define QUOTE_PP_TUPLE_FOREACH_I_0(macro, data, tuple) ()

#define QUOTE_PP_TUPLE_FOREACH_I_1(macro, data, tuple) \
	QUOTE_PP_TUPLE_FOREACH_II_1(macro, data, QUOTE_PP_TUPLE_ELEMENT(0, tuple))
#define QUOTE_PP_TUPLE_FOREACH_II_1(macro, data, elm) \
	 QUOTE_PP_TUPLE_FOREACH_III_1(macro, data, elm)
#define QUOTE_PP_TUPLE_FOREACH_III_1(macro, data, elm) \
	 (macro(data, elm))

#define QUOTE_PP_TUPLE_FOREACH_I_2(macro, data, tuple) \
	QUOTE_PP_TUPLE_FOREACH_II_2(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple))
#define QUOTE_PP_TUPLE_FOREACH_II_2(macro, data, elm, rest) \
	QUOTE_PP_TUPLE_FOREACH_III_2(macro, data, elm, rest)
#define QUOTE_PP_TUPLE_FOREACH_III_2(macro, data, elm, rest) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \
		macro(data, elm), \
		QUOTE_PP_TUPLE_FOREACH_I_1(macro, data, rest)),)

#define QUOTE_PP_TUPLE_FOREACH_I_3(macro, data, tuple) \
	QUOTE_PP_TUPLE_FOREACH_II_3(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple))
#define QUOTE_PP_TUPLE_FOREACH_II_3(macro, data, elm, rest) \
	QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest)
#define QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \
		macro(data, elm), \
		QUOTE_PP_TUPLE_FOREACH_I_2(macro, data, rest)),)

#define QUOTE_PP_TUPLE_FOREACH_I_4(macro, data, tuple) \
	QUOTE_PP_TUPLE_FOREACH_II_4(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple))
#define QUOTE_PP_TUPLE_FOREACH_II_4(macro, data, elm, rest) \
	QUOTE_PP_TUPLE_FOREACH_III_4(macro, data, elm, rest)
#define QUOTE_PP_TUPLE_FOREACH_III_4(macro, data, elm, rest) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \
		macro(data, elm), \
		QUOTE_PP_TUPLE_FOREACH_I_3(macro, data, rest)),)

#define QUOTE_PP_TUPLE_FOREACH_I_5(macro, data, tuple) \
	QUOTE_PP_TUPLE_FOREACH_II_5(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple))
#define QUOTE_PP_TUPLE_FOREACH_II_5(macro, data, elm, rest) \
	QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest)
#define QUOTE_PP_TUPLE_FOREACH_III_5(macro, data, elm, rest) \
	QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \
		macro(data, elm), \
		QUOTE_PP_TUPLE_FOREACH_I_4(macro, data, rest)),)
<|endoftext|>


<commit_before>/**
 * @file LLRenderNavPrim.cpp
 * @brief Renderable primitives used by the pathing library
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "linden_common.h"
#include "llrendernavprim.h"
#include "llerror.h"
#include "llglheaders.h"
#include "llvertexbuffer.h"
#include "llglslshader.h"

//=============================================================================
LLRenderNavPrim gRenderNav;
//=============================================================================
void LLRenderNavPrim::renderSegment( const LLVector3& start, const LLVector3& end, int color, bool overlayMode  ) const
{
	LLGLSLShader::sNoFixedFunction = false;
	LLGLEnable smooth(GL_LINE_SMOOTH);
	LLColor4 colorA( color );
	glLineWidth(1.5f);
	gGL.color3fv( colorA.mV );

	gGL.begin(LLRender::LINES);
	{
		gGL.vertex3fv( start.mV );
		gGL.vertex3fv( end.mV );
	}
	gGL.end();

	gGL.flush();
	LLGLSLShader::sNoFixedFunction = true;
	LLGLDisable smoothout(GL_LINE_SMOOTH);
	glLineWidth(1.0f);
}
//=============================================================================
void LLRenderNavPrim::renderTri( const LLVector3& a, const LLVector3& b, const LLVector3& c, int color, bool overlayMode ) const
{
	glLineWidth(1.5f);
	if ( overlayMode )
	{
		glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
	}
	else
	{
		glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
	}
	LLGLDisable cull(GL_CULL_FACE);
	LLColor4 colorA( color );
	colorA*=1.25f;
	gGL.color4fv( colorA.mV );
	LLGLSLShader::sNoFixedFunction = false;
	gGL.begin(LLRender::TRIANGLES);
	{
		gGL.vertex3fv( a.mV );
		gGL.vertex3fv( b.mV );
		gGL.vertex3fv( c.mV );
	}
	gGL.end();
	gGL.flush();
	glLineWidth(1.0f);
	glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
	LLGLSLShader::sNoFixedFunction = true;
}
//=============================================================================
void LLRenderNavPrim::renderNavMeshVB( LLVertexBuffer* pVBO, int vertCnt )
{
	LLGLSUIDefault gls_ui;
	LLGLEnable depth( GL_DEPTH_TEST );
	LLGLEnable cull( GL_CULL_FACE );
	glLineWidth(1.5f);
	LLGLSLShader::sNoFixedFunction = false;
	//pass 1 filled
	pVBO->setBuffer( LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR | LLVertexBuffer::MAP_NORMAL );
	pVBO->drawArrays( LLRender::TRIANGLES, 0, vertCnt );
	glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
	LLGLEnable smooth(GL_LINE_SMOOTH);
	//pass 2 outlined
	pVBO->drawArrays( LLRender::TRIANGLES, 0, vertCnt );
	LLGLSLShader::sNoFixedFunction = true;
	glLineWidth(1.0f);
	glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
	LLGLDisable smoothout(GL_LINE_SMOOTH);
}
//=============================================================================
void LLRenderNavPrim::renderStar( const LLVector3& center, const float scale, int color ) const
{
	for (int k=0; k<3; k++)
	{
		LLVector3 star, pt1, pt2;
		star = LLVector3( 0.0f,0.0f,0.0f);
		star[k] = 0.5f;
		pt1 =  center + star;
		pt2 =  center - star;
		renderSegment( pt1, pt2, color, false );
	}
}
//=============================================================================
<commit_msg>Path-266: Navmesh is backfaced culled<commit_after>/**
 * @file LLRenderNavPrim.cpp
 * @brief Renderable primitives used by the pathing library
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "linden_common.h"
#include "llrendernavprim.h"
#include "llerror.h"
#include "llglheaders.h"
#include "llvertexbuffer.h"
#include "llglslshader.h"

//=============================================================================
LLRenderNavPrim gRenderNav;
//=============================================================================
void LLRenderNavPrim::renderSegment( const LLVector3& start, const LLVector3& end, int color, bool overlayMode  ) const
{
	LLGLSLShader::sNoFixedFunction = false;
	LLGLEnable smooth(GL_LINE_SMOOTH);
	LLColor4 colorA( color );
	glLineWidth(1.5f);
	gGL.color3fv( colorA.mV );

	gGL.begin(LLRender::LINES);
	{
		gGL.vertex3fv( start.mV );
		gGL.vertex3fv( end.mV );
	}
	gGL.end();

	gGL.flush();
	LLGLSLShader::sNoFixedFunction = true;
	LLGLDisable smoothout(GL_LINE_SMOOTH);
	glLineWidth(1.0f);
}
//=============================================================================
void LLRenderNavPrim::renderTri( const LLVector3& a, const LLVector3& b, const LLVector3& c, int color, bool overlayMode ) const
{
	glLineWidth(1.5f);
	if ( overlayMode )
	{
		glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
	}
	else
	{
		glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
	}
	LLGLEnable cull(GL_CULL_FACE);
	LLColor4 colorA( color );
	colorA*=1.25f;
	gGL.color4fv( colorA.mV );
	LLGLSLShader::sNoFixedFunction = false;
	gGL.begin(LLRender::TRIANGLES);
	{
		gGL.vertex3fv( a.mV );
		gGL.vertex3fv( b.mV );
		gGL.vertex3fv( c.mV );
	}
	gGL.end();
	gGL.flush();
	glLineWidth(1.0f);
	glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
	LLGLSLShader::sNoFixedFunction = true;
}
//=============================================================================
void LLRenderNavPrim::renderNavMeshVB( LLVertexBuffer* pVBO, int vertCnt )
{
	LLGLSUIDefault gls_ui;
	LLGLEnable depth( GL_DEPTH_TEST );
	LLGLEnable cull( GL_CULL_FACE );
	glLineWidth(1.5f);
	LLGLSLShader::sNoFixedFunction = false;
	//pass 1 filled
	pVBO->setBuffer( LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR | LLVertexBuffer::MAP_NORMAL );
	pVBO->drawArrays( LLRender::TRIANGLES, 0, vertCnt );
	glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
	LLGLEnable smooth(GL_LINE_SMOOTH);
	//pass 2 outlined
	pVBO->drawArrays( LLRender::TRIANGLES, 0, vertCnt );
	LLGLSLShader::sNoFixedFunction = true;
	glLineWidth(1.0f);
	glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
	LLGLDisable smoothout(GL_LINE_SMOOTH);
}
//=============================================================================
void LLRenderNavPrim::renderStar( const LLVector3& center, const float scale, int color ) const
{
	for (int k=0; k<3; k++)
	{
		LLVector3 star, pt1, pt2;
		star = LLVector3( 0.0f,0.0f,0.0f);
		star[k] = 0.5f;
		pt1 =  center + star;
		pt2 =  center - star;
		renderSegment( pt1, pt2, color, false );
	}
}
//=============================================================================
<|endoftext|>


<commit_before>/**
 * @file llimconversation.cpp
 * @brief LLIMConversation class implements the common behavior of LNearbyChatBar
 * @brief and LLIMFloater for hosting both in LLIMContainer
 *
 * $LicenseInfo:firstyear=2012&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llimconversation.h"

#include "llchatentry.h"
#include "llchathistory.h"
#include "lldraghandle.h"
#include "llfloaterreg.h"
#include "llimfloater.h"
#include "llimfloatercontainer.h" // to replace separate IM Floaters with multifloater container
#include "lllayoutstack.h"
#include "llnearbychat.h"

const F32 REFRESH_INTERVAL = 0.2f;

LLIMConversation::LLIMConversation(const LLUUID& session_id)
  : LLTransientDockableFloater(NULL, true, session_id)
  ,	LLEventTimer(REFRESH_INTERVAL)
  ,  mIsP2PChat(false)
  ,  mExpandCollapseBtn(NULL)
  ,  mTearOffBtn(NULL)
  ,  mCloseBtn(NULL)
  ,  mSessionID(session_id)
  , mParticipantList(NULL)
  , mChatHistory(NULL)
  , mInputEditor(NULL)
  , mInputEditorTopPad(0)
{
	mCommitCallbackRegistrar.add("IMSession.Menu.Action",
			boost::bind(&LLIMConversation::onIMSessionMenuItemClicked,  this, _2));
//	mCommitCallbackRegistrar.add("IMSession.ExpCollapseBtn.Click",
//			boost::bind(&LLIMConversation::onSlide,  this));
//	mCommitCallbackRegistrar.add("IMSession.CloseBtn.Click",
//			boost::bind(&LLFloater::onClickClose, this));
	mCommitCallbackRegistrar.add("IMSession.TearOffBtn.Click",
			boost::bind(&LLIMConversation::onTearOffClicked, this));
	mEnableCallbackRegistrar.add("IMSession.Menu.CompactExpandedModes.CheckItem",
			boost::bind(&LLIMConversation::onIMCompactExpandedMenuItemCheck, this, _2));
	mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.CheckItem",
			boost::bind(&LLIMConversation::onIMShowModesMenuItemCheck,   this, _2));
	mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.Enable",
			boost::bind(&LLIMConversation::onIMShowModesMenuItemEnable,  this, _2));
}

LLIMConversation::~LLIMConversation()
{
	if (mParticipantList)
	{
		delete mParticipantList;
		mParticipantList = NULL;
	}
}

BOOL LLIMConversation::postBuild()
{
	mCloseBtn = getChild<LLButton>("close_btn");
	mCloseBtn->setCommitCallback(boost::bind(&LLFloater::onClickClose, this));

	mExpandCollapseBtn = getChild<LLButton>("expand_collapse_btn");
	mExpandCollapseBtn->setClickedCallback(boost::bind(&LLIMConversation::onSlide, this));

	mParticipantListPanel = getChild<LLLayoutPanel>("speakers_list_panel");

	mTearOffBtn = getChild<LLButton>("tear_off_btn");
	mTearOffBtn->setCommitCallback(boost::bind(&LLIMConversation::onTearOffClicked, this));

	mChatHistory = getChild<LLChatHistory>("chat_history");
	mInputEditor = getChild<LLChatEntry>("chat_editor");

	mInputEditor->setTextExpandedCallback(boost::bind(&LLIMConversation::reshapeChatHistory, this));
	mInputEditorTopPad = mChatHistory->getRect().mBottom - mInputEditor->getRect().mTop;

	if (!getTornOff())
	{
		setOpenPositioning(LLFloaterEnums::POSITIONING_RELATIVE);
	}

	buildParticipantList();

	if (isChatMultiTab())
	{
		if (mIsNearbyChat)
		{
			setCanClose(FALSE);
		}
		return LLFloater::postBuild();
	}
	else
	{
		return LLDockableFloater::postBuild();
	}

}

BOOL LLIMConversation::tick()
{
	// This check is needed until LLFloaterReg::removeInstance() is synchronized with deleting the floater
	// via LLMortician::updateClass(), to avoid calling dead instances. See LLFloater::destroy().
	if (isDead()) return false;

	// Need to resort the participant list if it's in sort by recent speaker order.
	if (mParticipantList)
	{
		mParticipantList->update();
	}

	return false;
}

void LLIMConversation::buildParticipantList()
{
	if (mIsNearbyChat)
	{
		LLLocalSpeakerMgr* speaker_manager = LLLocalSpeakerMgr::getInstance();
		mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false);
	}
	else
	{
		// for group and ad-hoc chat we need to include agent into list
		if(!mIsP2PChat && !mParticipantList && mSessionID.notNull())
		{
			LLSpeakerMgr* speaker_manager = LLIMModel::getInstance()->getSpeakerManager(mSessionID);
			mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false);
		}
	}
}

void LLIMConversation::onSortMenuItemClicked(const LLSD& userdata)
{
	// TODO: Check this code when sort order menu will be added. (EM)
	if (!mParticipantList)
	{
		return;
	}

	std::string chosen_item = userdata.asString();

	if (chosen_item == "sort_name")
	{
		mParticipantList->setSortOrder(LLParticipantList::E_SORT_BY_NAME);
	}

}

void LLIMConversation::onIMSessionMenuItemClicked(const LLSD& userdata)
{
	std::string item = userdata.asString();

	if (item == "compact_view" || item == "expanded_view")
	{
		gSavedSettings.setBOOL("PlainTextChatHistory", item == "compact_view");
	}
	else
	{
		bool prev_value = gSavedSettings.getBOOL(item);
		gSavedSettings.setBOOL(item, !prev_value);
	}

	LLIMConversation::processChatHistoryStyleUpdate();
}

bool LLIMConversation::onIMCompactExpandedMenuItemCheck(const LLSD& userdata)
{
	std::string item = userdata.asString();
	bool is_plain_text_mode = gSavedSettings.getBOOL("PlainTextChatHistory");

	return is_plain_text_mode? item == "compact_view" : item == "expanded_view";
}

bool LLIMConversation::onIMShowModesMenuItemCheck(const LLSD& userdata)
{
	return gSavedSettings.getBOOL(userdata.asString());
}

// enable/disable states for the "show time" and "show names" items of the show-modes menu
bool LLIMConversation::onIMShowModesMenuItemEnable(const LLSD& userdata)
{
	std::string item = userdata.asString();
	bool plain_text = gSavedSettings.getBOOL("PlainTextChatHistory");
	bool is_not_names = (item != "IMShowNamesForP2PConv");
	return (plain_text && (is_not_names || mIsP2PChat));
}

void LLIMConversation::updateHeaderAndToolbar()
{
	bool is_hosted = getHost() != NULL;

	if (is_hosted)
	{
		for (S32 i = 0; i < BUTTON_COUNT; i++)
		{
			if (mButtons[i])
			{
				// Hide the standard header buttons in a docked IM floater.
				mButtons[i]->setVisible(false);
			}
		}
	}

	// Participant list should be visible only in torn off floaters.
	bool is_participant_list_visible =
			!is_hosted
			&& gSavedSettings.getBOOL("IMShowControlPanel")
			&& !mIsP2PChat;

	mParticipantListPanel->setVisible(is_participant_list_visible);

	// Display collapse image (<<) if the floater is hosted
	// or if it is torn off but has an open control panel.
	bool is_expanded = is_hosted || is_participant_list_visible;
	mExpandCollapseBtn->setImageOverlay(getString(is_expanded ? "collapse_icon" : "expand_icon"));

	// The button (>>) should be disabled for torn off P2P conversations.
	mExpandCollapseBtn->setEnabled(is_hosted || !mIsP2PChat);

	if (mDragHandle)
	{
		// toggle floater's drag handle and title visibility
		mDragHandle->setVisible(!is_hosted);
	}

	mTearOffBtn->setImageOverlay(getString(is_hosted ? "tear_off_icon" : "return_icon"));

	mCloseBtn->setVisible(is_hosted && !mIsNearbyChat);

	enableDisableCallBtn();

	showTranslationCheckbox();
}

void LLIMConversation::reshapeChatHistory()
{
	LLRect chat_rect  = mChatHistory->getRect();
	LLRect input_rect = mInputEditor->getRect();

	int delta_height = chat_rect.mBottom - (input_rect.mTop + mInputEditorTopPad);

	chat_rect.setLeftTopAndSize(chat_rect.mLeft, chat_rect.mTop, chat_rect.getWidth(), chat_rect.getHeight() + delta_height);
	mChatHistory->setShape(chat_rect);
}

void LLIMConversation::showTranslationCheckbox(BOOL show)
{
	getChild<LLUICtrl>("translate_chat_checkbox_lp")->setVisible(mIsNearbyChat? show : FALSE);
}

// static
void LLIMConversation::processChatHistoryStyleUpdate()
{
	LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("impanel");
	for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin();
			iter != inst_list.end(); ++iter)
	{
		LLIMFloater* floater = dynamic_cast<LLIMFloater*>(*iter);
		if (floater)
		{
			floater->reloadMessages();
		}
	}

	LLNearbyChat* nearby_chat = LLNearbyChat::getInstance();
	if (nearby_chat)
	{
		nearby_chat->reloadMessages();
	}
}

void LLIMConversation::updateCallBtnState(bool callIsActive)
{
	getChild<LLButton>("voice_call_btn")->setImageOverlay(
			callIsActive? getString("call_btn_stop") : getString("call_btn_start"));
    enableDisableCallBtn();

}

void LLIMConversation::onSlide(LLIMConversation* self)
{
	LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(self->getHost());
	if (host_floater)
	{
		// Hide the messages pane if a floater is hosted in the Conversations
		host_floater->collapseMessagesPane(true);
	}
	else ///< floater is torn off
	{
		if (!self->mIsP2PChat)
		{
			bool expand = !self->mParticipantListPanel->getVisible();

			// Expand/collapse the IM control panel
			self->mParticipantListPanel->setVisible(expand);

			gSavedSettings.setBOOL("IMShowControlPanel", expand);

			self->mExpandCollapseBtn->setImageOverlay(self->getString(expand ? "collapse_icon" : "expand_icon"));
		}
	}
}

/*virtual*/
void LLIMConversation::onOpen(const LLSD& key)
{
	LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(getHost());
	if (host_floater)
	{
		// Show the messages pane when opening a floater hosted in the Conversations
		host_floater->collapseMessagesPane(false);
	}

	updateHeaderAndToolbar();
}

// virtual
void LLIMConversation::onClose(bool app_quitting)
{
	// Always suppress the IM from the conversations list on close if present for any reason
	if (LLIMConversation::isChatMultiTab())
	{
		LLIMFloaterContainer* im_box = LLIMFloaterContainer::findInstance();
		if (im_box)
		{
            im_box->removeConversationListItem(mSessionID);
        }
    }
}

void LLIMConversation::onTearOffClicked()
{
	onClickTearOff(this);
	updateHeaderAndToolbar();
}

// static
bool LLIMConversation::isChatMultiTab()
{
	// Restart is required in order to change chat window type.
	return true;
}
<commit_msg>CHUI-168 FIXED Added call of updateHeaderAndToolbar from postBuild for correct floater's title and standard buttons showing at start<commit_after>/**
 * @file llimconversation.cpp
 * @brief LLIMConversation class implements the common behavior of LNearbyChatBar
 * @brief and LLIMFloater for hosting both in LLIMContainer
 *
 * $LicenseInfo:firstyear=2012&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llimconversation.h"

#include "llchatentry.h"
#include "llchathistory.h"
#include "lldraghandle.h"
#include "llfloaterreg.h"
#include "llimfloater.h"
#include "llimfloatercontainer.h" // to replace separate IM Floaters with multifloater container
#include "lllayoutstack.h"
#include "llnearbychat.h"

const F32 REFRESH_INTERVAL = 0.2f;

LLIMConversation::LLIMConversation(const LLUUID& session_id)
  : LLTransientDockableFloater(NULL, true, session_id)
  ,	LLEventTimer(REFRESH_INTERVAL)
  ,  mIsP2PChat(false)
  ,  mExpandCollapseBtn(NULL)
  ,  mTearOffBtn(NULL)
  ,  mCloseBtn(NULL)
  ,  mSessionID(session_id)
  , mParticipantList(NULL)
  , mChatHistory(NULL)
  , mInputEditor(NULL)
  , mInputEditorTopPad(0)
{
	mCommitCallbackRegistrar.add("IMSession.Menu.Action",
			boost::bind(&LLIMConversation::onIMSessionMenuItemClicked,  this, _2));
//	mCommitCallbackRegistrar.add("IMSession.ExpCollapseBtn.Click",
//			boost::bind(&LLIMConversation::onSlide,  this));
//	mCommitCallbackRegistrar.add("IMSession.CloseBtn.Click",
//			boost::bind(&LLFloater::onClickClose, this));
	mCommitCallbackRegistrar.add("IMSession.TearOffBtn.Click",
			boost::bind(&LLIMConversation::onTearOffClicked, this));
	mEnableCallbackRegistrar.add("IMSession.Menu.CompactExpandedModes.CheckItem",
			boost::bind(&LLIMConversation::onIMCompactExpandedMenuItemCheck, this, _2));
	mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.CheckItem",
			boost::bind(&LLIMConversation::onIMShowModesMenuItemCheck,   this, _2));
	mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.Enable",
			boost::bind(&LLIMConversation::onIMShowModesMenuItemEnable,  this, _2));
}

LLIMConversation::~LLIMConversation()
{
	if (mParticipantList)
	{
		delete mParticipantList;
		mParticipantList = NULL;
	}
}

BOOL LLIMConversation::postBuild()
{
	mCloseBtn = getChild<LLButton>("close_btn");
	mCloseBtn->setCommitCallback(boost::bind(&LLFloater::onClickClose, this));

	mExpandCollapseBtn = getChild<LLButton>("expand_collapse_btn");
	mExpandCollapseBtn->setClickedCallback(boost::bind(&LLIMConversation::onSlide, this));

	mParticipantListPanel = getChild<LLLayoutPanel>("speakers_list_panel");

	mTearOffBtn = getChild<LLButton>("tear_off_btn");
	mTearOffBtn->setCommitCallback(boost::bind(&LLIMConversation::onTearOffClicked, this));

	mChatHistory = getChild<LLChatHistory>("chat_history");
	mInputEditor = getChild<LLChatEntry>("chat_editor");

	mInputEditor->setTextExpandedCallback(boost::bind(&LLIMConversation::reshapeChatHistory, this));
	mInputEditorTopPad = mChatHistory->getRect().mBottom - mInputEditor->getRect().mTop;

	if (!getTornOff())
	{
		setOpenPositioning(LLFloaterEnums::POSITIONING_RELATIVE);
	}

	buildParticipantList();
	updateHeaderAndToolbar();

	if (isChatMultiTab())
	{
		if (mIsNearbyChat)
		{
			setCanClose(FALSE);
		}
		return LLFloater::postBuild();
	}
	else
	{
		return LLDockableFloater::postBuild();
	}

}

BOOL LLIMConversation::tick()
{
	// This check is needed until LLFloaterReg::removeInstance() is synchronized with deleting the floater
	// via LLMortician::updateClass(), to avoid calling dead instances. See LLFloater::destroy().
	if (isDead()) return false;

	// Need to resort the participant list if it's in sort by recent speaker order.
	if (mParticipantList)
	{
		mParticipantList->update();
	}

	return false;
}

void LLIMConversation::buildParticipantList()
{
	if (mIsNearbyChat)
	{
		LLLocalSpeakerMgr* speaker_manager = LLLocalSpeakerMgr::getInstance();
		mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false);
	}
	else
	{
		// for group and ad-hoc chat we need to include agent into list
		if(!mIsP2PChat && !mParticipantList && mSessionID.notNull())
		{
			LLSpeakerMgr* speaker_manager = LLIMModel::getInstance()->getSpeakerManager(mSessionID);
			mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false);
		}
	}
}

void LLIMConversation::onSortMenuItemClicked(const LLSD& userdata)
{
	// TODO: Check this code when sort order menu will be added. (EM)
	if (!mParticipantList)
	{
		return;
	}

	std::string chosen_item = userdata.asString();

	if (chosen_item == "sort_name")
	{
		mParticipantList->setSortOrder(LLParticipantList::E_SORT_BY_NAME);
	}

}

void LLIMConversation::onIMSessionMenuItemClicked(const LLSD& userdata)
{
	std::string item = userdata.asString();

	if (item == "compact_view" || item == "expanded_view")
	{
		gSavedSettings.setBOOL("PlainTextChatHistory", item == "compact_view");
	}
	else
	{
		bool prev_value = gSavedSettings.getBOOL(item);
		gSavedSettings.setBOOL(item, !prev_value);
	}

	LLIMConversation::processChatHistoryStyleUpdate();
}

bool LLIMConversation::onIMCompactExpandedMenuItemCheck(const LLSD& userdata)
{
	std::string item = userdata.asString();
	bool is_plain_text_mode = gSavedSettings.getBOOL("PlainTextChatHistory");

	return is_plain_text_mode? item == "compact_view" : item == "expanded_view";
}

bool LLIMConversation::onIMShowModesMenuItemCheck(const LLSD& userdata)
{
	return gSavedSettings.getBOOL(userdata.asString());
}

// enable/disable states for the "show time" and "show names" items of the show-modes menu
bool LLIMConversation::onIMShowModesMenuItemEnable(const LLSD& userdata)
{
	std::string item = userdata.asString();
	bool plain_text = gSavedSettings.getBOOL("PlainTextChatHistory");
	bool is_not_names = (item != "IMShowNamesForP2PConv");
	return (plain_text && (is_not_names || mIsP2PChat));
}

void LLIMConversation::updateHeaderAndToolbar()
{
	bool is_hosted = getHost() != NULL;

	if (is_hosted)
	{
		for (S32 i = 0; i < BUTTON_COUNT; i++)
		{
			if (mButtons[i])
			{
				// Hide the standard header buttons in a docked IM floater.
				mButtons[i]->setVisible(false);
			}
		}
	}

	// Participant list should be visible only in torn off floaters.
	bool is_participant_list_visible =
			!is_hosted
			&& gSavedSettings.getBOOL("IMShowControlPanel")
			&& !mIsP2PChat;

	mParticipantListPanel->setVisible(is_participant_list_visible);

	// Display collapse image (<<) if the floater is hosted
	// or if it is torn off but has an open control panel.
	bool is_expanded = is_hosted || is_participant_list_visible;
	mExpandCollapseBtn->setImageOverlay(getString(is_expanded ? "collapse_icon" : "expand_icon"));

	// The button (>>) should be disabled for torn off P2P conversations.
	mExpandCollapseBtn->setEnabled(is_hosted || !mIsP2PChat);

	if (mDragHandle)
	{
		// toggle floater's drag handle and title visibility
		mDragHandle->setVisible(!is_hosted);
	}

	mTearOffBtn->setImageOverlay(getString(is_hosted ? "tear_off_icon" : "return_icon"));

	mCloseBtn->setVisible(is_hosted && !mIsNearbyChat);

	enableDisableCallBtn();

	showTranslationCheckbox();
}

void LLIMConversation::reshapeChatHistory()
{
	LLRect chat_rect  = mChatHistory->getRect();
	LLRect input_rect = mInputEditor->getRect();

	int delta_height = chat_rect.mBottom - (input_rect.mTop + mInputEditorTopPad);

	chat_rect.setLeftTopAndSize(chat_rect.mLeft, chat_rect.mTop, chat_rect.getWidth(), chat_rect.getHeight() + delta_height);
	mChatHistory->setShape(chat_rect);
}

void LLIMConversation::showTranslationCheckbox(BOOL show)
{
	getChild<LLUICtrl>("translate_chat_checkbox_lp")->setVisible(mIsNearbyChat? show : FALSE);
}

// static
void LLIMConversation::processChatHistoryStyleUpdate()
{
	LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("impanel");
	for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin();
			iter != inst_list.end(); ++iter)
	{
		LLIMFloater* floater = dynamic_cast<LLIMFloater*>(*iter);
		if (floater)
		{
			floater->reloadMessages();
		}
	}

	LLNearbyChat* nearby_chat = LLNearbyChat::getInstance();
	if (nearby_chat)
	{
		nearby_chat->reloadMessages();
	}
}

void LLIMConversation::updateCallBtnState(bool callIsActive)
{
	getChild<LLButton>("voice_call_btn")->setImageOverlay(
			callIsActive? getString("call_btn_stop") : getString("call_btn_start"));
    enableDisableCallBtn();

}

void LLIMConversation::onSlide(LLIMConversation* self)
{
	LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(self->getHost());
	if (host_floater)
	{
		// Hide the messages pane if a floater is hosted in the Conversations
		host_floater->collapseMessagesPane(true);
	}
	else ///< floater is torn off
	{
		if (!self->mIsP2PChat)
		{
			bool expand = !self->mParticipantListPanel->getVisible();

			// Expand/collapse the IM control panel
			self->mParticipantListPanel->setVisible(expand);

			gSavedSettings.setBOOL("IMShowControlPanel", expand);

			self->mExpandCollapseBtn->setImageOverlay(self->getString(expand ? "collapse_icon" : "expand_icon"));
		}
	}
}

/*virtual*/
void LLIMConversation::onOpen(const LLSD& key)
{
	LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(getHost());
	if (host_floater)
	{
		// Show the messages pane when opening a floater hosted in the Conversations
		host_floater->collapseMessagesPane(false);
	}

	updateHeaderAndToolbar();
}

// virtual
void LLIMConversation::onClose(bool app_quitting)
{
	// Always suppress the IM from the conversations list on close if present for any reason
	if (LLIMConversation::isChatMultiTab())
	{
		LLIMFloaterContainer* im_box = LLIMFloaterContainer::findInstance();
		if (im_box)
		{
            im_box->removeConversationListItem(mSessionID);
        }
    }
}

void LLIMConversation::onTearOffClicked()
{
	onClickTearOff(this);
	updateHeaderAndToolbar();
}

// static
bool LLIMConversation::isChatMultiTab()
{
	// Restart is required in order to change chat window type.
	return true;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

//
// vie_autotest_linux.cc
//
#include "vie_autotest_linux.h"

#include <string>

#include "vie_autotest_defines.h"
#include "vie_autotest_main.h"
#include "engine_configurations.h"
#include "critical_section_wrapper.h"
#include "thread_wrapper.h"

ViEAutoTestWindowManager::ViEAutoTestWindowManager()
    : _hdsp1(NULL),
      _hdsp2(NULL) {
}

ViEAutoTestWindowManager::~ViEAutoTestWindowManager() {
  TerminateWindows();
}

void* ViEAutoTestWindowManager::GetWindow1() {
  return reinterpret_cast<void*>(_hwnd1);
}

void* ViEAutoTestWindowManager::GetWindow2() {
  return reinterpret_cast<void*>(_hwnd2);
}

int ViEAutoTestWindowManager::TerminateWindows() {
  if (_hdsp1) {
    ViEDestroyWindow(&_hwnd1, _hdsp1);
    _hdsp1 = NULL;
  }
  if (_hdsp2) {
    ViEDestroyWindow(&_hwnd2, _hdsp2);
    _hdsp2 = NULL;
  }
  return 0;
}

int ViEAutoTestWindowManager::CreateWindows(AutoTestRect window1Size,
                                            AutoTestRect window2Size,
                                            void* window1Title,
                                            void* window2Title) {
  ViECreateWindow(&_hwnd1, &_hdsp1, window1Size.origin.x,
                  window1Size.origin.y, window1Size.size.width,
                  window1Size.size.height,
                  reinterpret_cast<char*>(window1Title));
  ViECreateWindow(&_hwnd2, &_hdsp2, window2Size.origin.x,
                  window2Size.origin.y, window2Size.size.width,
                  window2Size.size.height,
                  reinterpret_cast<char*>(window2Title));

  return 0;
}

int ViEAutoTestWindowManager::ViECreateWindow(Window *outWindow,
                                              Display **outDisplay, int xpos,
                                              int ypos, int width, int height,
                                              char* title) {
  int screen;
  XEvent evnt;
  XSetWindowAttributes xswa;  // window attribute struct
  XVisualInfo vinfo;          // screen visual info struct
  unsigned long mask;         // attribute mask

  // get connection handle to xserver
  Display* _display = XOpenDisplay(NULL);

  // get screen number
  screen = DefaultScreen(_display);

  // put desired visual info for the screen in vinfo
  // TODO(unknown): more display settings should be allowed
  if (XMatchVisualInfo(_display, screen, 24, TrueColor, &vinfo) != 0) {
    // printf( "Screen visual info match!\n" );
  }
  // set window attributes
  xswa.colormap = XCreateColormap(_display, DefaultRootWindow(_display),
                                  vinfo.visual, AllocNone);
  xswa.event_mask = StructureNotifyMask | ExposureMask;
  xswa.background_pixel = 0;
  xswa.border_pixel = 0;

  // value mask for attributes
  mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

  Window _window = XCreateWindow(_display, DefaultRootWindow(_display), xpos,
                                 ypos, width, height, 0, vinfo.depth,
                                 InputOutput, vinfo.visual, mask, &xswa);

  // Set window name
  XStoreName(_display, _window, title);
  XSetIconName(_display, _window, title);

  // make x report events for mask
  XSelectInput(_display, _window, StructureNotifyMask);

  // map the window to the display
  XMapWindow(_display, _window);

  // wait for map event
  do {
    XNextEvent(_display, &evnt);
  } while (evnt.type != MapNotify || evnt.xmap.event != _window);

  *outWindow = _window;
  *outDisplay = _display;
  return 0;
}

int ViEAutoTestWindowManager::ViEDestroyWindow(Window *window,
                                               Display *display) {
  XUnmapWindow(display, *window);
  XDestroyWindow(display, *window);
  XSync(display, false);
  return 0;
}

bool ViEAutoTestWindowManager::SetTopmostWindow() {
  return 0;
}

int main(int argc, char** argv) {
  ViEAutoTestMain auto_test;
  return auto_test.RunTests(argc, argv);
}
<commit_msg>Made vie_auto_test more robust in Linux when the X environment is broken.<commit_after>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

//
// vie_autotest_linux.cc
//
#include "vie_autotest_linux.h"

#include <string>

#include "vie_autotest_defines.h"
#include "vie_autotest_main.h"
#include "engine_configurations.h"
#include "critical_section_wrapper.h"
#include "thread_wrapper.h"

ViEAutoTestWindowManager::ViEAutoTestWindowManager()
    : _hdsp1(NULL),
      _hdsp2(NULL) {
}

ViEAutoTestWindowManager::~ViEAutoTestWindowManager() {
  TerminateWindows();
}

void* ViEAutoTestWindowManager::GetWindow1() {
  return reinterpret_cast<void*>(_hwnd1);
}

void* ViEAutoTestWindowManager::GetWindow2() {
  return reinterpret_cast<void*>(_hwnd2);
}

int ViEAutoTestWindowManager::TerminateWindows() {
  if (_hdsp1) {
    ViEDestroyWindow(&_hwnd1, _hdsp1);
    _hdsp1 = NULL;
  }
  if (_hdsp2) {
    ViEDestroyWindow(&_hwnd2, _hdsp2);
    _hdsp2 = NULL;
  }
  return 0;
}

int ViEAutoTestWindowManager::CreateWindows(AutoTestRect window1Size,
                                            AutoTestRect window2Size,
                                            void* window1Title,
                                            void* window2Title) {
  ViECreateWindow(&_hwnd1, &_hdsp1, window1Size.origin.x,
                  window1Size.origin.y, window1Size.size.width,
                  window1Size.size.height,
                  reinterpret_cast<char*>(window1Title));
  ViECreateWindow(&_hwnd2, &_hdsp2, window2Size.origin.x,
                  window2Size.origin.y, window2Size.size.width,
                  window2Size.size.height,
                  reinterpret_cast<char*>(window2Title));

  return 0;
}

int ViEAutoTestWindowManager::ViECreateWindow(Window *out_window,
                                              Display **out_display, int x_pos,
                                              int y_pos, int width, int height,
                                              char* title) {
  Display* display = XOpenDisplay(NULL);
  if (display == NULL) {
    // There's no point to continue if this happens: nothing will work anyway.
    printf("Failed to connect to X server: X environment likely broken\n");
    exit(-1);
  }

  int screen = DefaultScreen(display);

  // Try to establish a 24-bit TrueColor display
  // (our environment must allow this).
  XVisualInfo visual_info;
  if (XMatchVisualInfo(display, screen, 24, TrueColor, &visual_info) == 0) {
    printf("Failed to establish 24-bit TrueColor in X environment.\n");
    exit(-1);
  }

  // Create suitable window attributes.
  XSetWindowAttributes window_attributes;
  window_attributes.colormap = XCreateColormap(
      display, DefaultRootWindow(display), visual_info.visual, AllocNone);
  window_attributes.event_mask = StructureNotifyMask | ExposureMask;
  window_attributes.background_pixel = 0;
  window_attributes.border_pixel = 0;

  unsigned long attribute_mask = CWBackPixel | CWBorderPixel | CWColormap |
                                 CWEventMask;

  Window _window = XCreateWindow(display, DefaultRootWindow(display), x_pos,
                                 y_pos, width, height, 0, visual_info.depth,
                                 InputOutput, visual_info.visual,
                                 attribute_mask, &window_attributes);

  // Set window name.
  XStoreName(display, _window, title);
  XSetIconName(display, _window, title);

  // Make x report events for mask.
  XSelectInput(display, _window, StructureNotifyMask);

  // Map the window to the display.
  XMapWindow(display, _window);

  // Wait for map event.
  XEvent event;
  do {
    XNextEvent(display, &event);
  } while (event.type != MapNotify || event.xmap.event != _window);

  *out_window = _window;
  *out_display = display;
  return 0;
}

int ViEAutoTestWindowManager::ViEDestroyWindow(Window *window,
                                               Display *display) {
  XUnmapWindow(display, *window);
  XDestroyWindow(display, *window);
  XSync(display, false);
  return 0;
}

bool ViEAutoTestWindowManager::SetTopmostWindow() {
  return 0;
}

int main(int argc, char** argv) {
  ViEAutoTestMain auto_test;
  return auto_test.RunTests(argc, argv);
}
<|endoftext|>


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

#include <mpi.h>
#include <vector>
#include "geopm.h"
#include "ModelRegion.hpp"

__attribute__((noinline))
void setup(std::vector<double> &aa_vec,
           std::vector<double> &bb_vec,
           std::vector<double> &cc_vec)
{
#pragma omp parallel for
    for (size_t idx = 0; idx < aa_vec.size(); ++idx) {
        aa_vec[idx] = 0.0;
        aa_vec[idx] = 1.0;
        aa_vec[idx] = 2.0;
    }
}

__attribute__((noinline))
void triad_with_post(std::vector<double> &aa_vec,
                     const std::vector<double> &bb_vec,
                     const std::vector<double> &cc_vec)
{
    double scalar = 3.0;
#pragma omp parallel for
    for (size_t idx = 0; idx < aa_vec.size(); ++idx) {
        geopm_tprof_post();
        aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx];
    }
}

__attribute__((noinline))
void triad_no_post(std::vector<double> &aa_vec,
                   const std::vector<double> &bb_vec,
                   const std::vector<double> &cc_vec)
{
    double scalar = 3.0;
#pragma omp parallel for
    for (size_t idx = 0; idx < aa_vec.size(); ++idx) {
        aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx];
    }
}

__attribute__((noinline))
void warmup(std::vector<double> &aa_vec,
            const std::vector<double> &bb_vec,
            const std::vector<double> &cc_vec)
{
    double scalar = 3.0;
#pragma omp parallel for
    for (size_t idx = 0; idx < aa_vec.size(); ++idx) {
        aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx];
    }
}

__attribute__((noinline))
void loop_dgemm_with_post(double big_o, int count)
{
#pragma omp parallel
{
    std::shared_ptr<geopm::ModelRegion> dgemm_model(
        geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false));
#pragma omp for
    for (size_t idx = 0; idx < count; ++idx) {
        geopm_tprof_post();
        dgemm_model->run();
    }
}
}

__attribute__((noinline))
void loop_dgemm_no_post(double big_o, int count)
{
#pragma omp parallel
{
    std::shared_ptr<geopm::ModelRegion> dgemm_model(
        geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false));
#pragma omp for
    for (size_t idx = 0; idx < count; ++idx) {
        dgemm_model->run();
    }
}
}

__attribute__((noinline))
void loop_dgemm_warmup(double big_o, int count)
{
#pragma omp parallel
{
    std::shared_ptr<geopm::ModelRegion> dgemm_model(
        geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false));
#pragma omp for
    for (size_t idx = 0; idx < count; ++idx) {
        dgemm_model->run();
    }
}
}

int main(int argc, char **argv)
{
    MPI_Init(&argc, &argv);
    int vec_size = 134217728; // 1 GiB

    std::vector<double> aa_vec(vec_size);
    std::vector<double> bb_vec(vec_size);
    std::vector<double> cc_vec(vec_size);

    MPI_Barrier(MPI_COMM_WORLD);
    setup(aa_vec, bb_vec, cc_vec);

    MPI_Barrier(MPI_COMM_WORLD);
    warmup(aa_vec, bb_vec, cc_vec);

    MPI_Barrier(MPI_COMM_WORLD);
    triad_with_post(aa_vec, bb_vec, cc_vec);

    MPI_Barrier(MPI_COMM_WORLD);
    triad_no_post(aa_vec, bb_vec, cc_vec);

    MPI_Barrier(MPI_COMM_WORLD);
    loop_dgemm_warmup(0.01, 100);

    MPI_Barrier(MPI_COMM_WORLD);
    loop_dgemm_with_post(0.01, 10000);

    MPI_Barrier(MPI_COMM_WORLD);
    loop_dgemm_no_post(0.01, 10000);

    MPI_Finalize();
    return 0;
}
<commit_msg>Fix signed / unsigned comparison<commit_after>/*
 * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <mpi.h>
#include <vector>
#include "geopm.h"
#include "ModelRegion.hpp"

__attribute__((noinline))
void setup(std::vector<double> &aa_vec,
           std::vector<double> &bb_vec,
           std::vector<double> &cc_vec)
{
#pragma omp parallel for
    for (size_t idx = 0; idx < aa_vec.size(); ++idx) {
        aa_vec[idx] = 0.0;
        aa_vec[idx] = 1.0;
        aa_vec[idx] = 2.0;
    }
}

__attribute__((noinline))
void triad_with_post(std::vector<double> &aa_vec,
                     const std::vector<double> &bb_vec,
                     const std::vector<double> &cc_vec)
{
    double scalar = 3.0;
#pragma omp parallel for
    for (size_t idx = 0; idx < aa_vec.size(); ++idx) {
        geopm_tprof_post();
        aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx];
    }
}

__attribute__((noinline))
void triad_no_post(std::vector<double> &aa_vec,
                   const std::vector<double> &bb_vec,
                   const std::vector<double> &cc_vec)
{
    double scalar = 3.0;
#pragma omp parallel for
    for (size_t idx = 0; idx < aa_vec.size(); ++idx) {
        aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx];
    }
}

__attribute__((noinline))
void warmup(std::vector<double> &aa_vec,
            const std::vector<double> &bb_vec,
            const std::vector<double> &cc_vec)
{
    double scalar = 3.0;
#pragma omp parallel for
    for (size_t idx = 0; idx < aa_vec.size(); ++idx) {
        aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx];
    }
}

__attribute__((noinline))
void loop_dgemm_with_post(double big_o, int count)
{
#pragma omp parallel
{
    std::shared_ptr<geopm::ModelRegion> dgemm_model(
        geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false));
#pragma omp for
    for (int idx = 0; idx < count; ++idx) {
        geopm_tprof_post();
        dgemm_model->run();
    }
}
}

__attribute__((noinline))
void loop_dgemm_no_post(double big_o, int count)
{
#pragma omp parallel
{
    std::shared_ptr<geopm::ModelRegion> dgemm_model(
        geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false));
#pragma omp for
    for (int idx = 0; idx < count; ++idx) {
        dgemm_model->run();
    }
}
}

__attribute__((noinline))
void loop_dgemm_warmup(double big_o, int count)
{
#pragma omp parallel
{
    std::shared_ptr<geopm::ModelRegion> dgemm_model(
        geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false));
#pragma omp for
    for (int idx = 0; idx < count; ++idx) {
        dgemm_model->run();
    }
}
}

int main(int argc, char **argv)
{
    MPI_Init(&argc, &argv);
    int vec_size = 134217728; // 1 GiB

    std::vector<double> aa_vec(vec_size);
    std::vector<double> bb_vec(vec_size);
    std::vector<double> cc_vec(vec_size);

    MPI_Barrier(MPI_COMM_WORLD);
    setup(aa_vec, bb_vec, cc_vec);

    MPI_Barrier(MPI_COMM_WORLD);
    warmup(aa_vec, bb_vec, cc_vec);

    MPI_Barrier(MPI_COMM_WORLD);
    triad_with_post(aa_vec, bb_vec, cc_vec);

    MPI_Barrier(MPI_COMM_WORLD);
    triad_no_post(aa_vec, bb_vec, cc_vec);

    MPI_Barrier(MPI_COMM_WORLD);
    loop_dgemm_warmup(0.01, 100);

    MPI_Barrier(MPI_COMM_WORLD);
    loop_dgemm_with_post(0.01, 10000);

    MPI_Barrier(MPI_COMM_WORLD);
    loop_dgemm_no_post(0.01, 10000);

    MPI_Finalize();
    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include <array>
#include <cstdio>
#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>

#include "iree/base/api.h"
#include "iree/base/internal/file_io.h"
#include "iree/base/internal/flags.h"
#include "iree/base/status_cc.h"
#include "iree/base/tracing.h"
#include "iree/hal/api.h"
#include "iree/hal/drivers/init.h"
#include "iree/modules/hal/module.h"
#include "iree/tools/utils/vm_util.h"
#include "iree/vm/api.h"
#include "iree/vm/bytecode_module.h"
#include "iree/vm/ref_cc.h"

IREE_FLAG(string, module_file, "-",
          "File containing the module to load that contains the entry "
          "function. Defaults to stdin.");

IREE_FLAG(string, entry_function, "",
          "Name of a function contained in the module specified by module_file "
          "to run.");

IREE_FLAG(string, driver, "vmvx", "Backend driver to use.");

static iree_status_t parse_function_input(iree_string_view_t flag_name,
                                          void* storage,
                                          iree_string_view_t value) {
  auto* list = (std::vector<std::string>*)storage;
  list->push_back(std::string(value.data, value.size));
  return iree_ok_status();
}
static void print_function_input(iree_string_view_t flag_name, void* storage,
                                 FILE* file) {
  auto* list = (std::vector<std::string>*)storage;
  if (list->empty()) {
    fprintf(file, "# --%.*s=\n", (int)flag_name.size, flag_name.data);
  } else {
    for (size_t i = 0; i < list->size(); ++i) {
      fprintf(file, "--%.*s=\"%s\"\n", (int)flag_name.size, flag_name.data,
              list->at(i).c_str());
    }
  }
}
static std::vector<std::string> FLAG_function_inputs;
IREE_FLAG_CALLBACK(
    parse_function_input, print_function_input, &FLAG_function_inputs,
    function_input,
    "An input value or buffer of the format:\n"
    "  [shape]xtype=[value]\n"
    "  2x2xi32=1 2 3 4\n"
    "Optionally, brackets may be used to separate the element values:\n"
    "  2x2xi32=[[1 2][3 4]]\n"
    "Each occurrence of the flag indicates an input in the order they were\n"
    "specified on the command line.");

namespace iree {
namespace {

iree_status_t GetModuleContentsFromFlags(std::string* out_contents) {
  IREE_TRACE_SCOPE0("GetModuleContentsFromFlags");
  auto module_file = std::string(FLAG_module_file);
  if (module_file == "-") {
    *out_contents = std::string{std::istreambuf_iterator<char>(std::cin),
                                std::istreambuf_iterator<char>()};
  } else {
    IREE_RETURN_IF_ERROR(GetFileContents(module_file.c_str(), out_contents));
  }
  return iree_ok_status();
}

iree_status_t Run() {
  IREE_TRACE_SCOPE0("iree-run-module");

  IREE_RETURN_IF_ERROR(iree_hal_module_register_types(),
                       "registering HAL types");
  iree_vm_instance_t* instance = nullptr;
  IREE_RETURN_IF_ERROR(
      iree_vm_instance_create(iree_allocator_system(), &instance),
      "creating instance");

  std::string module_data;
  IREE_RETURN_IF_ERROR(GetModuleContentsFromFlags(&module_data));
  iree_vm_module_t* input_module = nullptr;
  IREE_RETURN_IF_ERROR(iree_vm_bytecode_module_create(
      iree_make_const_byte_span((void*)module_data.data(), module_data.size()),
      iree_allocator_null(), iree_allocator_system(), &input_module));

  iree_hal_device_t* device = nullptr;
  IREE_RETURN_IF_ERROR(CreateDevice(FLAG_driver, &device));
  iree_vm_module_t* hal_module = nullptr;
  IREE_RETURN_IF_ERROR(
      iree_hal_module_create(device, iree_allocator_system(), &hal_module));

  iree_vm_context_t* context = nullptr;
  // Order matters. The input module will likely be dependent on the hal module.
  std::array<iree_vm_module_t*, 2> modules = {hal_module, input_module};
  IREE_RETURN_IF_ERROR(iree_vm_context_create_with_modules(
                           instance, modules.data(), modules.size(),
                           iree_allocator_system(), &context),
                       "creating context");

  std::string function_name = std::string(FLAG_entry_function);
  iree_vm_function_t function;
  if (function_name.empty()) {
    return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
                            "no --entry_function= specified");
  } else {
    IREE_RETURN_IF_ERROR(
        input_module->lookup_function(
            input_module->self, IREE_VM_FUNCTION_LINKAGE_EXPORT,
            iree_string_view_t{function_name.data(), function_name.size()},
            &function),
        "looking up function '%s'", function_name.c_str());
  }

  vm::ref<iree_vm_list_t> inputs;
  IREE_CHECK_OK(ParseToVariantList(
      iree_hal_device_allocator(device),
      iree::span<const std::string>{FLAG_function_inputs.data(),
                                    FLAG_function_inputs.size()},
      &inputs));

  vm::ref<iree_vm_list_t> outputs;
  IREE_RETURN_IF_ERROR(iree_vm_list_create(/*element_type=*/nullptr, 16,
                                           iree_allocator_system(), &outputs));

  std::cout << "EXEC @" << function_name << "\n";
  IREE_RETURN_IF_ERROR(
      iree_vm_invoke(context, function, /*policy=*/nullptr, inputs.get(),
                     outputs.get(), iree_allocator_system()),
      "invoking function '%s'", function_name.c_str());

  IREE_RETURN_IF_ERROR(PrintVariantList(outputs.get()), "printing results");

  inputs.reset();
  outputs.reset();
  iree_vm_module_release(hal_module);
  iree_vm_module_release(input_module);
  iree_hal_device_release(device);
  iree_vm_context_release(context);
  iree_vm_instance_release(instance);
  return iree_ok_status();
}

}  // namespace

extern "C" int main(int argc, char** argv) {
  iree_flags_parse_checked(IREE_FLAGS_PARSE_MODE_DEFAULT, &argc, &argv);
  IREE_CHECK_OK(iree_hal_register_all_available_drivers(
      iree_hal_driver_registry_default()));
  IREE_CHECK_OK(Run());
  return 0;
}

}  // namespace iree
<commit_msg>Update iree-run-module to error out with more than one positional argument. (#6334)<commit_after>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include <array>
#include <cstdio>
#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>

#include "iree/base/api.h"
#include "iree/base/internal/file_io.h"
#include "iree/base/internal/flags.h"
#include "iree/base/status_cc.h"
#include "iree/base/tracing.h"
#include "iree/hal/api.h"
#include "iree/hal/drivers/init.h"
#include "iree/modules/hal/module.h"
#include "iree/tools/utils/vm_util.h"
#include "iree/vm/api.h"
#include "iree/vm/bytecode_module.h"
#include "iree/vm/ref_cc.h"

IREE_FLAG(string, module_file, "-",
          "File containing the module to load that contains the entry "
          "function. Defaults to stdin.");

IREE_FLAG(string, entry_function, "",
          "Name of a function contained in the module specified by module_file "
          "to run.");

IREE_FLAG(string, driver, "vmvx", "Backend driver to use.");

static iree_status_t parse_function_input(iree_string_view_t flag_name,
                                          void* storage,
                                          iree_string_view_t value) {
  auto* list = (std::vector<std::string>*)storage;
  list->push_back(std::string(value.data, value.size));
  return iree_ok_status();
}
static void print_function_input(iree_string_view_t flag_name, void* storage,
                                 FILE* file) {
  auto* list = (std::vector<std::string>*)storage;
  if (list->empty()) {
    fprintf(file, "# --%.*s=\n", (int)flag_name.size, flag_name.data);
  } else {
    for (size_t i = 0; i < list->size(); ++i) {
      fprintf(file, "--%.*s=\"%s\"\n", (int)flag_name.size, flag_name.data,
              list->at(i).c_str());
    }
  }
}
static std::vector<std::string> FLAG_function_inputs;
IREE_FLAG_CALLBACK(
    parse_function_input, print_function_input, &FLAG_function_inputs,
    function_input,
    "An input value or buffer of the format:\n"
    "  [shape]xtype=[value]\n"
    "  2x2xi32=1 2 3 4\n"
    "Optionally, brackets may be used to separate the element values:\n"
    "  2x2xi32=[[1 2][3 4]]\n"
    "Each occurrence of the flag indicates an input in the order they were\n"
    "specified on the command line.");

namespace iree {
namespace {

iree_status_t GetModuleContentsFromFlags(std::string* out_contents) {
  IREE_TRACE_SCOPE0("GetModuleContentsFromFlags");
  auto module_file = std::string(FLAG_module_file);
  if (module_file == "-") {
    *out_contents = std::string{std::istreambuf_iterator<char>(std::cin),
                                std::istreambuf_iterator<char>()};
  } else {
    IREE_RETURN_IF_ERROR(GetFileContents(module_file.c_str(), out_contents));
  }
  return iree_ok_status();
}

iree_status_t Run() {
  IREE_TRACE_SCOPE0("iree-run-module");

  IREE_RETURN_IF_ERROR(iree_hal_module_register_types(),
                       "registering HAL types");
  iree_vm_instance_t* instance = nullptr;
  IREE_RETURN_IF_ERROR(
      iree_vm_instance_create(iree_allocator_system(), &instance),
      "creating instance");

  std::string module_data;
  IREE_RETURN_IF_ERROR(GetModuleContentsFromFlags(&module_data));
  iree_vm_module_t* input_module = nullptr;
  IREE_RETURN_IF_ERROR(iree_vm_bytecode_module_create(
      iree_make_const_byte_span((void*)module_data.data(), module_data.size()),
      iree_allocator_null(), iree_allocator_system(), &input_module));

  iree_hal_device_t* device = nullptr;
  IREE_RETURN_IF_ERROR(CreateDevice(FLAG_driver, &device));
  iree_vm_module_t* hal_module = nullptr;
  IREE_RETURN_IF_ERROR(
      iree_hal_module_create(device, iree_allocator_system(), &hal_module));

  iree_vm_context_t* context = nullptr;
  // Order matters. The input module will likely be dependent on the hal module.
  std::array<iree_vm_module_t*, 2> modules = {hal_module, input_module};
  IREE_RETURN_IF_ERROR(iree_vm_context_create_with_modules(
                           instance, modules.data(), modules.size(),
                           iree_allocator_system(), &context),
                       "creating context");

  std::string function_name = std::string(FLAG_entry_function);
  iree_vm_function_t function;
  if (function_name.empty()) {
    return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
                            "no --entry_function= specified");
  } else {
    IREE_RETURN_IF_ERROR(
        input_module->lookup_function(
            input_module->self, IREE_VM_FUNCTION_LINKAGE_EXPORT,
            iree_string_view_t{function_name.data(), function_name.size()},
            &function),
        "looking up function '%s'", function_name.c_str());
  }

  vm::ref<iree_vm_list_t> inputs;
  IREE_CHECK_OK(ParseToVariantList(
      iree_hal_device_allocator(device),
      iree::span<const std::string>{FLAG_function_inputs.data(),
                                    FLAG_function_inputs.size()},
      &inputs));

  vm::ref<iree_vm_list_t> outputs;
  IREE_RETURN_IF_ERROR(iree_vm_list_create(/*element_type=*/nullptr, 16,
                                           iree_allocator_system(), &outputs));

  std::cout << "EXEC @" << function_name << "\n";
  IREE_RETURN_IF_ERROR(
      iree_vm_invoke(context, function, /*policy=*/nullptr, inputs.get(),
                     outputs.get(), iree_allocator_system()),
      "invoking function '%s'", function_name.c_str());

  IREE_RETURN_IF_ERROR(PrintVariantList(outputs.get()), "printing results");

  inputs.reset();
  outputs.reset();
  iree_vm_module_release(hal_module);
  iree_vm_module_release(input_module);
  iree_hal_device_release(device);
  iree_vm_context_release(context);
  iree_vm_instance_release(instance);
  return iree_ok_status();
}

}  // namespace

extern "C" int main(int argc, char** argv) {
  iree_flags_parse_checked(IREE_FLAGS_PARSE_MODE_DEFAULT, &argc, &argv);
  if (argc > 1) {
    // Avoid iree-run-module spinning endlessly on stdin if the user uses single
    // dashes for flags.
    std::cout << "Error: unexpected positional argument (expected none)."
                 " Did you use pass a flag with a single dash ('-')?"
                 " Use '--' instead.\n";
    return 1;
  }
  IREE_CHECK_OK(iree_hal_register_all_available_drivers(
      iree_hal_driver_registry_default()));
  IREE_CHECK_OK(Run());
  return 0;
}

}  // namespace iree
<|endoftext|>


<commit_before>/* \author Geoffrey Biggs */

#include <iostream>

#include <boost/thread/thread.hpp>
#include "pcl/common/common_headers.h"
#include "pcl/common/common_headers.h"
#include "pcl/features/normal_3d.h"
#include "pcl/io/pcd_io.h"
#include "pcl/visualization/pcl_visualizer.h"
#include <pcl/console/parse.h>

// --------------
// -----Help-----
// --------------
void
printUsage (const char* progName)
{
  std::cout << "\n\nUsage: "<<progName<<" [options]\n\n"
            << "Options:\n"
            << "-------------------------------------------\n"
            << "-h           this help\n"
            << "-s           Simple visualisation example\n"
            << "-r           RGB colour visualisation example\n"
            << "-c           Custom colour visualisation example\n"
            << "-n           Normals visualisation example\n"
            << "-a           Shapes visualisation example\n"
            << "-v           Viewports example\n"
            << "\n\n";
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  viewer->addPointCloud (cloud, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> rgbVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> customColourVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(cloud, 0, 255, 0);
  viewer->addPointCloud<pcl::PointXYZ> (cloud, single_color, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> normalsVis (
    pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals)
{
  // --------------------------------------------------------
  // -----Open 3D viewer and add point cloud and normals-----
  // --------------------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
  viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals, 10, 0.05, "normals");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> shapesVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();

  //------------------------------------
  //-----Add shapes at cloud points-----
  //------------------------------------
  viewer->addLine<pcl::PointXYZRGB> (cloud->points[0],
                                     cloud->points[cloud->size() - 1], "line");
  viewer->addSphere (cloud->points[0], 0.2, 0.5, 0.5, 0.0, "sphere");

  //---------------------------------------
  //-----Add shapes at other locations-----
  //---------------------------------------
  pcl::ModelCoefficients coeffs;
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (1.0);
  coeffs.values.push_back (0.0);
  viewer->addPlane (coeffs, "plane");
  coeffs.values.clear ();
  coeffs.values.push_back (0.3);
  coeffs.values.push_back (0.3);
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (1.0);
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (5.0);
  viewer->addCone (coeffs, "cone");

  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> viewportsVis (
    pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals1, pcl::PointCloud<pcl::Normal>::ConstPtr normals2)
{
  // --------------------------------------------------------
  // -----Open 3D viewer and add point cloud and normals-----
  // --------------------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->initCameraParameters ();

  int v1(0);
  viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1);
  viewer->setBackgroundColor (0, 0, 0, v1);
  viewer->addText("Radius: 0.01", 10, 10, "v1 text", v1);
  pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud1", v1);

  int v2(0);
  viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2);
  viewer->setBackgroundColor (0.3, 0.3, 0.3, v2);
  viewer->addText("Radius: 0.1", 10, 10, "v2 text", v2);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> single_color(cloud, 0, 255, 0);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, single_color, "sample cloud2", v2);

  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud1");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud2");
  viewer->addCoordinateSystem (1.0);

  viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals1, 10, 0.05, "normals1", v1);
  viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals2, 10, 0.05, "normals2", v2);

  return (viewer);
}

// --------------
// -----Main-----
// --------------
int
main (int argc, char** argv)
{
  // --------------------------------------
  // -----Parse Command Line Arguments-----
  // --------------------------------------
  if (pcl::console::find_argument (argc, argv, "-h") >= 0)
  {
    printUsage (argv[0]);
    return 0;
  }
  bool simple(false), rgb(false), custom_c(false), normals(false),
    shapes(false), viewports(false);
  if (pcl::console::find_argument (argc, argv, "-s") >= 0)
  {
    simple = true;
    std::cout << "Simple visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-c") >= 0)
  {
    custom_c = true;
    std::cout << "Custom colour visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-r") >= 0)
  {
    rgb = true;
    std::cout << "RGB colour visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-n") >= 0)
  {
    normals = true;
    std::cout << "Normals visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-a") >= 0)
  {
    shapes = true;
    std::cout << "Shapes visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-v") >= 0)
  {
    viewports = true;
    std::cout << "Viewports example\n";
  }
  else
  {
    printUsage (argv[0]);
    return 0;
  }

  // ------------------------------------
  // -----Create example point cloud-----
  // ------------------------------------
  pcl::PointCloud<pcl::PointXYZ>::Ptr basic_cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>);
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr point_cloud_ptr (new pcl::PointCloud<pcl::PointXYZRGB>);
  std::cout << "Genarating example point clouds.\n\n";
  // We're going to make an ellipse extruded along the z-axis. The colour for
  // the XYZRGB cloud will gradually go from red to green to blue.
  uint8_t r(255), g(15), b(15);
  for (float z(-1.0); z <= 1.0; z += 0.05)
  {
    for (float angle(0.0); angle <= 360.0; angle += 5.0)
    {
      pcl::PointXYZ basic_point;
      basic_point.x = 0.5 * cosf (pcl::deg2rad(angle));
      basic_point.y = sinf (pcl::deg2rad(angle));
      basic_point.z = z;
      basic_cloud_ptr->points.push_back(basic_point);

      pcl::PointXYZRGB point;
      point.x = basic_point.x;
      point.y = basic_point.y;
      point.z = basic_point.z;
      uint32_t rgb = (static_cast<uint32_t>(r) << 16 |
              static_cast<uint32_t>(g) << 8 | static_cast<uint32_t>(b));
      point.rgb = *reinterpret_cast<float*>(&rgb);
      point_cloud_ptr->points.push_back (point);
    }
    if (z < 0.0)
    {
      r -= 12;
      g += 12;
    }
    else
    {
      g -= 12;
      b += 12;
    }
  }
  basic_cloud_ptr->width = basic_cloud_ptr->points.size ();
  basic_cloud_ptr->height = 1;
  point_cloud_ptr->width = point_cloud_ptr->points.size ();
  point_cloud_ptr->height = 1;

  // ----------------------------------------------------------------
  // -----Calculate surface normals with a search radius of 0.05-----
  // ----------------------------------------------------------------
  pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne;
  ne.setInputCloud (point_cloud_ptr);
  pcl::KdTreeFLANN<pcl::PointXYZRGB>::Ptr tree (new pcl::KdTreeFLANN<pcl::PointXYZRGB> ());
  ne.setSearchMethod (tree);
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals1 (new pcl::PointCloud<pcl::Normal>);
  ne.setRadiusSearch (0.05);
  ne.compute (*cloud_normals1);

  // ---------------------------------------------------------------
  // -----Calculate surface normals with a search radius of 0.1-----
  // ---------------------------------------------------------------
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2 (new pcl::PointCloud<pcl::Normal>);
  ne.setRadiusSearch (0.1);
  ne.compute (*cloud_normals2);

  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
  if (simple)
  {
    viewer = simpleVis(basic_cloud_ptr);
  }
  else if (rgb)
  {
    viewer = rgbVis(point_cloud_ptr);
  }
  else if (custom_c)
  {
    viewer = customColourVis(basic_cloud_ptr);
  }
  else if (normals)
  {
    viewer = normalsVis(point_cloud_ptr, cloud_normals2);
  }
  else if (shapes)
  {
    viewer = shapesVis(point_cloud_ptr);
  }
  else if (viewports)
  {
    viewer = viewportsVis(point_cloud_ptr, cloud_normals1, cloud_normals2);
  }

  //--------------------
  // -----Main loop-----
  //--------------------
  while (!viewer->wasStopped ())
  {
    viewer->spinOnce (100);
    boost::this_thread::sleep (boost::posix_time::microseconds (100000));
  }
}

<commit_msg>changed name of file back to original<commit_after>/* \author Geoffrey Biggs */

#include <iostream>

#include <boost/thread/thread.hpp>
#include "pcl/common/common_headers.h"
#include "pcl/common/common_headers.h"
#include "pcl/features/normal_3d.h"
#include "pcl/io/pcd_io.h"
#include "pcl/visualization/pcl_visualizer.h"
#include <pcl/console/parse.h>

// --------------
// -----Help-----
// --------------
void
printUsage (const char* progName)
{
  std::cout << "\n\nUsage: "<<progName<<" [options]\n\n"
            << "Options:\n"
            << "-------------------------------------------\n"
            << "-h           this help\n"
            << "-s           Simple visualisation example\n"
            << "-r           RGB colour visualisation example\n"
            << "-c           Custom colour visualisation example\n"
            << "-n           Normals visualisation example\n"
            << "-a           Shapes visualisation example\n"
            << "-v           Viewports example\n"
            << "\n\n";
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  viewer->addPointCloud<pcl::PointXYZ> (cloud, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> rgbVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> customColourVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(cloud, 0, 255, 0);
  viewer->addPointCloud<pcl::PointXYZ> (cloud, single_color, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> normalsVis (
    pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals)
{
  // --------------------------------------------------------
  // -----Open 3D viewer and add point cloud and normals-----
  // --------------------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
  viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals, 10, 0.05, "normals");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> shapesVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();

  //------------------------------------
  //-----Add shapes at cloud points-----
  //------------------------------------
  viewer->addLine<pcl::PointXYZRGB> (cloud->points[0],
                                     cloud->points[cloud->size() - 1], "line");
  viewer->addSphere (cloud->points[0], 0.2, 0.5, 0.5, 0.0, "sphere");

  //---------------------------------------
  //-----Add shapes at other locations-----
  //---------------------------------------
  pcl::ModelCoefficients coeffs;
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (1.0);
  coeffs.values.push_back (0.0);
  viewer->addPlane (coeffs, "plane");
  coeffs.values.clear ();
  coeffs.values.push_back (0.3);
  coeffs.values.push_back (0.3);
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (1.0);
  coeffs.values.push_back (0.0);
  coeffs.values.push_back (5.0);
  viewer->addCone (coeffs, "cone");

  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> viewportsVis (
    pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals1, pcl::PointCloud<pcl::Normal>::ConstPtr normals2)
{
  // --------------------------------------------------------
  // -----Open 3D viewer and add point cloud and normals-----
  // --------------------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->initCameraParameters ();

  int v1(0);
  viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1);
  viewer->setBackgroundColor (0, 0, 0, v1);
  viewer->addText("Radius: 0.01", 10, 10, "v1 text", v1);
  pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud1", v1);

  int v2(0);
  viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2);
  viewer->setBackgroundColor (0.3, 0.3, 0.3, v2);
  viewer->addText("Radius: 0.1", 10, 10, "v2 text", v2);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> single_color(cloud, 0, 255, 0);
  viewer->addPointCloud<pcl::PointXYZRGB> (cloud, single_color, "sample cloud2", v2);

  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud1");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud2");
  viewer->addCoordinateSystem (1.0);

  viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals1, 10, 0.05, "normals1", v1);
  viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals2, 10, 0.05, "normals2", v2);

  return (viewer);
}

// --------------
// -----Main-----
// --------------
int
main (int argc, char** argv)
{
  // --------------------------------------
  // -----Parse Command Line Arguments-----
  // --------------------------------------
  if (pcl::console::find_argument (argc, argv, "-h") >= 0)
  {
    printUsage (argv[0]);
    return 0;
  }
  bool simple(false), rgb(false), custom_c(false), normals(false),
    shapes(false), viewports(false);
  if (pcl::console::find_argument (argc, argv, "-s") >= 0)
  {
    simple = true;
    std::cout << "Simple visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-c") >= 0)
  {
    custom_c = true;
    std::cout << "Custom colour visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-r") >= 0)
  {
    rgb = true;
    std::cout << "RGB colour visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-n") >= 0)
  {
    normals = true;
    std::cout << "Normals visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-a") >= 0)
  {
    shapes = true;
    std::cout << "Shapes visualisation example\n";
  }
  else if (pcl::console::find_argument (argc, argv, "-v") >= 0)
  {
    viewports = true;
    std::cout << "Viewports example\n";
  }
  else
  {
    printUsage (argv[0]);
    return 0;
  }

  // ------------------------------------
  // -----Create example point cloud-----
  // ------------------------------------
  pcl::PointCloud<pcl::PointXYZ>::Ptr basic_cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>);
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr point_cloud_ptr (new pcl::PointCloud<pcl::PointXYZRGB>);
  std::cout << "Genarating example point clouds.\n\n";
  // We're going to make an ellipse extruded along the z-axis. The colour for
  // the XYZRGB cloud will gradually go from red to green to blue.
  uint8_t r(255), g(15), b(15);
  for (float z(-1.0); z <= 1.0; z += 0.05)
  {
    for (float angle(0.0); angle <= 360.0; angle += 5.0)
    {
      pcl::PointXYZ basic_point;
      basic_point.x = 0.5 * cosf (pcl::deg2rad(angle));
      basic_point.y = sinf (pcl::deg2rad(angle));
      basic_point.z = z;
      basic_cloud_ptr->points.push_back(basic_point);

      pcl::PointXYZRGB point;
      point.x = basic_point.x;
      point.y = basic_point.y;
      point.z = basic_point.z;
      uint32_t rgb = (static_cast<uint32_t>(r) << 16 |
              static_cast<uint32_t>(g) << 8 | static_cast<uint32_t>(b));
      point.rgb = *reinterpret_cast<float*>(&rgb);
      point_cloud_ptr->points.push_back (point);
    }
    if (z < 0.0)
    {
      r -= 12;
      g += 12;
    }
    else
    {
      g -= 12;
      b += 12;
    }
  }
  basic_cloud_ptr->width = basic_cloud_ptr->points.size ();
  basic_cloud_ptr->height = 1;
  point_cloud_ptr->width = point_cloud_ptr->points.size ();
  point_cloud_ptr->height = 1;

  // ----------------------------------------------------------------
  // -----Calculate surface normals with a search radius of 0.05-----
  // ----------------------------------------------------------------
  pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne;
  ne.setInputCloud (point_cloud_ptr);
  pcl::KdTreeFLANN<pcl::PointXYZRGB>::Ptr tree (new pcl::KdTreeFLANN<pcl::PointXYZRGB> ());
  ne.setSearchMethod (tree);
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals1 (new pcl::PointCloud<pcl::Normal>);
  ne.setRadiusSearch (0.05);
  ne.compute (*cloud_normals1);

  // ---------------------------------------------------------------
  // -----Calculate surface normals with a search radius of 0.1-----
  // ---------------------------------------------------------------
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2 (new pcl::PointCloud<pcl::Normal>);
  ne.setRadiusSearch (0.1);
  ne.compute (*cloud_normals2);

  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
  if (simple)
  {
    viewer = simpleVis(basic_cloud_ptr);
  }
  else if (rgb)
  {
    viewer = rgbVis(point_cloud_ptr);
  }
  else if (custom_c)
  {
    viewer = customColourVis(basic_cloud_ptr);
  }
  else if (normals)
  {
    viewer = normalsVis(point_cloud_ptr, cloud_normals2);
  }
  else if (shapes)
  {
    viewer = shapesVis(point_cloud_ptr);
  }
  else if (viewports)
  {
    viewer = viewportsVis(point_cloud_ptr, cloud_normals1, cloud_normals2);
  }

  //--------------------
  // -----Main loop-----
  //--------------------
  while (!viewer->wasStopped ())
  {
    viewer->spinOnce (100);
    boost::this_thread::sleep (boost::posix_time::microseconds (100000));
  }
}

<|endoftext|>