<commit_before>#include "WindowEmscripten.hpp"

#include "OE/Application/InputManager.hpp"
#include "OE/Misc/Log.hpp"

namespace OrbitEngine {	namespace Application { namespace priv {
	WindowEmscripten::WindowEmscripten()
		: WindowImpl()
	{
		updateSizeFromHTML();

    	emscripten_set_fullscreenchange_callback("#document", this, 0, EMS_Callback_FullscreenChange);
		emscripten_set_resize_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_ResizeCanvas);
		emscripten_set_focus_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Focus);
		emscripten_set_blur_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Focus);

		emscripten_set_keypress_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_KeyPress);
		emscripten_set_keydown_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Key);
		emscripten_set_keyup_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Key);
		emscripten_set_wheel_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Wheel);
		emscripten_set_mousemove_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_MouseMove);
		emscripten_set_mouseup_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_MouseButton);
		emscripten_set_mousedown_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_MouseButton);

		// Do we start with the focus?
		p_Focused = true;
	}

	void WindowEmscripten::processEvents()
	{
		m_PointerLock = isPointerLockActive();
		//p_InputManager->m_CursorMode = m_PointerLock ? CursorMode::GRABBED : CursorMode::NORMAL;

		WindowImpl::processEvents();
	}

	WindowEmscripten::~WindowEmscripten()
	{

	}

	bool WindowEmscripten::isMinimized() const
	{
		// TODO: This can be done
		return false;
	}

	bool WindowEmscripten::setDisplayMode(DisplayMode mode)
	{
		// TODO: !
		return true;
	}

	bool WindowEmscripten::setCursor(Cursor cursor)
	{
		std::string script = "Module.canvas.style.cursor = \"" + CursorToCSS(cursor) + "\";";
		emscripten_run_script(script.c_str());
		return true;
	}

	bool WindowEmscripten::setTitle(const std::string& title)
	{
		// TODO: change document.title?
		return false;
	}

	bool WindowEmscripten::setPosition(const Math::Vec2i& position)
	{
		// not valid
		return false;
	}

	bool WindowEmscripten::setSize(const Math::Vec2i& size)
	{
		// not valid
		return false;
	}

	bool WindowEmscripten::setVisibility(bool visible)
	{
		// TODO: set display: none?
		return true;
	}

	bool WindowEmscripten::requestFocus()
	{
		// TODO?
		return true;
	}

	bool WindowEmscripten::setAlpha(float alpha)
	{
		// not valid
		return false;
	}

	WindowNativeHandle WindowEmscripten::getWindowNativeHandle()
	{
		return 0;
	}

	DisplayNativeHandle WindowEmscripten::getDisplayNativeHandle()
	{
		return 0;
	}

	/*
	void WindowEmscripten::requestCursorMode(const CursorMode cursorMode) {
		if(cursorMode == CursorMode::GRABBED){
			emscripten_request_pointerlock(NULL, true);
		}
	}
	*/

	bool WindowEmscripten::isPointerLockActive(){
	    EmscriptenPointerlockChangeEvent pointerlockStatus;
	    emscripten_get_pointerlock_status(&pointerlockStatus);
		return pointerlockStatus.isActive;
	}

	void WindowEmscripten::updateSizeFromHTML(){
		//double pixel_ratio = emscripten_get_device_pixel_ratio(); Use it?
		double w = p_Size.x;
		double h = p_Size.y;

		if(p_DisplayMode != DisplayMode::FULLSCREEN){
			// If we are not in fullscreen, we use the css size values
			emscripten_get_element_css_size(NULL, &w, &h);
		} else {
			// If we are in fullscreen we use the window inner dimensions
			w = EM_ASM_INT_V({
				return window.innerWidth;
			});

			h = EM_ASM_INT_V({
				return window.innerHeight;
			});
		}

		emscripten_set_canvas_size(w, h);

		p_Size = Math::Vec2i(w, h);
	}

	EM_BOOL WindowEmscripten::EMS_Callback_FullscreenChange(int eventType, const EmscriptenFullscreenChangeEvent *fullscreenChangeEvent, void *userData) {
		WindowEmscripten* window = static_cast<WindowEmscripten*>(userData);
		if(fullscreenChangeEvent->isFullscreen)
			window->p_DisplayMode = DisplayMode::FULLSCREEN;
		else
			window->p_DisplayMode = DisplayMode::WINDOWED;
		window->updateSizeFromHTML();
	}

	EM_BOOL WindowEmscripten::EMS_Callback_ResizeCanvas(int eventType, const EmscriptenUiEvent *uiEvent, void *userData) {
		WindowEmscripten* window = static_cast<WindowEmscripten*>(userData);
		window->updateSizeFromHTML();
	}

	EM_BOOL WindowEmscripten::EMS_Callback_Focus(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData) {
		WindowEmscripten* window = static_cast<WindowEmscripten*>(userData);
		window->p_Focused = eventType == EMSCRIPTEN_EVENT_FOCUS;
	}

	EM_BOOL WindowEmscripten::EMS_Callback_Key(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData) {
		if (keyEvent->keyCode < OE_MAX_KEYS) {
			Key key = Key(keyEvent->keyCode);
			InputManager::Get()->onInputKey(key, eventType == EMSCRIPTEN_EVENT_KEYDOWN);
			bool isNavKey = key == Key::BACKSPACE ||
							key == Key::TAB;
			return isNavKey;
		}
	}

	EM_BOOL OrbitEngine::Application::priv::WindowEmscripten::EMS_Callback_KeyPress(int eventType, const EmscriptenKeyboardEvent* keyEvent, void* userData)
	{
		InputManager::Get()->onInputChar((unsigned int)keyEvent->charCode);
	}

	EM_BOOL WindowEmscripten::EMS_Callback_Wheel(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData) {
		InputManager::Get()->onInputWheel((float)wheelEvent->deltaY / -120.0f);
	}

	EM_BOOL WindowEmscripten::EMS_Callback_MouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) {
		WindowEmscripten* window = static_cast<WindowEmscripten*>(userData);
		if(window->m_PointerLock){
			InputManager::Get()->onInputMouseMove(-mouseEvent->movementX, -mouseEvent->movementY, true);
		} else {
			InputManager::Get()->onInputMouseMove(mouseEvent->canvasX, mouseEvent->canvasY);
		}
	}

	EM_BOOL WindowEmscripten::EMS_Callback_MouseButton(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) {
		Button btn;
		switch (mouseEvent->button) {
		default:
		case 0: btn = Button::LEFT; break;
		case 1: btn = Button::MIDDLE; break;
		case 2: btn = Button::RIGHT; break;
		}
		InputManager::Get()->onInputMouseButton(btn, eventType == EMSCRIPTEN_EVENT_MOUSEDOWN);
	}

	std::string WindowEmscripten::CursorToCSS(const Cursor cursor){
		switch(cursor){
		default:
		case DEFAULT:
		case ARROW:
			return "";
		case CROSS:
			return "crosshair";
		case HOURGLASS:
			return "wait";
		case HAND:
			return "pointer";
		case NO:
			return "not-allowed";
		case SIZEALL:
			return "move";
		case SIZENS:
			return "n-resize";
		case SIZEWE:
			return "w-resize";
		case SIZENWSE:
			return "se-resize";
		}
	}

} } }<commit_msg>Prevent emscripten to consume key events<commit_after>#include "WindowEmscripten.hpp"

#include "OE/Application/InputManager.hpp"
#include "OE/Misc/Log.hpp"

namespace OrbitEngine {	namespace Application { namespace priv {
	WindowEmscripten::WindowEmscripten()
		: WindowImpl()
	{
		updateSizeFromHTML();

    	emscripten_set_fullscreenchange_callback("#document", this, 0, EMS_Callback_FullscreenChange);
		emscripten_set_resize_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_ResizeCanvas);
		emscripten_set_focus_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Focus);
		emscripten_set_blur_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Focus);

		emscripten_set_keypress_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_KeyPress);
		emscripten_set_keydown_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Key);
		emscripten_set_keyup_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Key);
		emscripten_set_wheel_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_Wheel);
		emscripten_set_mousemove_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_MouseMove);
		emscripten_set_mouseup_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_MouseButton);
		emscripten_set_mousedown_callback(NULL, this, false, &WindowEmscripten::EMS_Callback_MouseButton);

		// Do we start with the focus?
		p_Focused = true;
	}

	void WindowEmscripten::processEvents()
	{
		m_PointerLock = isPointerLockActive();
		//p_InputManager->m_CursorMode = m_PointerLock ? CursorMode::GRABBED : CursorMode::NORMAL;

		WindowImpl::processEvents();
	}

	WindowEmscripten::~WindowEmscripten()
	{

	}

	bool WindowEmscripten::isMinimized() const
	{
		// TODO: This can be done
		return false;
	}

	bool WindowEmscripten::setDisplayMode(DisplayMode mode)
	{
		// TODO: !
		return true;
	}

	bool WindowEmscripten::setCursor(Cursor cursor)
	{
		std::string script = "Module.canvas.style.cursor = \"" + CursorToCSS(cursor) + "\";";
		emscripten_run_script(script.c_str());
		return true;
	}

	bool WindowEmscripten::setTitle(const std::string& title)
	{
		// TODO: change document.title?
		return false;
	}

	bool WindowEmscripten::setPosition(const Math::Vec2i& position)
	{
		// not valid
		return false;
	}

	bool WindowEmscripten::setSize(const Math::Vec2i& size)
	{
		// not valid
		return false;
	}

	bool WindowEmscripten::setVisibility(bool visible)
	{
		// TODO: set display: none?
		return true;
	}

	bool WindowEmscripten::requestFocus()
	{
		// TODO?
		return true;
	}

	bool WindowEmscripten::setAlpha(float alpha)
	{
		// not valid
		return false;
	}

	WindowNativeHandle WindowEmscripten::getWindowNativeHandle()
	{
		return 0;
	}

	DisplayNativeHandle WindowEmscripten::getDisplayNativeHandle()
	{
		return 0;
	}

	/*
	void WindowEmscripten::requestCursorMode(const CursorMode cursorMode) {
		if(cursorMode == CursorMode::GRABBED){
			emscripten_request_pointerlock(NULL, true);
		}
	}
	*/

	bool WindowEmscripten::isPointerLockActive(){
	    EmscriptenPointerlockChangeEvent pointerlockStatus;
	    emscripten_get_pointerlock_status(&pointerlockStatus);
		return pointerlockStatus.isActive;
	}

	void WindowEmscripten::updateSizeFromHTML(){
		//double pixel_ratio = emscripten_get_device_pixel_ratio(); Use it?
		double w = p_Size.x;
		double h = p_Size.y;

		if(p_DisplayMode != DisplayMode::FULLSCREEN){
			// If we are not in fullscreen, we use the css size values
			emscripten_get_element_css_size(NULL, &w, &h);
		} else {
			// If we are in fullscreen we use the window inner dimensions
			w = EM_ASM_INT_V({
				return window.innerWidth;
			});

			h = EM_ASM_INT_V({
				return window.innerHeight;
			});
		}

		emscripten_set_canvas_size(w, h);

		p_Size = Math::Vec2i(w, h);
	}

	EM_BOOL WindowEmscripten::EMS_Callback_FullscreenChange(int eventType, const EmscriptenFullscreenChangeEvent *fullscreenChangeEvent, void *userData) {
		WindowEmscripten* window = static_cast<WindowEmscripten*>(userData);
		if(fullscreenChangeEvent->isFullscreen)
			window->p_DisplayMode = DisplayMode::FULLSCREEN;
		else
			window->p_DisplayMode = DisplayMode::WINDOWED;
		window->updateSizeFromHTML();
	}

	EM_BOOL WindowEmscripten::EMS_Callback_ResizeCanvas(int eventType, const EmscriptenUiEvent *uiEvent, void *userData) {
		WindowEmscripten* window = static_cast<WindowEmscripten*>(userData);
		window->updateSizeFromHTML();
	}

	EM_BOOL WindowEmscripten::EMS_Callback_Focus(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData) {
		WindowEmscripten* window = static_cast<WindowEmscripten*>(userData);
		window->p_Focused = eventType == EMSCRIPTEN_EVENT_FOCUS;
	}

	EM_BOOL WindowEmscripten::EMS_Callback_Key(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData) {
		if (keyEvent->keyCode < OE_MAX_KEYS) {
			Key key = Key(keyEvent->keyCode);
			InputManager::Get()->onInputKey(key, eventType == EMSCRIPTEN_EVENT_KEYDOWN);
			//bool isNavKey = key == Key::BACKSPACE ||
			//				key == Key::TAB;
			//return isNavKey;
		}
	}

	EM_BOOL OrbitEngine::Application::priv::WindowEmscripten::EMS_Callback_KeyPress(int eventType, const EmscriptenKeyboardEvent* keyEvent, void* userData)
	{
		InputManager::Get()->onInputChar((unsigned int)keyEvent->charCode);
	}

	EM_BOOL WindowEmscripten::EMS_Callback_Wheel(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData) {
		InputManager::Get()->onInputWheel((float)wheelEvent->deltaY / -120.0f);
	}

	EM_BOOL WindowEmscripten::EMS_Callback_MouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) {
		WindowEmscripten* window = static_cast<WindowEmscripten*>(userData);
		if(window->m_PointerLock){
			InputManager::Get()->onInputMouseMove(-mouseEvent->movementX, -mouseEvent->movementY, true);
		} else {
			InputManager::Get()->onInputMouseMove(mouseEvent->canvasX, mouseEvent->canvasY);
		}
	}

	EM_BOOL WindowEmscripten::EMS_Callback_MouseButton(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) {
		Button btn;
		switch (mouseEvent->button) {
		default:
		case 0: btn = Button::LEFT; break;
		case 1: btn = Button::MIDDLE; break;
		case 2: btn = Button::RIGHT; break;
		}
		InputManager::Get()->onInputMouseButton(btn, eventType == EMSCRIPTEN_EVENT_MOUSEDOWN);
	}

	std::string WindowEmscripten::CursorToCSS(const Cursor cursor){
		switch(cursor){
		default:
		case DEFAULT:
		case ARROW:
			return "";
		case CROSS:
			return "crosshair";
		case HOURGLASS:
			return "wait";
		case HAND:
			return "pointer";
		case NO:
			return "not-allowed";
		case SIZEALL:
			return "move";
		case SIZENS:
			return "n-resize";
		case SIZEWE:
			return "w-resize";
		case SIZENWSE:
			return "se-resize";
		}
	}

} } }<|endoftext|>


<commit_before>// $Id$
//****************************************************************************
//* This file is property of and copyright by the ALICE HLT Project          *
//* ALICE Experiment at CERN, All rights reserved.                           *
//*                                                                          *
//* Primary Authors: Sergey Gorbunov, Torsten Alt                            *
//* Developers:      Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de> *
//*                  Torsten Alt <talt@cern.ch>                              *
//*                  for The ALICE HLT Project.                              *
//*                                                                          *
//* Permission to use, copy, modify and distribute this software and its     *
//* documentation strictly for non-commercial purposes is hereby granted     *
//* without fee, provided that the above copyright notice appears in all     *
//* copies and that both the copyright notice and this permission notice     *
//* appear in the supporting documentation. The authors make no claims       *
//* about the suitability of this software for any purpose. It is            *
//* provided "as is" without express or implied warranty.                    *
//****************************************************************************

//  @file   AliHLTTPCHWCFProcessorUnit.cxx
//  @author Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de>
//  @author Torsten Alt <talt@cern.ch>
//  @date
//  @brief  Channel Processor unit of FPGA ClusterFinder Emulator for TPC
//  @brief  ( see AliHLTTPCHWCFEmulator class )
//  @note

#include "AliHLTTPCHWCFProcessorUnit.h"
#include <iostream>
#include <cstdio>

AliHLTTPCHWCFProcessorUnit::AliHLTTPCHWCFProcessorUnit()
  :
  fOutput(),
  fkBunch(0),
  fBunchIndex(0),
  fWasDeconvoluted(0),
  fDeconvolute(0),
  fImprovedDeconvolution(0),
  fSingleSeqLimit(0),
  fUseTimeBinWindow(0),
  fDebug(0)
{
  //constructor
  Init();
}

AliHLTTPCHWCFProcessorUnit::~AliHLTTPCHWCFProcessorUnit()
{
  //destructor
}

AliHLTTPCHWCFProcessorUnit::AliHLTTPCHWCFProcessorUnit(const AliHLTTPCHWCFProcessorUnit&)
  :
  fOutput(),
  fkBunch(0),
  fBunchIndex(0),
  fWasDeconvoluted(0),
  fDeconvolute(0),
  fImprovedDeconvolution(0),
  fSingleSeqLimit(0),
  fUseTimeBinWindow(0),
  fDebug(0)
{
  // dummy
  Init();
}

AliHLTTPCHWCFProcessorUnit& AliHLTTPCHWCFProcessorUnit::operator=(const AliHLTTPCHWCFProcessorUnit&)
{
  // dummy
  return *this;
}

int AliHLTTPCHWCFProcessorUnit::Init()
{
  // initialise

  fkBunch = 0;
  fBunchIndex = 0;
  fWasDeconvoluted = 0;
  return 0;
}

int AliHLTTPCHWCFProcessorUnit::InputStream( const AliHLTTPCHWCFBunch *bunch )
{
  // input stream of data

  if( bunch && fDebug ){
    printf("\nHWCF Processor: input bunch F %1d R %3d P %3d  NS %2ld:\n",
	   bunch->fFlag, bunch->fRow, bunch->fPad, bunch->fData.size());
    for( unsigned int i=0; i<bunch->fData.size(); i++ ){
      AliHLTTPCHWCFDigit d =  bunch->fData[i];
      printf("   q %2d t %3d peak %2d ", d.fQ, d.fTime, d.fPeak);
       printf("(");
      for( int j=0; j<3; j++ ) printf(" {%d,%2.0f}",d.fMC.fClusterID[j].fMCID, d.fMC.fClusterID[j].fWeight );
      printf(" )\n");
    }
  }

  fkBunch = bunch;
  fBunchIndex = 0;
  fWasDeconvoluted = 0;
  return 0;
}

const AliHLTTPCHWCFClusterFragment *AliHLTTPCHWCFProcessorUnit::OutputStream()
{
  // output stream of data

  //const AliHLTUInt32_t kTimeBinWindow = 5;
  const AliHLTUInt32_t kHalfTimeBinWindow = 2;

  if( !fkBunch ) return 0;

  fOutput.fFlag = fkBunch->fFlag;
  fOutput.fRow = fkBunch->fRow;
  fOutput.fPad = fkBunch->fPad;
  fOutput.fBranch = fkBunch->fBranch;
  fOutput.fBorder = fkBunch->fBorder;
  fOutput.fEdge = 0; //Set below with some more constraints
  fOutput.fQmax = 0;
  fOutput.fQ = 0;
  fOutput.fT = 0;
  fOutput.fT2 = 0;
  fOutput.fP = 0;
  fOutput.fP2 = 0;
  fOutput.fTMean = 0;
  fOutput.fNPads = 0;
  fOutput.fNDeconvolutedTime = 0;
  fOutput.fIsDeconvolutedPad = 0;
  fOutput.fConsecutiveTimeDeconvolution = 0;
  fOutput.fLargestQ = 0;
  fOutput.fLargestQ2 = 0;
  fOutput.fLargestQPad = 0;
  fOutput.fMC.clear();

  if( fkBunch->fFlag==2 && fkBunch->fData.size()==1 ){ // rcu trailer word, forward it
    fOutput.fRow = fkBunch->fData[0].fQ;
  }

  if( fkBunch->fFlag >1 ){
    fkBunch = 0;
    return &fOutput;
  }

  if( fkBunch->fFlag < 1 ) return 0;

  if( fBunchIndex >= fkBunch->fData.size() ) return 0;

  AliHLTUInt32_t iStart = fBunchIndex;
  AliHLTUInt32_t iPeak = fBunchIndex;
  AliHLTUInt32_t qPeak = 0;

  // find next/best peak

  for( ; fBunchIndex<fkBunch->fData.size(); fBunchIndex++ ){
    const AliHLTTPCHWCFDigit &d = fkBunch->fData[fBunchIndex];
    if( d.fPeak != 1 ) continue;
    if( fDeconvolute ){
      iPeak = fBunchIndex;
      qPeak = d.fQ;
      fBunchIndex++;
      break;
    } else {
      if( d.fQ>qPeak ){
	qPeak = d.fQ;
	iPeak = fBunchIndex;
      }
    }
  }

  if( qPeak == 0 ) return 0;

  // find next minimum !!! At the moment the minimum finder is on only when no timebin window set

  bool isDeconvoluted = 0;

  if( !fUseTimeBinWindow ){
    for( ; fBunchIndex<fkBunch->fData.size(); fBunchIndex++ ){
      if( fDeconvolute ){
	if( fkBunch->fData[fBunchIndex].fPeak != 0 ){
	  fBunchIndex++;
	  break;
	}
      }
    }
    if( fBunchIndex<fkBunch->fData.size() ) isDeconvoluted = 1;
  } else {
    if( !fDeconvolute ){
      fBunchIndex = fkBunch->fData.size();
    } else if ( fImprovedDeconvolution) {
      fWasDeconvoluted = 0;
      for ( int i = std::max((int) iStart, (int) (iPeak - kHalfTimeBinWindow)); i < iPeak; i++) {
        if ( fkBunch->fData[i].fPeak == 2 )
        {
          iStart = i + 1;
          fWasDeconvoluted = 1;
        }
      }
      //Do not mark as deconvoluted when iPeak + 2 is a minimum (because we use that sample), do not consider minima add end of bunch!
      for ( ; fBunchIndex < fkBunch->fData.size(); fBunchIndex++ ) {
        if (fBunchIndex == iPeak + kHalfTimeBinWindow)
        {
          fBunchIndex++;
          break;
        }
        if (fkBunch->fData[fBunchIndex].fPeak == 2) {
          if (fBunchIndex + 1 != fkBunch->fData.size()) isDeconvoluted = 1;
          fBunchIndex++;
          break;
        }
      }
    } else {
      // find next peak
      if( fBunchIndex+1<fkBunch->fData.size() && fkBunch->fData[fBunchIndex+1].fPeak==1 ){
	fBunchIndex = fBunchIndex+1;
	isDeconvoluted = 1;
      } else   if( fBunchIndex+2<fkBunch->fData.size() && fkBunch->fData[fBunchIndex+2].fPeak==1 ){
	fBunchIndex = fBunchIndex+1;
	isDeconvoluted = 1;
      } else   if( fBunchIndex+3<fkBunch->fData.size() && fkBunch->fData[fBunchIndex+3].fPeak==1 ){
	fBunchIndex = fBunchIndex+2;
	isDeconvoluted = 1;
      } else   if( fBunchIndex+1<fkBunch->fData.size() ){
	fBunchIndex = fBunchIndex+2;
      } else   if( fBunchIndex<fkBunch->fData.size() ){
	fBunchIndex = fBunchIndex+1;
      }
    }
  }

  AliHLTUInt32_t iEnd = fBunchIndex;

  if( fUseTimeBinWindow ){
    if( iPeak > iStart + kHalfTimeBinWindow ) iStart = iPeak - kHalfTimeBinWindow;
    if( iEnd  > iPeak + kHalfTimeBinWindow + 1) iEnd = iPeak + kHalfTimeBinWindow + 1;
  }

  fOutput.fQmax = qPeak*fkBunch->fGain;
  fOutput.fQ = 0;
  fOutput.fT = 0;
  fOutput.fT2 = 0;
  fOutput.fP = 0;
  fOutput.fP2 = 0;
  fOutput.fTMean = fkBunch->fData[iPeak].fTime;
  fOutput.fNPads = 1;
  fOutput.fNDeconvolutedTime = ( fWasDeconvoluted || isDeconvoluted ) ? 1 :0;
  fOutput.fConsecutiveTimeDeconvolution = fOutput.fNDeconvolutedTime;
  fOutput.fMC.clear();

  fWasDeconvoluted = isDeconvoluted;

  for( AliHLTUInt32_t i=iStart; i<iEnd; i++ ){
    const AliHLTTPCHWCFDigit &d = fkBunch->fData[i];
    AliHLTUInt64_t q = d.fQ*fkBunch->fGain;
    fOutput.fQ += q;
    fOutput.fT += q*d.fTime;
    fOutput.fT2+= q*d.fTime*d.fTime;
    fOutput.fP += q*fkBunch->fPad;
    fOutput.fP2+= q*fkBunch->fPad*fkBunch->fPad;
    fOutput.fMC.push_back(d.fMC);
  }
  fOutput.fEdge = fkBunch->fEdge && iEnd > iStart + 2 && qPeak > 5;
  fOutput.fLargestQ = fOutput.fQ;
  fOutput.fLargestQPad = fkBunch->fEdge ? fkBunch->fPad : 0xFFFFFFFF; //We only correct if the largest charge is at the edge cluster. Mark other pads as -1

  if( fkBunch->fData.size()==1 && fOutput.fQ < fSingleSeqLimit ) return 0;

  return &fOutput;
}
<commit_msg>fix assignment of qMax in HWCF with smoothing<commit_after>// $Id$
//****************************************************************************
//* This file is property of and copyright by the ALICE HLT Project          *
//* ALICE Experiment at CERN, All rights reserved.                           *
//*                                                                          *
//* Primary Authors: Sergey Gorbunov, Torsten Alt                            *
//* Developers:      Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de> *
//*                  Torsten Alt <talt@cern.ch>                              *
//*                  for The ALICE HLT Project.                              *
//*                                                                          *
//* Permission to use, copy, modify and distribute this software and its     *
//* documentation strictly for non-commercial purposes is hereby granted     *
//* without fee, provided that the above copyright notice appears in all     *
//* copies and that both the copyright notice and this permission notice     *
//* appear in the supporting documentation. The authors make no claims       *
//* about the suitability of this software for any purpose. It is            *
//* provided "as is" without express or implied warranty.                    *
//****************************************************************************

//  @file   AliHLTTPCHWCFProcessorUnit.cxx
//  @author Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de>
//  @author Torsten Alt <talt@cern.ch>
//  @date
//  @brief  Channel Processor unit of FPGA ClusterFinder Emulator for TPC
//  @brief  ( see AliHLTTPCHWCFEmulator class )
//  @note

#include "AliHLTTPCHWCFProcessorUnit.h"
#include <iostream>
#include <cstdio>

AliHLTTPCHWCFProcessorUnit::AliHLTTPCHWCFProcessorUnit()
  :
  fOutput(),
  fkBunch(0),
  fBunchIndex(0),
  fWasDeconvoluted(0),
  fDeconvolute(0),
  fImprovedDeconvolution(0),
  fSingleSeqLimit(0),
  fUseTimeBinWindow(0),
  fDebug(0)
{
  //constructor
  Init();
}

AliHLTTPCHWCFProcessorUnit::~AliHLTTPCHWCFProcessorUnit()
{
  //destructor
}

AliHLTTPCHWCFProcessorUnit::AliHLTTPCHWCFProcessorUnit(const AliHLTTPCHWCFProcessorUnit&)
  :
  fOutput(),
  fkBunch(0),
  fBunchIndex(0),
  fWasDeconvoluted(0),
  fDeconvolute(0),
  fImprovedDeconvolution(0),
  fSingleSeqLimit(0),
  fUseTimeBinWindow(0),
  fDebug(0)
{
  // dummy
  Init();
}

AliHLTTPCHWCFProcessorUnit& AliHLTTPCHWCFProcessorUnit::operator=(const AliHLTTPCHWCFProcessorUnit&)
{
  // dummy
  return *this;
}

int AliHLTTPCHWCFProcessorUnit::Init()
{
  // initialise

  fkBunch = 0;
  fBunchIndex = 0;
  fWasDeconvoluted = 0;
  return 0;
}

int AliHLTTPCHWCFProcessorUnit::InputStream( const AliHLTTPCHWCFBunch *bunch )
{
  // input stream of data

  if( bunch && fDebug ){
    printf("\nHWCF Processor: input bunch F %1d R %3d P %3d  NS %2ld:\n",
	   bunch->fFlag, bunch->fRow, bunch->fPad, bunch->fData.size());
    for( unsigned int i=0; i<bunch->fData.size(); i++ ){
      AliHLTTPCHWCFDigit d =  bunch->fData[i];
      printf("   q %2d t %3d peak %2d ", d.fQ, d.fTime, d.fPeak);
       printf("(");
      for( int j=0; j<3; j++ ) printf(" {%d,%2.0f}",d.fMC.fClusterID[j].fMCID, d.fMC.fClusterID[j].fWeight );
      printf(" )\n");
    }
  }

  fkBunch = bunch;
  fBunchIndex = 0;
  fWasDeconvoluted = 0;
  return 0;
}

const AliHLTTPCHWCFClusterFragment *AliHLTTPCHWCFProcessorUnit::OutputStream()
{
  // output stream of data

  //const AliHLTUInt32_t kTimeBinWindow = 5;
  const AliHLTUInt32_t kHalfTimeBinWindow = 2;

  if( !fkBunch ) return 0;

  fOutput.fFlag = fkBunch->fFlag;
  fOutput.fRow = fkBunch->fRow;
  fOutput.fPad = fkBunch->fPad;
  fOutput.fBranch = fkBunch->fBranch;
  fOutput.fBorder = fkBunch->fBorder;
  fOutput.fEdge = 0; //Set below with some more constraints
  fOutput.fQmax = 0;
  fOutput.fQ = 0;
  fOutput.fT = 0;
  fOutput.fT2 = 0;
  fOutput.fP = 0;
  fOutput.fP2 = 0;
  fOutput.fTMean = 0;
  fOutput.fNPads = 0;
  fOutput.fNDeconvolutedTime = 0;
  fOutput.fIsDeconvolutedPad = 0;
  fOutput.fConsecutiveTimeDeconvolution = 0;
  fOutput.fLargestQ = 0;
  fOutput.fLargestQ2 = 0;
  fOutput.fLargestQPad = 0;
  fOutput.fMC.clear();

  if( fkBunch->fFlag==2 && fkBunch->fData.size()==1 ){ // rcu trailer word, forward it
    fOutput.fRow = fkBunch->fData[0].fQ;
  }

  if( fkBunch->fFlag >1 ){
    fkBunch = 0;
    return &fOutput;
  }

  if( fkBunch->fFlag < 1 ) return 0;

  if( fBunchIndex >= fkBunch->fData.size() ) return 0;

  AliHLTUInt32_t iStart = fBunchIndex;
  AliHLTUInt32_t iPeak = fBunchIndex;
  AliHLTUInt32_t qPeak = 0;

  // find next/best peak

  for( ; fBunchIndex<fkBunch->fData.size(); fBunchIndex++ ){
    const AliHLTTPCHWCFDigit &d = fkBunch->fData[fBunchIndex];
    if( d.fPeak != 1 ) continue;
    if( fDeconvolute ){
      iPeak = fBunchIndex;
      qPeak = d.fQ;
      fBunchIndex++;
      break;
    } else {
      if( d.fQ>qPeak ){
	qPeak = d.fQ;
	iPeak = fBunchIndex;
      }
    }
  }

  if( qPeak == 0 ) return 0;

  // find next minimum !!! At the moment the minimum finder is on only when no timebin window set

  bool isDeconvoluted = 0;

  if( !fUseTimeBinWindow ){
    for( ; fBunchIndex<fkBunch->fData.size(); fBunchIndex++ ){
      if( fDeconvolute ){
	if( fkBunch->fData[fBunchIndex].fPeak != 0 ){
	  fBunchIndex++;
	  break;
	}
      }
    }
    if( fBunchIndex<fkBunch->fData.size() ) isDeconvoluted = 1;
  } else {
    if( !fDeconvolute ){
      fBunchIndex = fkBunch->fData.size();
    } else if ( fImprovedDeconvolution) {
      fWasDeconvoluted = 0;
      for ( int i = std::max((int) iStart, (int) (iPeak - kHalfTimeBinWindow)); i < iPeak; i++) {
        if ( fkBunch->fData[i].fPeak == 2 )
        {
          iStart = i + 1;
          fWasDeconvoluted = 1;
        }
      }
      //Do not mark as deconvoluted when iPeak + 2 is a minimum (because we use that sample), do not consider minima add end of bunch!
      for ( ; fBunchIndex < fkBunch->fData.size(); fBunchIndex++ ) {
        if (fBunchIndex == iPeak + kHalfTimeBinWindow)
        {
          fBunchIndex++;
          break;
        }
        if (fkBunch->fData[fBunchIndex].fPeak == 2) {
          if (fBunchIndex + 1 != fkBunch->fData.size()) isDeconvoluted = 1;
          fBunchIndex++;
          break;
        }
      }
    } else {
      // find next peak
      if( fBunchIndex+1<fkBunch->fData.size() && fkBunch->fData[fBunchIndex+1].fPeak==1 ){
	fBunchIndex = fBunchIndex+1;
	isDeconvoluted = 1;
      } else   if( fBunchIndex+2<fkBunch->fData.size() && fkBunch->fData[fBunchIndex+2].fPeak==1 ){
	fBunchIndex = fBunchIndex+1;
	isDeconvoluted = 1;
      } else   if( fBunchIndex+3<fkBunch->fData.size() && fkBunch->fData[fBunchIndex+3].fPeak==1 ){
	fBunchIndex = fBunchIndex+2;
	isDeconvoluted = 1;
      } else   if( fBunchIndex+1<fkBunch->fData.size() ){
	fBunchIndex = fBunchIndex+2;
      } else   if( fBunchIndex<fkBunch->fData.size() ){
	fBunchIndex = fBunchIndex+1;
      }
    }
  }

  AliHLTUInt32_t iEnd = fBunchIndex;

  if( fUseTimeBinWindow ){
    if( iPeak > iStart + kHalfTimeBinWindow ) iStart = iPeak - kHalfTimeBinWindow;
    if( iEnd  > iPeak + kHalfTimeBinWindow + 1) iEnd = iPeak + kHalfTimeBinWindow + 1;
  }

  fOutput.fQmax = 0;
  fOutput.fQ = 0;
  fOutput.fT = 0;
  fOutput.fT2 = 0;
  fOutput.fP = 0;
  fOutput.fP2 = 0;
  fOutput.fTMean = fkBunch->fData[iPeak].fTime;
  fOutput.fNPads = 1;
  fOutput.fNDeconvolutedTime = ( fWasDeconvoluted || isDeconvoluted ) ? 1 :0;
  fOutput.fConsecutiveTimeDeconvolution = fOutput.fNDeconvolutedTime;
  fOutput.fMC.clear();

  fWasDeconvoluted = isDeconvoluted;

  for( AliHLTUInt32_t i=iStart; i<iEnd; i++ ){
    const AliHLTTPCHWCFDigit &d = fkBunch->fData[i];
    AliHLTUInt64_t q = d.fQ*fkBunch->fGain;
    if (q > fOutput.fQmax) fOutput.fQmax = q;
    fOutput.fQ += q;
    fOutput.fT += q*d.fTime;
    fOutput.fT2+= q*d.fTime*d.fTime;
    fOutput.fP += q*fkBunch->fPad;
    fOutput.fP2+= q*fkBunch->fPad*fkBunch->fPad;
    fOutput.fMC.push_back(d.fMC);
  }
  fOutput.fEdge = fkBunch->fEdge && iEnd > iStart + 2 && qPeak > 5;
  fOutput.fLargestQ = fOutput.fQ;
  fOutput.fLargestQPad = fkBunch->fEdge ? fkBunch->fPad : 0xFFFFFFFF; //We only correct if the largest charge is at the edge cluster. Mark other pads as -1

  if( fkBunch->fData.size()==1 && fOutput.fQ < fSingleSeqLimit ) return 0;

  return &fOutput;
}
<|endoftext|>


<commit_before>namespace factor
{

template<typename TargetGeneration, typename Policy>
struct copying_collector : collector<TargetGeneration,Policy> {
	cell scan;

	explicit copying_collector(factor_vm *parent_, TargetGeneration *target_, Policy policy_) :
		collector<TargetGeneration,Policy>(parent_,target_,policy_), scan(target_->here) {}

	void cheneys_algorithm()
	{
		while(scan && scan < this->target->here)
		{
			this->trace_object((object *)scan);
			scan = this->target->next_object_after(scan);
		}
	}
};

}
<commit_msg>VM: Refactor copying_collector.hpp to Factor style<commit_after>namespace factor {

template <typename TargetGeneration, typename Policy>
struct copying_collector : collector<TargetGeneration, Policy> {
  cell scan;

  explicit copying_collector(factor_vm* parent_, TargetGeneration* target_,
                             Policy policy_)
      : collector<TargetGeneration, Policy>(parent_, target_, policy_),
        scan(target_->here) {}

  void cheneys_algorithm() {
    while (scan && scan < this->target->here) {
      this->trace_object((object*)scan);
      scan = this->target->next_object_after(scan);
    }
  }
};

}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "Header.h"
#include "EasyBMP.h"
int main() {
	int x=20;
	int y=20;
	int z=20;
	World_Map Plot(x,y,z);
	int i = 0;
	int j = 0;
	int k = 0;
	BMP *image = new BMP;
	Isometric_Render iso(&Plot, image, 0, x-1, 0, y-1, 0, z-1);
	image->SetSize(iso.width + DEBUGGING_WIDTH, iso.height+1+DEBUGGING_HEIGHT);
	for (i = 0; i < iso.width; i++) {
		for (j = 0; j < iso.height; j++) {
			RGBApixel* pixel = new RGBApixel;
			pixel->Alpha = 127;
			pixel->Red = 0;
			pixel->Green = 0;
			pixel->Blue = 0;
			image->SetPixel(i, j, *pixel);
		}
	}
    //change made
	//bmp image(10,10,(char*)"air.bmp");
	//image->save();
	printf("Saved!\n");
	int x_max = Plot.get_x();
	int y_max = Plot.get_y();
	int z_max = Plot.get_z();
	//for (i = 0; i < x_max; i++) {
		//for (j = 0; j < y_max; j++) {
			//for (k = 0; k < z_max; k++) {
				//if (k == (int)(25 + 10 * sin(i))) {
				//if (1) {
					//Plot.set_point(i, j, k);
					//int * point = iso.find_xy(i, j, k);
					//iso.place_cube(i,j,k);
					//RGBApixel* pixel = new RGBApixel;
					//pixel->Alpha = 127;
					//pixel->Red = Plot.get_point(i, j, k)->r;
					//pixel->Green = Plot.get_point(i, j, k)->g;
					//pixel->Blue = Plot.get_point(i, j, k)->b;
					//image->SetPixel(point[0], iso.height-point[1], *pixel);
					//cout << "i: " << i << "  j: " << j << "  k: " << k << endl;
				//}
				//}
			//}
		//}
	//}
	RGBApixel* pixel = new RGBApixel;
	pixel->Alpha = 127;
	pixel->Red =192;
	pixel->Green = 192;
	pixel->Blue = 192;
	int a[2];
	a[0] = 17;
	a[1] = 82;
	int b[2];
	a[0] = 43;
	a[1] = 53;
	iso.draw_line(a, b, pixel);
	pixel = new RGBApixel;
	pixel->Alpha = 127;
	pixel->Red = 0;
	pixel->Green = 0;
	pixel->Blue = 0;
	image->SetPixel(0, 0, *pixel);

	Plot.set_point(0, 0, 0);
	int * point = iso.find_xy(0, 0, 1);
	printf("\n\n\n%d     %d\n", point[0], point[1]);
	point = iso.find_xy(1, 1, 0);
	printf("\n%d     %d\n", point[0], point[1]);
	image->WriteToFile("isometric.bmp");

	//Plot.~World_Map();
	return EXIT_SUCCESS;
}
<commit_msg>drew a line<commit_after>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "Header.h"
#include "EasyBMP.h"
int main() {
	int x=20;
	int y=20;
	int z=20;
	World_Map Plot(x,y,z);
	int i = 0;
	int j = 0;
	int k = 0;
	BMP *image = new BMP;
	Isometric_Render iso(&Plot, image, 0, x-1, 0, y-1, 0, z-1);
	image->SetSize(iso.width + DEBUGGING_WIDTH, iso.height+1+DEBUGGING_HEIGHT);
	for (i = 0; i < iso.width; i++) {
		for (j = 0; j < iso.height; j++) {
			RGBApixel* pixel = new RGBApixel;
			pixel->Alpha = 127;
			pixel->Red = 0;
			pixel->Green = 0;
			pixel->Blue = 0;
			image->SetPixel(i, j, *pixel);
		}
	}
    //change made
	//bmp image(10,10,(char*)"air.bmp");
	//image->save();
	printf("Saved!\n");
	int x_max = Plot.get_x();
	int y_max = Plot.get_y();
	int z_max = Plot.get_z();
	//for (i = 0; i < x_max; i++) {
		//for (j = 0; j < y_max; j++) {
			//for (k = 0; k < z_max; k++) {
				//if (k == (int)(25 + 10 * sin(i))) {
				//if (1) {
					//Plot.set_point(i, j, k);
					//int * point = iso.find_xy(i, j, k);
					//iso.place_cube(i,j,k);
					//RGBApixel* pixel = new RGBApixel;
					//pixel->Alpha = 127;
					//pixel->Red = Plot.get_point(i, j, k)->r;
					//pixel->Green = Plot.get_point(i, j, k)->g;
					//pixel->Blue = Plot.get_point(i, j, k)->b;
					//image->SetPixel(point[0], iso.height-point[1], *pixel);
					//cout << "i: " << i << "  j: " << j << "  k: " << k << endl;
				//}
				//}
			//}
		//}
	//}
	RGBApixel* pixel = new RGBApixel;
	pixel->Alpha = 127;
	pixel->Red =192;
	pixel->Green = 192;
	pixel->Blue = 192;
	int * a = (int *)malloc(sizeof(int)*2);
	a[0] = 17;
	a[1] = 82;
	int * b = (int *)malloc(sizeof(int) * 2);
	b[0] = 43;
	b[1] = 53;
	iso.draw_line(a, b, pixel);
	pixel = new RGBApixel;
	pixel->Alpha = 127;
	pixel->Red = 0;
	pixel->Green = 0;
	pixel->Blue = 0;
	image->SetPixel(0, 0, *pixel);

	Plot.set_point(0, 0, 0);
	int * point = iso.find_xy(0, 0, 1);
	printf("\n\n\n%d     %d\n", point[0], point[1]);
	point = iso.find_xy(1, 1, 0);
	printf("\n%d     %d\n", point[0], point[1]);
	image->WriteToFile("isometric.bmp");

	//Plot.~World_Map();
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 *  Copyright 2010-2011 Anders Wallin (anders.e.e.wallin "at" gmail.com)
 *
 *  This file is part of OpenVoronoi.
 *
 *  OpenCAMlib is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  OpenCAMlib is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef VODI_G_HPP
#define VODI_G_HPP

#include <vector>

#include <boost/graph/adjacency_list.hpp>

#include "point.hpp"
#include "halfedgediagram.hpp"
#include "voronoivertex.hpp"

// this file contains typedefs used by voronoidiagram.h
namespace ovd {

// notes from the Okabe-Boots-Sugihara book, page 171->:
/*
 * Distance-function.
 * R1 - region of endpoint pi1
 * R2 - region of endpoint pi2
 * R3 - region of line-segment Li
 *               dist(p,pi1) if  p in R1
 * dist(p,Li) =  dist(p,pi2) if  p in R2
 *               dist(p,Li)  if p in R3
 *
 * dist(p,Li) = distance from p to L, along perpendicular line to L
 *
 * = norm(  (x-xi1)   -  dotprod( (x-xi1), (xi2-xi1) ) / ( norm_sq(xi2-xi1) ) * (xi2,xi1) )
 *
 *
 *
 * Vertex - LineSegment
 * Bisectors:
 *  B1: point-point: line
 *  B2: point-line: parabola
 *  B3: line-line: line
 *
 *  Voronoi Edges:
 *  E1: point pi - point pj. straight line bisecting pi-pj
 *  E2: edge generated by line-segment L's endpoint pi. perpendicular to L, passing through pi
 *  E3: point pi - segment Lj. dist(E3, p) == dist(E3,Lj). Parabolic arc
 *  E4: line Li - Line Lj. straight line bisector
 *  (G): generator segment edge
 *
 *  Voronoi vertices (see p177 of Okabe book):
 *  V1: generators(pi, pj, pk). edges(E1, E1, E1)
 *     - compute using detH. This is also the circumcenter of the pi,pj,pk triangle
 *  V2: generators(pi, Lj, pj1) point, segment, segment's endpoint. edges(E1, E2, E3)   E1 and E3 are tangent at V2
 *     - ? compute by mirroring pi in the separator and use detH
 *  V3: generators(Li, pj, pk) edges(E1, E3, E3)   E3-edges have common directrix(Li)
 *  V4: generators(Li, Lj, pi1)  edges(E2, E3, E4)  E3-E4 tangent at V4
 *  V5: generators(pi, Lj, Lk) edges (E3, E3, E4)
 *  V6: generators(Li, Lj, Lk) edges(E4, E4, E4)
 *    - this is the incenter of a incircle inscribed by triangle Li,Lj,Lk (or sometiems excenter of excircle if V6 outside triangle?)
 *    - The Cartesian coordinates of the incenter are a weighted average of the coordinates of the three vertices using the side
 *       lengths of the triangle as weights. (The weights are positive so the incenter lies inside the triangle as stated above.)
 *      If the three vertices are located at (xa,ya), (xb,yb), and (xc,yc), and the sides opposite these vertices have corresponding
 *      lengths a, b, and c, then the incenter is at
 *      (a x_a + b x_b + c x_c)/ (a+b+c)
 *
 * bisector formulas
 * x = x1 - x2 - x3*t +/- x4 * sqrt( square(x5+x6*t) - square(x7+x8*t) )
 * (same formula for y-coordinate)
 * line (line/line)
 * parabola (circle/line)
 * hyperbola (circle/circle)
 * ellipse (circle/circle)
 *
 * line: a1*x + b1*y + c + k*t = 0  (t is amount of offset) k=+1 offset left of line, k=-1 right of line
 * with a*a + b*b = 1
 *
 * circle: square(x-xc) + square(y-yc) = square(r+k*t)  k=+1 for enlarging circle, k=-1 shrinking
 */

// use traits-class here so that EdgePros can store data of type HEEdge
// typedef of the VD-graph follows below.

// vecS is slightly faster than listS
// vecS   5.72us * n log(n)
// listS  6.18 * n log(n)
#define OUT_EDGE_CONTAINER boost::vecS

// note: cannot use vecS since remove_vertex invalidates iterators/edge_descriptors (?)
#define VERTEX_CONTAINER boost::listS
#define EDGE_LIST_CONTAINER boost::listS

// type of edge-descriptors in the graph
typedef boost::adjacency_list_traits<OUT_EDGE_CONTAINER,
                                     VERTEX_CONTAINER,
                                     boost::bidirectionalS,
                                     EDGE_LIST_CONTAINER >::edge_descriptor HEEdge;
// type of face-descriptors in the graph
typedef unsigned int HEFace;

/*
 * bisector formulas
 * x = x1 - x2 - x3*t +/- x4 * sqrt( square(x5+x6*t) - square(x7+x8*t) )
 * (same formula for y-coordinate)
 * line (line/line)
 * parabola (circle/line)
 * hyperbola (circle/circle)
 * ellipse (circle/circle)
*/

enum VoronoiEdgeType {LINE, PARABOLA, ELLIPSE, HYPERBOLA, SEPARATOR, LINESITE};

/// properties of an edge in the voronoi diagram
/// each edge stores a pointer to the next HEEdge
/// and the HEFace to which this HEEdge belongs
struct EdgeProps {
    EdgeProps() {}
    EdgeProps(HEEdge n, HEFace f): next(n), face(f) {}
    /// create edge with given next, twin, and face
    EdgeProps(HEEdge n, HEEdge t, HEFace f): next(n), twin(t), face(f) {}
    /// the next edge, counterclockwise, from this edge
    HEEdge next;
    /// the twin edge
    HEEdge twin;
    /// the face to which this edge belongs
    HEFace face; // each face corresponds to an input Site/generator
    double k; // offset-direction from the adjacent site, either +1 or -1
    VoronoiEdgeType type;
    inline double sq(double x) const {return x*x;}
    Point point(double t) const {
        double discr1 = sq(x[4]+x[5]*t) - sq(x[6]+x[7]*t);
        double discr2 = sq(y[4]+y[5]*t) - sq(y[6]+y[7]*t);
        if ( (discr1 >= 0) && (discr2 >= 0) ) {
            double xc = x[0] - x[1] - x[2]*t + x[3] * sqrt( sq(x[4]+x[5]*t) - sq(x[6]+x[7]*t) );
            double yc = y[0] - y[1] - y[2]*t + y[3] * sqrt( sq(y[4]+y[5]*t) - sq(y[6]+y[7]*t) );
            return Point(xc,yc);
        } else {
            std::cout << " warning bisector sqrt(-1) !\n";
            return Point(0,0);
        }
    }
    double x[8];
    double y[8];
    void set_parameters(Site* s1, Site* s2) {
        if (s1->isPoint() && s2->isPoint())        // PP
            set_pp_parameters(s1,s2);
        else if (s1->isPoint() && s2->isLine())    // PL
            set_pl_parameters(s1,s2);
        else if (s2->isPoint() && s1->isLine())    // LP
            set_pl_parameters(s2,s1);
        else if (s1->isLine() && s2->isLine())     // LL
            set_ll_parameters(s2,s1);
        else
            assert(0);
            // AP
            // PA
            // AA
            // AL
            // LA
    }
    // called for point(s1)-point(s2) edges
    void set_pp_parameters(Site* s1, Site* s2) {
        std::cout << " set_pp \n";
        type = LINE;
    }
    // called for point(s1)-line(s2) edges
    void set_pl_parameters(Site* s1, Site* s2) {
        std::cout << " set_pl \n";
        type = PARABOLA;
        double alfa3 = s2->a()*s1->x() + s2->b()*s1->y() + s2->c();
        x[0]=s1->x();       // xc1
        x[1]=s2->a()*alfa3; // alfa1*alfa3
        x[2]=-s2->a();      // -alfa1 = - a2
        x[3]=s2->b();       // alfa2 = b2
        x[4]=0;             // alfa4 = r1
        x[5]=+1;            // lambda1 (allways positive offset from PointSite?)
        x[6]= alfa3;        // alfa3= a2*xc1+b2*yc1+d2?
        x[7]=-1;            // -1

        y[0]=s1->y();       // yc1
        y[1]=s2->b()*alfa3; // alfa2*alfa3
        y[2]=-s2->b();      // -alfa2 = -b2
        y[3]=s2->a();       // alfa1 = a2
        y[4]=0;             // alfa4 = r1
        y[5]=+1;            // lambda1 (allways positive offset from PointSite?)
        y[6]=alfa3;         // alfa3
        y[7]=-1;            // -1
        print_params();
    }
    // line(s1)-line(s2) edge
    void set_ll_parameters(Site* s1, Site* s2) {  // Held thesis p96
        std::cout << " set_ll \n";
        type = LINE;
        double delta = s1->a()*s2->b() - s1->b()*s2->a();
        assert( delta != 0 );
        x[0]= ( (s1->b() * s2->c()) - (s2->b() * s1->c()) ) / delta;  // alfa1 = (b1*d2-b2*d1) / delta
        x[1]=0;
        x[2]= -(s2->b()-s1->b()); // -alfa3 = -( b2-b1 )
        x[3]=0;
        x[4]=0;
        x[5]=0;
        x[6]=0;
        x[7]=0;

        y[0]= ( (s2->a()*s1->c()) - (s1->a()*s2->c()) ) / delta;  // alfa2 = (a2*d1-a1*d2) / delta
        y[1]= 0;
        y[2]= -(s1->a()-s2->a());  // -alfa4 = -( a1-a2 )
        y[3]=0;
        y[4]=0;
        y[5]=0;
        y[6]=0;
        y[7]=0;
        y[8]=0;
    }
    void print_params() const {
        std::cout << "x-params: ";
        for (int m=0;m<8;m++)
            std::cout << x[m] << " ";
        std::cout << "\n";
        std::cout << "y-params: ";
        for (int m=0;m<8;m++)
            std::cout << y[m] << " ";
        std::cout << "\n";
    }
    // arc: d=sqrt( sq(xc1-xc2) + sq(yc1-yc2) )
};

/// Status of faces in the voronoi diagram
/// INCIDENT faces contain one or more IN-vertex
/// NONINCIDENT faces contain only OUT-vertices
enum VoronoiFaceStatus {INCIDENT, NONINCIDENT};

/// properties of a face in the voronoi diagram
/// each face stores one edge on the boundary of the face
struct FaceProps {
    FaceProps( ) {}
    /// create face with given edge, generator, and type
    FaceProps( HEEdge e , Site* s, VoronoiFaceStatus st) : edge(e), site(s), status(st) {}
    /// operator for sorting faces
    bool operator<(const FaceProps& f) const {return (this->idx<f.idx);}
    /// face index
    HEFace idx;
    /// one edge that bounds this face
    HEEdge edge;
    /// the site/generator for this face (either PointSite, LineSite, or ArcSite)
    Site* site;
    /// face status (either incident or nonincident)
    VoronoiFaceStatus status;
};

// the type of graph with which we construct the voronoi-diagram
typedef hedi::HEDIGraph< OUT_EDGE_CONTAINER,     // out-edges stored in a std::list
                       VERTEX_CONTAINER,         // vertex set stored here
                       boost::bidirectionalS,    // bidirectional graph.
                       VoronoiVertex,            // vertex properties
                       EdgeProps,                // edge properties
                       FaceProps,                // face properties
                       boost::no_property,       // graph properties
                       EDGE_LIST_CONTAINER       // edge storage
                       > HEGraph;
// NOTE: if these listS etc. arguments ever change, they must also be updated
// above where we do: adjacency_list_traits

typedef boost::graph_traits< HEGraph::BGLGraph >::vertex_descriptor  HEVertex;
typedef boost::graph_traits< HEGraph::BGLGraph >::vertex_iterator    HEVertexItr;
typedef boost::graph_traits< HEGraph::BGLGraph >::edge_iterator      HEEdgeItr;
typedef boost::graph_traits< HEGraph::BGLGraph >::out_edge_iterator  HEOutEdgeItr;
typedef boost::graph_traits< HEGraph::BGLGraph >::adjacency_iterator HEAdjacencyItr;
typedef boost::graph_traits< HEGraph::BGLGraph >::vertices_size_type HEVertexSize;

// these containers are used instead of iterators when accessing
// adjacent vertices, edges, faces.
// FIXME: it may be faster to rewrite the code so it uses iterators, as does the BGL.
typedef std::vector<HEVertex> VertexVector;
typedef std::vector<HEFace> FaceVector;
typedef std::vector<HEEdge> EdgeVector;

} // end namespace
#endif

<commit_msg>minor documentation<commit_after>/*
 *  Copyright 2010-2011 Anders Wallin (anders.e.e.wallin "at" gmail.com)
 *
 *  This file is part of OpenVoronoi.
 *
 *  OpenCAMlib is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  OpenCAMlib is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef VODI_G_HPP
#define VODI_G_HPP

#include <vector>

#include <boost/graph/adjacency_list.hpp>

#include "point.hpp"
#include "halfedgediagram.hpp"
#include "voronoivertex.hpp"

// this file contains typedefs used by voronoidiagram.h
namespace ovd {

// notes from the Okabe-Boots-Sugihara book, page 171->:
/*
 * Distance-function.
 * R1 - region of endpoint pi1
 * R2 - region of endpoint pi2
 * R3 - region of line-segment Li
 *               dist(p,pi1) if  p in R1
 * dist(p,Li) =  dist(p,pi2) if  p in R2
 *               dist(p,Li)  if p in R3
 *
 * dist(p,Li) = distance from p to L, along perpendicular line to L
 *
 * = norm(  (x-xi1)   -  dotprod( (x-xi1), (xi2-xi1) ) / ( norm_sq(xi2-xi1) ) * (xi2,xi1) )
 *
 *
 *
 * Vertex - LineSegment
 * Bisectors:
 *  B1: point-point: line
 *  B2: point-line: parabola
 *  B3: line-line: line
 *
 *  Voronoi Edges:
 *  E1: point pi - point pj. straight line bisecting pi-pj
 *  E2: edge generated by line-segment L's endpoint pi. perpendicular to L, passing through pi
 *  E3: point pi - segment Lj. dist(E3, p) == dist(E3,Lj). Parabolic arc
 *  E4: line Li - Line Lj. straight line bisector
 *  (G): generator segment edge
 *
 *  Voronoi vertices (see p177 of Okabe book):
 *  V1: generators(pi, pj, pk). edges(E1, E1, E1)
 *     - compute using detH. This is also the circumcenter of the pi,pj,pk triangle
 *  V2: generators(pi, Lj, pj1) point, segment, segment's endpoint. edges(E1, E2, E3)   E1 and E3 are tangent at V2
 *     - ? compute by mirroring pi in the separator and use detH
 *  V3: generators(Li, pj, pk) edges(E1, E3, E3)   E3-edges have common directrix(Li)
 *  V4: generators(Li, Lj, pi1)  edges(E2, E3, E4)  E3-E4 tangent at V4
 *  V5: generators(pi, Lj, Lk) edges (E3, E3, E4)
 *  V6: generators(Li, Lj, Lk) edges(E4, E4, E4)
 *    - this is the incenter of a incircle inscribed by triangle Li,Lj,Lk (or sometiems excenter of excircle if V6 outside triangle?)
 *    - The Cartesian coordinates of the incenter are a weighted average of the coordinates of the three vertices using the side
 *       lengths of the triangle as weights. (The weights are positive so the incenter lies inside the triangle as stated above.)
 *      If the three vertices are located at (xa,ya), (xb,yb), and (xc,yc), and the sides opposite these vertices have corresponding
 *      lengths a, b, and c, then the incenter is at
 *      (a x_a + b x_b + c x_c)/ (a+b+c)
 *
 * bisector formulas
 * x = x1 - x2 - x3*t +/- x4 * sqrt( square(x5+x6*t) - square(x7+x8*t) )
 * (same formula for y-coordinate)
 * line (line/line)
 * parabola (circle/line)
 * hyperbola (circle/circle)
 * ellipse (circle/circle)
 *
 * line: a1*x + b1*y + c + k*t = 0  (t is amount of offset) k=+1 offset left of line, k=-1 right of line
 * with a*a + b*b = 1
 *
 * circle: square(x-xc) + square(y-yc) = square(r+k*t)  k=+1 for enlarging circle, k=-1 shrinking
 */

// use traits-class here so that EdgePros can store data of type HEEdge
// typedef of the VD-graph follows below.

// vecS is slightly faster than listS
// vecS   5.72us * n log(n)
// listS  6.18 * n log(n)
#define OUT_EDGE_CONTAINER boost::vecS

// note: cannot use vecS since remove_vertex invalidates iterators/edge_descriptors (?)
#define VERTEX_CONTAINER boost::listS
#define EDGE_LIST_CONTAINER boost::listS

// type of edge-descriptors in the graph
typedef boost::adjacency_list_traits<OUT_EDGE_CONTAINER,
                                     VERTEX_CONTAINER,
                                     boost::bidirectionalS,
                                     EDGE_LIST_CONTAINER >::edge_descriptor HEEdge;
// type of face-descriptors in the graph
typedef unsigned int HEFace;

/*
 * bisector formulas
 * x = x1 - x2 - x3*t +/- x4 * sqrt( square(x5+x6*t) - square(x7+x8*t) )
 * (same formula for y-coordinate)
 * line (line/line)
 * parabola (circle/line)
 * hyperbola (circle/circle)
 * ellipse (circle/circle)
*/

enum VoronoiEdgeType {LINE, PARABOLA, ELLIPSE, HYPERBOLA, SEPARATOR, LINESITE};

/// properties of an edge in the voronoi diagram
/// each edge stores a pointer to the next HEEdge
/// and the HEFace to which this HEEdge belongs
struct EdgeProps {
    EdgeProps() {}
    EdgeProps(HEEdge n, HEFace f): next(n), face(f) {}
    /// create edge with given next, twin, and face
    EdgeProps(HEEdge n, HEEdge t, HEFace f): next(n), twin(t), face(f) {}
    /// the next edge, counterclockwise, from this edge
    HEEdge next;
    /// the twin edge
    HEEdge twin;
    /// the face to which this edge belongs
    HEFace face; // each face corresponds to an input Site/generator
    double k; // offset-direction from the adjacent site, either +1 or -1
    VoronoiEdgeType type;
    inline double sq(double x) const {return x*x;}
    Point point(double t) const {
        double discr1 = sq(x[4]+x[5]*t) - sq(x[6]+x[7]*t);
        double discr2 = sq(y[4]+y[5]*t) - sq(y[6]+y[7]*t);
        if ( (discr1 >= 0) && (discr2 >= 0) ) {
            double xc = x[0] - x[1] - x[2]*t + x[3] * sqrt( sq(x[4]+x[5]*t) - sq(x[6]+x[7]*t) );
            double yc = y[0] - y[1] - y[2]*t + y[3] * sqrt( sq(y[4]+y[5]*t) - sq(y[6]+y[7]*t) );
            return Point(xc,yc);
        } else {
            std::cout << " warning bisector sqrt(-1) !\n";
            return Point(0,0);
        }
    }
    double x[8];
    double y[8];
    void set_parameters(Site* s1, Site* s2) {
        if (s1->isPoint() && s2->isPoint())        // PP
            set_pp_parameters(s1,s2);
        else if (s1->isPoint() && s2->isLine())    // PL
            set_pl_parameters(s1,s2);
        else if (s2->isPoint() && s1->isLine())    // LP
            set_pl_parameters(s2,s1);
        else if (s1->isLine() && s2->isLine())     // LL
            set_ll_parameters(s2,s1);
        else
            assert(0);
            // AP
            // PA
            // AA
            // AL
            // LA
    }
    // called for point(s1)-point(s2) edges
    void set_pp_parameters(Site* s1, Site* s2) {
        std::cout << " set_pp \n";
        type = LINE;
    }
    // called for point(s1)-line(s2) edges
    void set_pl_parameters(Site* s1, Site* s2) {
        // x = xc -a2 h -k2 a2 t +/- b2 sqrt( (e1+k1 t)^2 - (alfa3 + k2 t)^2 )
        std::cout << " set_pl \n";
        type = PARABOLA;
        double alfa3 = s2->a()*s1->x() + s2->b()*s1->y() + s2->c();
        x[0]=s1->x();       // xc1
        x[1]=s2->a()*alfa3; // alfa1*alfa3
        x[2]=-s2->a();      // -alfa1 = - a2 * k2?
        x[3]=s2->b();       // alfa2 = b2
        x[4]=0;             // alfa4 = r1
        x[5]=+1;            // lambda1 (allways positive offset from PointSite?)
        x[6]= alfa3;        // alfa3= a2*xc1+b2*yc1+d2?
        x[7]=-1;            // -1 = k2 side of line??

        y[0]=s1->y();       // yc1
        y[1]=s2->b()*alfa3; // alfa2*alfa3
        y[2]=-s2->b();      // -alfa2 = -b2
        y[3]=s2->a();       // alfa1 = a2
        y[4]=0;             // alfa4 = r1
        y[5]=+1;            // lambda1 (allways positive offset from PointSite?)
        y[6]=alfa3;         // alfa3
        y[7]=-1;            // -1 = k2 side of line??
        print_params();
    }
    // line(s1)-line(s2) edge
    void set_ll_parameters(Site* s1, Site* s2) {  // Held thesis p96
        std::cout << " set_ll \n";
        type = LINE;
        double delta = s1->a()*s2->b() - s1->b()*s2->a();
        assert( delta != 0 );
        x[0]= ( (s1->b() * s2->c()) - (s2->b() * s1->c()) ) / delta;  // alfa1 = (b1*d2-b2*d1) / delta
        x[1]=0;
        x[2]= -(s2->b()-s1->b()); // -alfa3 = -( b2-b1 )
        x[3]=0;
        x[4]=0;
        x[5]=0;
        x[6]=0;
        x[7]=0;

        y[0]= ( (s2->a()*s1->c()) - (s1->a()*s2->c()) ) / delta;  // alfa2 = (a2*d1-a1*d2) / delta
        y[1]= 0;
        y[2]= -(s1->a()-s2->a());  // -alfa4 = -( a1-a2 )
        y[3]=0;
        y[4]=0;
        y[5]=0;
        y[6]=0;
        y[7]=0;
        y[8]=0;
    }
    void print_params() const {
        std::cout << "x-params: ";
        for (int m=0;m<8;m++)
            std::cout << x[m] << " ";
        std::cout << "\n";
        std::cout << "y-params: ";
        for (int m=0;m<8;m++)
            std::cout << y[m] << " ";
        std::cout << "\n";
    }
    // arc: d=sqrt( sq(xc1-xc2) + sq(yc1-yc2) )
};

/// Status of faces in the voronoi diagram
/// INCIDENT faces contain one or more IN-vertex
/// NONINCIDENT faces contain only OUT-vertices
enum VoronoiFaceStatus {INCIDENT, NONINCIDENT};

/// properties of a face in the voronoi diagram
/// each face stores one edge on the boundary of the face
struct FaceProps {
    FaceProps( ) {}
    /// create face with given edge, generator, and type
    FaceProps( HEEdge e , Site* s, VoronoiFaceStatus st) : edge(e), site(s), status(st) {}
    /// operator for sorting faces
    bool operator<(const FaceProps& f) const {return (this->idx<f.idx);}
    /// face index
    HEFace idx;
    /// one edge that bounds this face
    HEEdge edge;
    /// the site/generator for this face (either PointSite, LineSite, or ArcSite)
    Site* site;
    /// face status (either incident or nonincident)
    VoronoiFaceStatus status;
};

// the type of graph with which we construct the voronoi-diagram
typedef hedi::HEDIGraph< OUT_EDGE_CONTAINER,     // out-edges stored in a std::list
                       VERTEX_CONTAINER,         // vertex set stored here
                       boost::bidirectionalS,    // bidirectional graph.
                       VoronoiVertex,            // vertex properties
                       EdgeProps,                // edge properties
                       FaceProps,                // face properties
                       boost::no_property,       // graph properties
                       EDGE_LIST_CONTAINER       // edge storage
                       > HEGraph;
// NOTE: if these listS etc. arguments ever change, they must also be updated
// above where we do: adjacency_list_traits

typedef boost::graph_traits< HEGraph::BGLGraph >::vertex_descriptor  HEVertex;
typedef boost::graph_traits< HEGraph::BGLGraph >::vertex_iterator    HEVertexItr;
typedef boost::graph_traits< HEGraph::BGLGraph >::edge_iterator      HEEdgeItr;
typedef boost::graph_traits< HEGraph::BGLGraph >::out_edge_iterator  HEOutEdgeItr;
typedef boost::graph_traits< HEGraph::BGLGraph >::adjacency_iterator HEAdjacencyItr;
typedef boost::graph_traits< HEGraph::BGLGraph >::vertices_size_type HEVertexSize;

// these containers are used instead of iterators when accessing
// adjacent vertices, edges, faces.
// FIXME: it may be faster to rewrite the code so it uses iterators, as does the BGL.
typedef std::vector<HEVertex> VertexVector;
typedef std::vector<HEFace> FaceVector;
typedef std::vector<HEEdge> EdgeVector;

} // end namespace
#endif

<|endoftext|>


<commit_before>class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> m;
        vector<int> ans;
        for (int i = 0; i < nums.size(); i++)
        {
            m[nums[i]]=i;
        }
        for(int i = 0; i < nums.size(); i++)
        {
            if(m.find(target - nums[i]) != m.end() && m[target - nums[i]] != i)
            {
                ans.push_back(i + 1);
                ans.push_back(m[target - nums[i]] + 1);
                break;
            }
        }
        return ans;
    }
};<commit_msg>Create code.cpp<commit_after>class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> m;
        vector<int> ans;
        for (int i = 0; i < nums.size(); i++)
        {
            m[nums[i]] = i;
        }
        for(int i = 0; i < nums.size(); i++)
        {
            if(m.find(target - nums[i]) != m.end() && m[target - nums[i]] != i)
            {
                ans.push_back(i);
                ans.push_back(m[target - nums[i]]);
                break;
            }
        }
        return ans;
    }
};
<|endoftext|>


<commit_before>#include "SIO/SIOSimCalHitHandler.h"

#include "SIO/LCSIO.h"

#include "EVENT/LCIO.h"
#include "EVENT/MCParticle.h"
#include "EVENT/SimCalorimeterHit.h"
#include "IOIMPL/SimCalorimeterHitIOImpl.h"
#include "IMPL/LCFlagImpl.h"

#include "SIO_functions.h"
#include "SIO_block.h"

using namespace EVENT ;
using namespace IMPL ;
using namespace IOIMPL ;

namespace SIO{

  unsigned int SIOSimCalHitHandler::read(SIO_stream* stream,
				      LCObject** objP){
    unsigned int status ;

    // create a new object :
    SimCalorimeterHitIOImpl* hit  = new SimCalorimeterHitIOImpl ;
    *objP = hit ;

    SIO_DATA( stream ,  &(hit->_cellID0) , 1  ) ;

    // in v00-08 cellid1 has been stored by default
    if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_ID1 ) ||

	( SIO_VERSION_MAJOR(_vers)==0 && SIO_VERSION_MINOR(_vers)==8) ){

      SIO_DATA( stream ,  &(hit->_cellID1) , 1  ) ;

    }
    SIO_DATA( stream ,  &(hit->_energy) , 1  ) ;

    if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_LONG ) ){
      SIO_DATA( stream ,  hit->_position  , 3 ) ;
    }

    // read MCContributions
    int nCon ;
    SIO_DATA( stream ,  &nCon , 1  ) ;

    for(int i=0; i< nCon ; i++){

      MCParticleCont* mcCon = new MCParticleCont ;
      SIO_PNTR( stream , &(mcCon->Particle)  ) ;
      SIO_DATA( stream , &(mcCon->Energy) , 1 ) ;
      SIO_DATA( stream , &(mcCon->Time)   , 1 ) ;
	SIO_DATA( stream , &(mcCon->PDG)    , 1 ) ;

    if( _vers > SIO_VERSION_ENCODE( 1, 52 ) ){
        if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_STEP ) ){
            SIO_DATA( stream , &(mcCon->StepPosition[0])    , 1 ) ;
            SIO_DATA( stream , &(mcCon->StepPosition[1])    , 1 ) ;
            SIO_DATA( stream , &(mcCon->StepPosition[2])    , 1 ) ;
        }
      }

      hit->_vec.push_back(  mcCon  );
    }

    // read a pointer tag for  reference to calorimeter hits

    if( _vers > SIO_VERSION_ENCODE( 1, 0) ){
      SIO_PTAG( stream , dynamic_cast<const SimCalorimeterHit*>(hit) ) ;
    }

    return ( SIO_BLOCK_SUCCESS ) ;

  }

  unsigned int SIOSimCalHitHandler::write(SIO_stream* stream,
				       const LCObject* obj){

    unsigned int status ;

    const SimCalorimeterHit* hit = dynamic_cast<const SimCalorimeterHit*>(obj)  ;

    LCSIO_WRITE( stream, hit->getCellID0()  ) ;
    if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_ID1 ) ){
      LCSIO_WRITE( stream, hit->getCellID1()  ) ;
    }
    LCSIO_WRITE( stream, hit->getEnergy()  ) ;
    // as SIO doesn't provide a write function with const arguments
    // we have to cast away the constness

    if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_LONG ) ){
      float* pos = const_cast<float*> ( hit->getPosition() ) ;
      SIO_DATA( stream,  pos , 3 ) ;
    }
    // now the MCParticle contributions
    int nMC = hit->getNMCContributions() ;
    SIO_DATA( stream,  &nMC , 1 ) ;

    for(int i=0; i<nMC ;i++){

      const MCParticle* part = hit->getParticleCont(i)  ;
      SIO_PNTR( stream , &part ) ;

      LCSIO_WRITE( stream, hit->getEnergyCont(i)  ) ;
      LCSIO_WRITE( stream, hit->getTimeCont(i)  ) ;
	  LCSIO_WRITE( stream, hit->getPDGCont(i)  ) ;

      if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_STEP ) ){
          const float* sp = hit->getStepPosition(i) ;
          LCSIO_WRITE( stream, sp[0] ) ;
          LCSIO_WRITE( stream, sp[1] ) ;
          LCSIO_WRITE( stream, sp[2] ) ;
      }
    }

    // add a pointer tag for reference to sim. calorimeter hits - added in v1.1
    SIO_PTAG( stream , hit ) ;

    return ( SIO_BLOCK_SUCCESS ) ;

  }

} // namespace
<commit_msg> - fixed reading of PDG code (only if CHBIT_PDG(STEP) is set) <commit_after>#include "SIO/SIOSimCalHitHandler.h"

#include "SIO/LCSIO.h"

#include "EVENT/LCIO.h"
#include "EVENT/MCParticle.h"
#include "EVENT/SimCalorimeterHit.h"
#include "IOIMPL/SimCalorimeterHitIOImpl.h"
#include "IMPL/LCFlagImpl.h"

#include "SIO_functions.h"
#include "SIO_block.h"

using namespace EVENT ;
using namespace IMPL ;
using namespace IOIMPL ;

namespace SIO{

  unsigned int SIOSimCalHitHandler::read(SIO_stream* stream,
				      LCObject** objP){
    unsigned int status ;

    // create a new object :
    SimCalorimeterHitIOImpl* hit  = new SimCalorimeterHitIOImpl ;
    *objP = hit ;

    SIO_DATA( stream ,  &(hit->_cellID0) , 1  ) ;

    // in v00-08 cellid1 has been stored by default
    if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_ID1 ) ||

	( SIO_VERSION_MAJOR(_vers)==0 && SIO_VERSION_MINOR(_vers)==8) ){

      SIO_DATA( stream ,  &(hit->_cellID1) , 1  ) ;

    }
    SIO_DATA( stream ,  &(hit->_energy) , 1  ) ;

    if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_LONG ) ){
      SIO_DATA( stream ,  hit->_position  , 3 ) ;
    }

    // read MCContributions
    int nCon ;
    SIO_DATA( stream ,  &nCon , 1  ) ;

    for(int i=0; i< nCon ; i++){

      MCParticleCont* mcCon = new MCParticleCont ;
      SIO_PNTR( stream , &(mcCon->Particle)  ) ;
      SIO_DATA( stream , &(mcCon->Energy) , 1 ) ;
      SIO_DATA( stream , &(mcCon->Time)   , 1 ) ;

      if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_PDG ) ){  // BIT_PDG == BIT_STEP
	SIO_DATA( stream , &(mcCon->PDG)    , 1 ) ;
      }

      if( _vers > SIO_VERSION_ENCODE( 1, 52 ) ){
	if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_STEP ) ){
	  SIO_DATA( stream , &(mcCon->StepPosition[0])    , 1 ) ;
	  SIO_DATA( stream , &(mcCon->StepPosition[1])    , 1 ) ;
	  SIO_DATA( stream , &(mcCon->StepPosition[2])    , 1 ) ;
        }
      }

      hit->_vec.push_back(  mcCon  );
    }

    // read a pointer tag for  reference to calorimeter hits

    if( _vers > SIO_VERSION_ENCODE( 1, 0) ){
      SIO_PTAG( stream , dynamic_cast<const SimCalorimeterHit*>(hit) ) ;
    }

    return ( SIO_BLOCK_SUCCESS ) ;

  }

  unsigned int SIOSimCalHitHandler::write(SIO_stream* stream,
				       const LCObject* obj){

    unsigned int status ;

    const SimCalorimeterHit* hit = dynamic_cast<const SimCalorimeterHit*>(obj)  ;

    LCSIO_WRITE( stream, hit->getCellID0()  ) ;
    if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_ID1 ) ){
      LCSIO_WRITE( stream, hit->getCellID1()  ) ;
    }
    LCSIO_WRITE( stream, hit->getEnergy()  ) ;
    // as SIO doesn't provide a write function with const arguments
    // we have to cast away the constness

    if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_LONG ) ){
      float* pos = const_cast<float*> ( hit->getPosition() ) ;
      SIO_DATA( stream,  pos , 3 ) ;
    }
    // now the MCParticle contributions
    int nMC = hit->getNMCContributions() ;
    SIO_DATA( stream,  &nMC , 1 ) ;

    for(int i=0; i<nMC ;i++){

      const MCParticle* part = hit->getParticleCont(i)  ;
      SIO_PNTR( stream , &part ) ;

      LCSIO_WRITE( stream, hit->getEnergyCont(i)  ) ;
      LCSIO_WRITE( stream, hit->getTimeCont(i)  ) ;

      if( LCFlagImpl(_flag).bitSet( LCIO::CHBIT_STEP ) ){

	LCSIO_WRITE( stream, hit->getPDGCont(i)  ) ;

	// const float* sp = hit->getStepPosition(i) ;
	// LCSIO_WRITE( stream, sp[0] ) ;
	// LCSIO_WRITE( stream, sp[1] ) ;
	// LCSIO_WRITE( stream, sp[2] ) ;
	float* sp = const_cast<float*> ( hit->getStepPosition(i) ) ;
	SIO_DATA( stream,  sp , 3 ) ;
      }
    }

    // add a pointer tag for reference to sim. calorimeter hits - added in v1.1
    SIO_PTAG( stream , hit ) ;

    return ( SIO_BLOCK_SUCCESS ) ;

  }

} // namespace
<|endoftext|>


<commit_before>#include "dioptre/physics/bullet/physics.h"
#include "dioptre/physics/bullet/shape.h"
#include "dioptre/locator.h"

#include <iostream>

namespace dioptre {
namespace physics {
namespace bullet {

int Physics::initialize() {
  broadphase_ = std::unique_ptr<btBroadphaseInterface>(new btDbvtBroadphase());
  collisionConfiguration_ = std::unique_ptr<btDefaultCollisionConfiguration>(new btDefaultCollisionConfiguration());
  dispatcher_ = std::unique_ptr<btCollisionDispatcher>(new btCollisionDispatcher(collisionConfiguration_.get()));
  solver_ = std::unique_ptr<btSequentialImpulseConstraintSolver>(new btSequentialImpulseConstraintSolver);

  dynamicsWorld_ = std::unique_ptr<btDiscreteDynamicsWorld>(new btDiscreteDynamicsWorld(dispatcher_.get(), broadphase_.get(), solver_.get(), collisionConfiguration_.get()));

  auto gravity = world_->getGravity();
  dynamicsWorld_->setGravity(btVector3(gravity.x, gravity.y, gravity.z));

  debugDrawer_ = std::unique_ptr<DebugDrawer>(new DebugDrawer());
  debugDrawer_->setDebugMode(btIDebugDraw::DBG_DrawWireframe);
  dynamicsWorld_->setDebugDrawer(debugDrawer_.get());

  LOG4CXX_INFO(logger_, "Bullet engine initialized.");

  return 0;
}

void Physics::initializeWorld() {
  LOG4CXX_INFO(logger_, "Initializing physics world.");
  for (auto it = world_->begin(); it != world_->end(); it++) {
    initializeRigidBody(*it);
  }
}

void Physics::initializeRigidBody(dioptre::physics::RigidBody* body) {
  auto shape = dynamic_cast<dioptre::physics::bullet::Shape*>(body->getShape());
  btCollisionShape* boxCollisionShape = shape->getCollisionShape();

  auto component = body->getComponent();
  auto object = component->getObject();
  auto transform = object->getTransform();
  auto position = transform->getPosition();
  auto orientation = body->getComponent()->getObject()->getTransform()->getOrientation();
  auto inertia = body->getInertia();
  auto mass = body->getMass();

  LOG4CXX_INFO(logger_, "Initializing rigid body." << object->getName());

  btDefaultMotionState* motionstate = new btDefaultMotionState(btTransform(
    btQuaternion(orientation.x, orientation.y, orientation.z, orientation.w),
    btVector3(position.x, position.y, position.z)
  ));

  btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(
      mass, // mass, in kg. 0 -> Static object, will never move.
      motionstate,
      boxCollisionShape, // collision shape of body
      btVector3(inertia.x, inertia.y, inertia.z) // local inertia
      );

  btRigidBody *rigidBody = new btRigidBody(rigidBodyCI);

  rigidBodies_.push_back(rigidBody);
  dynamicsWorld_->addRigidBody(rigidBody);

  rigidBody->setUserPointer(object);
}

void ScreenPosToWorldRay(
    double mouseX, double mouseY,             // Mouse position, in pixels, from bottom-left corner of the window
    int screenWidth, int screenHeight,  // Window size, in pixels
    glm::mat4 ViewMatrix,               // Camera position and orientation
    glm::mat4 ProjectionMatrix,         // Camera parameters (ratio, field of view, near and far planes)
    glm::vec3& out_origin,              // Ouput : Origin of the ray. /!\ Starts at the near plane, so if you want the ray to start at the camera's position instead, ignore this.
    glm::vec3& out_direction            // Ouput : Direction, in world space, of the ray that goes "through" the mouse.
    ){

  // The ray Start and End positions, in Normalized Device Coordinates (Have you read Tutorial 4 ?)
  glm::vec4 lRayStart_NDC(
      ((float)mouseX/(float)screenWidth  - 0.5f) * 2.0f, // [0,1024] -> [-1,1]
      ((float)mouseY/(float)screenHeight - 0.5f) * 2.0f, // [0, 768] -> [-1,1]
      -1.0, // The near plane maps to Z=-1 in Normalized Device Coordinates
      1.0f
      );
  glm::vec4 lRayEnd_NDC(
      ((float)mouseX/(float)screenWidth  - 0.5f) * 2.0f,
      ((float)mouseY/(float)screenHeight - 0.5f) * 2.0f,
      0.0,
      1.0f
      );

  // Faster way (just one inverse)
  glm::mat4 M = glm::inverse(ProjectionMatrix * ViewMatrix);
  glm::vec4 lRayStart_world = M * lRayStart_NDC; lRayStart_world/=lRayStart_world.w;
  glm::vec4 lRayEnd_world   = M * lRayEnd_NDC  ; lRayEnd_world  /=lRayEnd_world.w;

  glm::vec3 lRayDir_world(lRayEnd_world - lRayStart_world);
  lRayDir_world = glm::normalize(lRayDir_world);

  out_origin = glm::vec3(lRayStart_world);
  out_direction = glm::normalize(lRayDir_world);
}

void Physics::castRay(dioptre::mouse::Position position) {
  LOG4CXX_INFO(logger_, "Casting ray at:" << position.x << "x" << position.y);

  auto graphics = dioptre::Locator::getInstance<dioptre::graphics::GraphicsInterface>(dioptre::Module::M_GRAPHICS);
  auto debug = graphics->getDebug();
  auto camera = graphics->getCamera();
  auto window = dioptre::Locator::getInstance<dioptre::window::WindowInterface>(dioptre::Module::M_WINDOW);
  auto size = window->getSize();

  auto view = glm::inverse(camera->getTransform()->getMatrix());
  auto projection = camera->getProjectionMatrix();

  position.y = size.height - position.y;
  glm::vec3 rayStart;
  glm::vec3 rayEnd;
  glm::vec3 rayDirection;
  ScreenPosToWorldRay(
      position.x, position.y,
      size.width, size.height,
      view,
      projection,
      rayStart,
      rayDirection
  );

  rayDirection = rayDirection * 1000.0f;
  rayEnd = rayStart + rayDirection;

  btCollisionWorld::ClosestRayResultCallback rayCallback(btVector3(rayStart.x, rayStart.y, rayStart.z),
                                                         btVector3(rayEnd.x, rayEnd.y, rayEnd.z));

  dynamicsWorld_->rayTest(btVector3(rayStart.x, rayStart.y, rayStart.z),
                          btVector3(rayEnd.x, rayEnd.y, rayEnd.z),
                          rayCallback);

  if (rayCallback.hasHit()) {
    LOG4CXX_INFO(logger_, "Ray hit object.");

    auto hitPoint = rayCallback.m_hitPointWorld;
    glm::vec3 glmHitPoint = glm::vec3(hitPoint.x(), hitPoint.y(), hitPoint.z());
    debug->addCross(glmHitPoint);

    dioptre::Object* object = static_cast<dioptre::Object*>(rayCallback.m_collisionObject->getUserPointer());
    object->handleClick(glmHitPoint);
  } else {
    LOG4CXX_INFO(logger_, "Ray hit background.");
  }
}

void Physics::debug() {
  auto graphics = dioptre::Locator::getInstance<dioptre::graphics::GraphicsInterface>(dioptre::Module::M_GRAPHICS);
  auto debug = graphics->getDebug();

  if (debug) {
    debug->reset();
  }

  dynamicsWorld_->debugDrawWorld();
}

void Physics::simulate() {

}

void Physics::destroy() {

}

} // bullet
} // physics
} // dioptre
<commit_msg>remove debug cross when clicked on object<commit_after>#include "dioptre/physics/bullet/physics.h"
#include "dioptre/physics/bullet/shape.h"
#include "dioptre/locator.h"

#include <iostream>

namespace dioptre {
namespace physics {
namespace bullet {

int Physics::initialize() {
  broadphase_ = std::unique_ptr<btBroadphaseInterface>(new btDbvtBroadphase());
  collisionConfiguration_ = std::unique_ptr<btDefaultCollisionConfiguration>(new btDefaultCollisionConfiguration());
  dispatcher_ = std::unique_ptr<btCollisionDispatcher>(new btCollisionDispatcher(collisionConfiguration_.get()));
  solver_ = std::unique_ptr<btSequentialImpulseConstraintSolver>(new btSequentialImpulseConstraintSolver);

  dynamicsWorld_ = std::unique_ptr<btDiscreteDynamicsWorld>(new btDiscreteDynamicsWorld(dispatcher_.get(), broadphase_.get(), solver_.get(), collisionConfiguration_.get()));

  auto gravity = world_->getGravity();
  dynamicsWorld_->setGravity(btVector3(gravity.x, gravity.y, gravity.z));

  debugDrawer_ = std::unique_ptr<DebugDrawer>(new DebugDrawer());
  debugDrawer_->setDebugMode(btIDebugDraw::DBG_DrawWireframe);
  dynamicsWorld_->setDebugDrawer(debugDrawer_.get());

  LOG4CXX_INFO(logger_, "Bullet engine initialized.");

  return 0;
}

void Physics::initializeWorld() {
  LOG4CXX_INFO(logger_, "Initializing physics world.");
  for (auto it = world_->begin(); it != world_->end(); it++) {
    initializeRigidBody(*it);
  }
}

void Physics::initializeRigidBody(dioptre::physics::RigidBody* body) {
  auto shape = dynamic_cast<dioptre::physics::bullet::Shape*>(body->getShape());
  btCollisionShape* boxCollisionShape = shape->getCollisionShape();

  auto component = body->getComponent();
  auto object = component->getObject();
  auto transform = object->getTransform();
  auto position = transform->getPosition();
  auto orientation = body->getComponent()->getObject()->getTransform()->getOrientation();
  auto inertia = body->getInertia();
  auto mass = body->getMass();

  LOG4CXX_INFO(logger_, "Initializing rigid body." << object->getName());

  btDefaultMotionState* motionstate = new btDefaultMotionState(btTransform(
    btQuaternion(orientation.x, orientation.y, orientation.z, orientation.w),
    btVector3(position.x, position.y, position.z)
  ));

  btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(
      mass, // mass, in kg. 0 -> Static object, will never move.
      motionstate,
      boxCollisionShape, // collision shape of body
      btVector3(inertia.x, inertia.y, inertia.z) // local inertia
      );

  btRigidBody *rigidBody = new btRigidBody(rigidBodyCI);

  rigidBodies_.push_back(rigidBody);
  dynamicsWorld_->addRigidBody(rigidBody);

  rigidBody->setUserPointer(object);
}

void ScreenPosToWorldRay(
    double mouseX, double mouseY,             // Mouse position, in pixels, from bottom-left corner of the window
    int screenWidth, int screenHeight,  // Window size, in pixels
    glm::mat4 ViewMatrix,               // Camera position and orientation
    glm::mat4 ProjectionMatrix,         // Camera parameters (ratio, field of view, near and far planes)
    glm::vec3& out_origin,              // Ouput : Origin of the ray. /!\ Starts at the near plane, so if you want the ray to start at the camera's position instead, ignore this.
    glm::vec3& out_direction            // Ouput : Direction, in world space, of the ray that goes "through" the mouse.
    ){

  // The ray Start and End positions, in Normalized Device Coordinates (Have you read Tutorial 4 ?)
  glm::vec4 lRayStart_NDC(
      ((float)mouseX/(float)screenWidth  - 0.5f) * 2.0f, // [0,1024] -> [-1,1]
      ((float)mouseY/(float)screenHeight - 0.5f) * 2.0f, // [0, 768] -> [-1,1]
      -1.0, // The near plane maps to Z=-1 in Normalized Device Coordinates
      1.0f
      );
  glm::vec4 lRayEnd_NDC(
      ((float)mouseX/(float)screenWidth  - 0.5f) * 2.0f,
      ((float)mouseY/(float)screenHeight - 0.5f) * 2.0f,
      0.0,
      1.0f
      );

  // Faster way (just one inverse)
  glm::mat4 M = glm::inverse(ProjectionMatrix * ViewMatrix);
  glm::vec4 lRayStart_world = M * lRayStart_NDC; lRayStart_world/=lRayStart_world.w;
  glm::vec4 lRayEnd_world   = M * lRayEnd_NDC  ; lRayEnd_world  /=lRayEnd_world.w;

  glm::vec3 lRayDir_world(lRayEnd_world - lRayStart_world);
  lRayDir_world = glm::normalize(lRayDir_world);

  out_origin = glm::vec3(lRayStart_world);
  out_direction = glm::normalize(lRayDir_world);
}

void Physics::castRay(dioptre::mouse::Position position) {
  LOG4CXX_INFO(logger_, "Casting ray at:" << position.x << "x" << position.y);

  auto graphics = dioptre::Locator::getInstance<dioptre::graphics::GraphicsInterface>(dioptre::Module::M_GRAPHICS);
  auto debug = graphics->getDebug();
  auto camera = graphics->getCamera();
  auto window = dioptre::Locator::getInstance<dioptre::window::WindowInterface>(dioptre::Module::M_WINDOW);
  auto size = window->getSize();

  auto view = glm::inverse(camera->getTransform()->getMatrix());
  auto projection = camera->getProjectionMatrix();

  position.y = size.height - position.y;
  glm::vec3 rayStart;
  glm::vec3 rayEnd;
  glm::vec3 rayDirection;
  ScreenPosToWorldRay(
      position.x, position.y,
      size.width, size.height,
      view,
      projection,
      rayStart,
      rayDirection
  );

  rayDirection = rayDirection * 1000.0f;
  rayEnd = rayStart + rayDirection;

  btCollisionWorld::ClosestRayResultCallback rayCallback(btVector3(rayStart.x, rayStart.y, rayStart.z),
                                                         btVector3(rayEnd.x, rayEnd.y, rayEnd.z));

  dynamicsWorld_->rayTest(btVector3(rayStart.x, rayStart.y, rayStart.z),
                          btVector3(rayEnd.x, rayEnd.y, rayEnd.z),
                          rayCallback);

  if (rayCallback.hasHit()) {
    LOG4CXX_INFO(logger_, "Ray hit object.");

    auto hitPoint = rayCallback.m_hitPointWorld;
    glm::vec3 glmHitPoint = glm::vec3(hitPoint.x(), hitPoint.y(), hitPoint.z());
    /* debug->addCross(glmHitPoint); */

    dioptre::Object* object = static_cast<dioptre::Object*>(rayCallback.m_collisionObject->getUserPointer());
    object->handleClick(glmHitPoint);
  } else {
    LOG4CXX_INFO(logger_, "Ray hit background.");
  }
}

void Physics::debug() {
  auto graphics = dioptre::Locator::getInstance<dioptre::graphics::GraphicsInterface>(dioptre::Module::M_GRAPHICS);
  auto debug = graphics->getDebug();

  if (debug) {
    debug->reset();
  }

  dynamicsWorld_->debugDrawWorld();
}

void Physics::simulate() {

}

void Physics::destroy() {

}

} // bullet
} // physics
} // dioptre
<|endoftext|>


<commit_before>/*
 *	limiter≈
 *	Jamoma AudioGraph external object for Max
 *	Copyright © 2008 by Timothy Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "maxAudioGraph.h"

int TTCLASSWRAPPERMAX_EXPORT main(void)
{
	TTAudioGraphInit();
	wrapAsMaxAudioGraph(TT("clipper"), "jcom.clip≈", NULL);
	wrapAsMaxAudioGraph(TT("clipper"), "clip≈", NULL);
	return 0;
}

<commit_msg>jcom.clip≈: correcting header info<commit_after>/*
 *	clip≈
 *	Jamoma AudioGraph external object for Max
 *	Copyright © 2012 by Nils Peters
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "maxAudioGraph.h"

int TTCLASSWRAPPERMAX_EXPORT main(void)
{
	TTAudioGraphInit();
	wrapAsMaxAudioGraph(TT("clipper"), "jcom.clip≈", NULL);
	wrapAsMaxAudioGraph(TT("clipper"), "clip≈", NULL);
	return 0;
}

<|endoftext|>