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

/**
 * \file rq_sensor.cpp
 * \date July 14, 2014
 *  \author Jonathan Savoie <jonathan.savoie@robotiq.com>
 *  \maintainer Nicolas Lauzier <nicolas@robotiq.com>
 */

#include <string.h>
#include <stdio.h>

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/WrenchStamped.h"
#include "robotiq_force_torque_sensor/rq_sensor_state.h"
#include "robotiq_force_torque_sensor/ft_sensor.h"
#include "robotiq_force_torque_sensor/sensor_accessor.h"

static void decode_message_and_do(INT_8 const  * const buff, INT_8 * const ret);
static void wait_for_other_connection(void);
static int max_retries_(100);

ros::Publisher sensor_pub_acc;

/**
 * \brief Decode the message received and do the associated action
 * \param buff message to decode
 * \param ret buffer containing the return value from a GET command
 */
static void decode_message_and_do(INT_8 const  * const buff, INT_8 * const ret)
{
	INT_8 get_or_set[3];
	INT_8 nom_var[4];

	if(buff == NULL || strlen(buff) != 7)
	{
		return;
	}

	strncpy(get_or_set, &buff[0], 3);
	strncpy(nom_var, &buff[4], strlen(buff) -3);

	if(strstr(get_or_set, "GET"))
	{
		rq_state_get_command(nom_var, ret);
	}
	else if(strstr(get_or_set, "SET"))
	{
		if(strstr(nom_var, "ZRO"))
		{
			rq_state_do_zero_force_flag();
			strcpy(ret,"Done");
		}
	}
}

bool receiverCallback(robotiq_force_torque_sensor::sensor_accessor::Request& req,
	robotiq_force_torque_sensor::sensor_accessor::Response& res)
{
	ROS_INFO("I heard: [%s]",req.command.c_str());
	INT_8 buffer[512];
	decode_message_and_do((char*)req.command.c_str(), buffer);
	res.res = buffer;
	ROS_INFO("I send: [%s]", res.res.c_str());
	return true;
}

/**
 * \fn static void wait_for_other_connection()
 * \brief Each second, checks for a sensor that has been connected
 */
static void wait_for_other_connection(void)
{
	INT_8 ret;

	while(ros::ok())
	{
		ROS_INFO("Waiting for sensor connection...");
		usleep(1000000);//Attend 1 seconde.

		ret = rq_sensor_state(max_retries_);
		if(ret == 0)
		{
			ROS_INFO("Sensor connected!");
			break;
		}

		ros::spinOnce();
	}
}

/**
 * \fn void get_data(void)
 * \brief Builds the message with the force/torque data
 * \return ft_sensor updated with the latest data
 */
static robotiq_force_torque_sensor::ft_sensor get_data(void)
{
	robotiq_force_torque_sensor::ft_sensor msgStream;

	msgStream.Fx = rq_state_get_received_data(0);
	msgStream.Fy = rq_state_get_received_data(1);
	msgStream.Fz = rq_state_get_received_data(2);
	msgStream.Mx = rq_state_get_received_data(3);
	msgStream.My = rq_state_get_received_data(4);
	msgStream.Mz = rq_state_get_received_data(5);

	return msgStream;
}

int main(int argc, char **argv)
{
	ros::init(argc, argv, "robotiq_force_torque_sensor");
	ros::NodeHandle n;
	n.param("~max_retries", max_retries_, 100);

	INT_8 bufStream[512];
	robotiq_force_torque_sensor::ft_sensor msgStream;
	INT_8 ret;

	//If we can't initialize, we return an error
	ret = rq_sensor_state(max_retries_);
	if(ret == -1)
	{
		wait_for_other_connection();
	}

	//Reads basic info on the sensor
	ret = rq_sensor_state(max_retries_);
	if(ret == -1)
	{
		wait_for_other_connection();
	}

	//Starts the stream
	ret = rq_sensor_state(max_retries_);
	if(ret == -1)
	{
		wait_for_other_connection();
	}

	ros::Publisher sensor_pub = n.advertise<robotiq_force_torque_sensor::ft_sensor>("robotiq_force_torque_sensor", 512);
	ros::Publisher wrench_pub = n.advertise<geometry_msgs::WrenchStamped>("robotiq_force_torque_wrench", 512);
	ros::ServiceServer service = n.advertiseService("robotiq_force_torque_sensor_acc", receiverCallback);

	//std_msgs::String msg;
	geometry_msgs::WrenchStamped wrenchMsg;
	ros::param::param<std::string>("~frame_id", wrenchMsg.header.frame_id, "robotiq_force_torque_frame_id");

	ROS_INFO("Starting Sensor");
	while(ros::ok())
	{
		ret = rq_sensor_state(max_retries_);

		if(ret == -1)
		{
			wait_for_other_connection();
		}

		if(rq_sensor_get_current_state() == RQ_STATE_RUN)
		{
			strcpy(bufStream,"");
			msgStream = get_data();

			if(rq_state_got_new_message())
			{
				sensor_pub.publish(msgStream);

				//compose WrenchStamped Msg
				wrenchMsg.header.stamp = ros::Time::now();
				wrenchMsg.wrench.force.x = msgStream.Fx;
				wrenchMsg.wrench.force.y = msgStream.Fy;
				wrenchMsg.wrench.force.z = msgStream.Fz;
				wrenchMsg.wrench.torque.x = msgStream.Mx;
				wrenchMsg.wrench.torque.y = msgStream.My;
				wrenchMsg.wrench.torque.z = msgStream.Mz;
				wrench_pub.publish(wrenchMsg);
			}
		}

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

/**
 * \file rq_sensor.cpp
 * \date July 14, 2014
 *  \author Jonathan Savoie <jonathan.savoie@robotiq.com>
 *  \maintainer Nicolas Lauzier <nicolas@robotiq.com>
 */

#include <string.h>
#include <stdio.h>

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/WrenchStamped.h"
#include "robotiq_force_torque_sensor/rq_sensor_state.h"
#include "robotiq_force_torque_sensor/ft_sensor.h"
#include "robotiq_force_torque_sensor/sensor_accessor.h"

static void decode_message_and_do(INT_8 const  * const buff, INT_8 * const ret);
static void wait_for_other_connection(void);
static int max_retries_(100);

ros::Publisher sensor_pub_acc;

/**
 * \brief Decode the message received and do the associated action
 * \param buff message to decode
 * \param ret buffer containing the return value from a GET command
 */
static void decode_message_and_do(INT_8 const  * const buff, INT_8 * const ret)
{
	INT_8 get_or_set[3];
	INT_8 nom_var[4];

	if(buff == NULL || strlen(buff) != 7)
	{
		return;
	}

	strncpy(get_or_set, &buff[0], 3);
	strncpy(nom_var, &buff[4], strlen(buff) -3);

	if(strstr(get_or_set, "GET"))
	{
		rq_state_get_command(nom_var, ret);
	}
	else if(strstr(get_or_set, "SET"))
	{
		if(strstr(nom_var, "ZRO"))
		{
			rq_state_do_zero_force_flag();
			strcpy(ret,"Done");
		}
	}
}

bool receiverCallback(robotiq_force_torque_sensor::sensor_accessor::Request& req,
	robotiq_force_torque_sensor::sensor_accessor::Response& res)
{
	ROS_INFO("I heard: [%s]",req.command.c_str());
	INT_8 buffer[512];
	decode_message_and_do((char*)req.command.c_str(), buffer);
	res.res = buffer;
	ROS_INFO("I send: [%s]", res.res.c_str());
	return true;
}

/**
 * \fn static void wait_for_other_connection()
 * \brief Each second, checks for a sensor that has been connected
 */
static void wait_for_other_connection(void)
{
	INT_8 ret;

	while(ros::ok())
	{
		ROS_INFO("Waiting for sensor connection...");
		usleep(1000000);//Attend 1 seconde.

		ret = rq_sensor_state(max_retries_);
		if(ret == 0)
		{
			ROS_INFO("Sensor connected!");
			break;
		}

		ros::spinOnce();
	}
}

/**
 * \fn void get_data(void)
 * \brief Builds the message with the force/torque data
 * \return ft_sensor updated with the latest data
 */
static robotiq_force_torque_sensor::ft_sensor get_data(void)
{
	robotiq_force_torque_sensor::ft_sensor msgStream;

	msgStream.Fx = rq_state_get_received_data(0);
	msgStream.Fy = rq_state_get_received_data(1);
	msgStream.Fz = rq_state_get_received_data(2);
	msgStream.Mx = rq_state_get_received_data(3);
	msgStream.My = rq_state_get_received_data(4);
	msgStream.Mz = rq_state_get_received_data(5);

	return msgStream;
}

int main(int argc, char **argv)
{
	ros::init(argc, argv, "robotiq_force_torque_sensor");
	ros::NodeHandle n;
	ros::param::param<int>("~max_retries", max_retries_, 100);

	INT_8 bufStream[512];
	robotiq_force_torque_sensor::ft_sensor msgStream;
	INT_8 ret;

	//If we can't initialize, we return an error
	ret = rq_sensor_state(max_retries_);
	if(ret == -1)
	{
		wait_for_other_connection();
	}

	//Reads basic info on the sensor
	ret = rq_sensor_state(max_retries_);
	if(ret == -1)
	{
		wait_for_other_connection();
	}

	//Starts the stream
	ret = rq_sensor_state(max_retries_);
	if(ret == -1)
	{
		wait_for_other_connection();
	}

	ros::Publisher sensor_pub = n.advertise<robotiq_force_torque_sensor::ft_sensor>("robotiq_force_torque_sensor", 512);
	ros::Publisher wrench_pub = n.advertise<geometry_msgs::WrenchStamped>("robotiq_force_torque_wrench", 512);
	ros::ServiceServer service = n.advertiseService("robotiq_force_torque_sensor_acc", receiverCallback);

	//std_msgs::String msg;
	geometry_msgs::WrenchStamped wrenchMsg;
	ros::param::param<std::string>("~frame_id", wrenchMsg.header.frame_id, "robotiq_force_torque_frame_id");

	ROS_INFO("Starting Sensor");
	while(ros::ok())
	{
		ret = rq_sensor_state(max_retries_);

		if(ret == -1)
		{
			wait_for_other_connection();
		}

		if(rq_sensor_get_current_state() == RQ_STATE_RUN)
		{
			strcpy(bufStream,"");
			msgStream = get_data();

			if(rq_state_got_new_message())
			{
				sensor_pub.publish(msgStream);

				//compose WrenchStamped Msg
				wrenchMsg.header.stamp = ros::Time::now();
				wrenchMsg.wrench.force.x = msgStream.Fx;
				wrenchMsg.wrench.force.y = msgStream.Fy;
				wrenchMsg.wrench.force.z = msgStream.Fz;
				wrenchMsg.wrench.torque.x = msgStream.Mx;
				wrenchMsg.wrench.torque.y = msgStream.My;
				wrenchMsg.wrench.torque.z = msgStream.Mz;
				wrench_pub.publish(wrenchMsg);
			}
		}

		ros::spinOnce();
	}
	return 0;
}
<|endoftext|>


<commit_before>// $Header$

#include "ITSModuleStepperGL.h"

#include <Reve/GLTextNS.h>
#include <Reve/GLUtilNS.h>
#include <Reve/RGTopFrame.h>
#include <Reve/RGEditor.h>
#include <Reve/RGBAPalette.h>

#include <Alieve/ITSModuleStepper.h>
#include <Alieve/ITSScaledModule.h>

#include <TGLDrawFlags.h>

using namespace Reve;
using namespace Alieve;

//______________________________________________________________________
// ITSModuleStepperGL
//

ClassImp(ITSModuleStepperGL)

ITSModuleStepperGL::ITSModuleStepperGL() : TGLObject(), fM(0)
{
  fCached = false; // Disable display list.
}

ITSModuleStepperGL::~ITSModuleStepperGL()
{}

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

Bool_t ITSModuleStepperGL::SetModel(TObject* obj)
{
  if(SetModelCheckClass(obj, ITSModuleStepper::Class())) {
    fM = dynamic_cast<ITSModuleStepper*>(obj);
    return kTRUE;
  }
  return kFALSE;
}

void ITSModuleStepperGL::SetBBox()
{
  // !! This ok if master sub-classed from TAttBBox
  SetAxisAlignedBBox(fM->AssertBBox());
}

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

void ITSModuleStepperGL::DirectDraw(const TGLDrawFlags & flags) const
{
  // printf("ITSModuleStepperGL::DirectDraw Style %d, LOD %d\n", flags.Style(), flags.LOD());

  ITSModuleStepper& MS = *fM;
  Int_t W = Int_t(MS.fStepper->Dx*MS.fStepper->Nx);
  Int_t H = Int_t(MS.fStepper->Dy*MS.fStepper->Ny);
  Float_t dx = W*MS.fWWidth;
  Float_t dy = 6; // H*MS.fWHeight;

  GLboolean lightp;
  glGetBooleanv(GL_LIGHTING, &lightp);
  if (lightp) glDisable(GL_LIGHTING);

  UChar_t color[4];
  ColorFromIdx(MS.fWColor, color);
  glColor4ubv(color);

  // render frame of grid stepper
  if (MS.fRnrFrame)
  {
    glBegin(GL_LINE_LOOP);
    glVertex2f(-1,  -1);
    glVertex2f(W+1, -1);
    glVertex2f(W+1,  H+1);
    glVertex2f(-1 ,  H+1);
    glEnd();
  }

  // triangles
  glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT);
  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

  Float_t sx =0 ,sy = 0;
  switch(MS.fWCorner) {
    case ITSModuleStepper::PT_BottomLeft:
      sy = -dy;
      break;
    case ITSModuleStepper::PT_BottomRight:
      sy = -dy;
      break;
    case ITSModuleStepper::PT_TopLeft:
      sy = H;
      break;
    case ITSModuleStepper::PT_TopRight:
      sy = H;
      break;
    default:
      sy = dy;
      break;
  }

  if (flags.SecSelection()) glPushName(0);
  glPushMatrix();
  glTranslatef(sx, sy, 0.);

  // pager
  if (flags.SecSelection()) glLoadName(2);
  RenderSymbol(dx, dy, 2);
  glTranslatef(dx, 0, 0);
  if (flags.SecSelection()) glLoadName(1);
  RenderSymbol(dx, dy, 1);
  glTranslatef(dx, 0, 0);
  RenderString(Form(" %d/%d ", MS.GetCurrentPage(), MS.GetPages()), dy);
  if (flags.SecSelection()) glLoadName(3);
  RenderSymbol(dx, dy, 3);
  glTranslatef(dx, 0, 0);
  if (flags.SecSelection()) glLoadName(4);
  RenderSymbol(dx, dy, 4);
  glTranslatef(2*dx, 0, 0);

  // scale info
  Int_t cnx = 0, cnz = 0;
  ITSDigitsInfo* di = MS.fDigitsInfo;
  Int_t scale = fM->fScaleInfo->GetScale();
  ITSScaledModule* sm = dynamic_cast<ITSScaledModule*>(*fM->BeginChildren());
  switch(sm->GetSubDetID())
  {
    case 0:
      cnx = di->fSPDScaleX[scale], cnz = di->fSPDScaleZ[scale];
      break;
    case 1:
      cnx = di->fSDDScaleX[scale], cnz = di->fSDDScaleZ[scale];
      break;
    case 2:
      cnx = di->fSSDScale[scale], cnz = 1;
      break;
  }
  RenderString(Form("Scale: %dx%d ", cnx, cnz), dy);

  // up down arrows
  if (flags.SecSelection()) glLoadName(6);
  RenderSymbol(dx, dy, 5);
  if (flags.SecSelection()) glLoadName(7);
  RenderSymbol(dx, dy, 6);
  glTranslatef(2*dx, 0, 0);
  glTranslatef(0, dy*0.25,0);

  glPopMatrix();
  if (flags.SecSelection()) glLoadName(5);
  glPushMatrix();
  glTranslatef(W+2, 0, 0);
  RenderPalette(H, 4);
  glPopMatrix();

  if (flags.SecSelection()) glPopName();

  glPopAttrib();

  if (lightp) glEnable(GL_LIGHTING);
}

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

void ITSModuleStepperGL::RenderPalette(Float_t dx, Float_t dy) const
{
  ITSModule* qs = dynamic_cast<ITSModule*>(*fM->BeginChildren());
  RGBAPalette* p = qs->GetPalette();
  Float_t xs = dx/(p->GetMaxVal()- p->GetMinVal());
  Float_t ys = dy;

  Float_t x  = 0;
  glBegin(GL_QUAD_STRIP);
  for(Int_t i=p->GetMinVal(); i<=p->GetMaxVal(); i++)
  {
    glColor4ubv(p->ColorFromValue(i + p->GetMinVal()));
    glVertex2f(0,  x);
    glVertex2f(ys, x);
    x+=xs;
  }
  glEnd();
}

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

void ITSModuleStepperGL::RenderSymbol(Float_t dx, Float_t dy, Int_t id) const
{
  Float_t xs = dx/4, ys = dy/4;

  if(id == 0) {
    glBegin(GL_QUADS);
    glVertex2f(0,ys); glVertex2f(0, ys*3);
    glVertex2f(dx, ys*3); glVertex2f(dx, ys);
    glEnd();
    return;
  }

  glBegin(GL_TRIANGLES);
  switch (id) {
    case 1:
    {
      glVertex2f(xs*2.5, ys*3); glVertex2f(xs*1.5, ys*2); glVertex2f(xs*2.5, ys);
      break;
    }
    case 2:
    {
      glVertex2f(xs*2, ys*3); glVertex2f(xs, ys*2); glVertex2f(xs*2, ys);
      glVertex2f(xs*3, ys*3); glVertex2f(xs*2, ys*2); glVertex2f(xs*3, ys);
      break;
    }
    case 3:
    {
      glVertex2f(xs*1.5, ys);  glVertex2f(xs*2.5, ys*2); glVertex2f(xs*1.5, ys*3);
      break;
    }
    case 4:
    {
      glVertex2f(xs, ys);  glVertex2f(xs*2, ys*2); glVertex2f(xs, ys*3);
      glVertex2f(xs*2, ys); glVertex2f(xs*3, ys*2); glVertex2f(xs*2, ys*3);
      break;
    }
    case 5:
    {
      glVertex2f(xs, ys*2.5);  glVertex2f(xs*2, ys*3.5); glVertex2f(xs*3, ys*2.5);
      break;
    }
    case 6:
    {
      glVertex2f(xs, ys*1.5);  glVertex2f(xs*2, ys*0.5); glVertex2f(xs*3, ys*1.5);
      break;
    }

    default:
      break;
  }
  glEnd();
}

/**************************************************************************/
void ITSModuleStepperGL::RenderString(TString info, Float_t dy, Bool_t trans) const
{
  Float_t movex = 0;

  GLUtilNS::GL_Capability_Switch texure_on(GL_TEXTURE_2D, true);
  GLTextNS::txfBindFontTexture(GLTextNS::fgDefaultFont);

  glPushMatrix();
  glTranslatef(0, dy*0.25, 0);
  Float_t s = (dy)/ (GLTextNS::fgDefaultFont->max_height());
  Float_t sx = s*0.75; Float_t sy = s*0.8;
  glScalef(sx, sy, 1);
  txfRenderString(GLTextNS::fgDefaultFont, info.Data(), info.Length());
  Int_t w, ma, md;
  txfGetStringMetrics(GLTextNS::fgDefaultFont,info.Data(), info.Length() , w, ma, md);
  movex = w*sx;
  glPopMatrix();

  if(trans)
    glTranslatef(movex, 0, 0);
}

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

void ITSModuleStepperGL::ProcessSelection(UInt_t* ptr, TGLViewer*, TGLScene*)
{
  // Processes secondary selection from TGLViewer.
  // Calls TPointSet3D::PointSelected(Int_t) with index of selected
  // point as an argument.

  if (ptr[0] < 2) return;

  switch (ptr[4]){
    case 1 :
      fM->Previous();
      break;
    case 2:
      fM->Start();
      break;
    case 3:
      fM->Next();
      break;
    case 4:
      fM->End();
      break;
    case 5:
      gReve->GetEditor()->DisplayRenderElement(*fM->BeginChildren());
      break;
    case 6:
    {
      DigitScaleInfo* si = fM->fScaleInfo;
      if(si->fScale < 4)
	si->ScaleChanged(si->fScale + 1);
      gReve->Redraw3D();
      break;
    }
    case 7:
    {
      DigitScaleInfo* si = fM->fScaleInfo;
      if(si->fScale > 0)
	si->ScaleChanged(si->GetScale() - 1);
      gReve->Redraw3D();
      break;
    }
    default:
      break;
  }
}
<commit_msg>Fix obi-wan in SetScale.<commit_after>// $Header$

#include "ITSModuleStepperGL.h"

#include <Reve/GLTextNS.h>
#include <Reve/GLUtilNS.h>
#include <Reve/RGTopFrame.h>
#include <Reve/RGEditor.h>
#include <Reve/RGBAPalette.h>

#include <Alieve/ITSModuleStepper.h>
#include <Alieve/ITSScaledModule.h>

#include <TGLDrawFlags.h>

using namespace Reve;
using namespace Alieve;

//______________________________________________________________________
// ITSModuleStepperGL
//

ClassImp(ITSModuleStepperGL)

ITSModuleStepperGL::ITSModuleStepperGL() : TGLObject(), fM(0)
{
  fCached = false; // Disable display list.
}

ITSModuleStepperGL::~ITSModuleStepperGL()
{}

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

Bool_t ITSModuleStepperGL::SetModel(TObject* obj)
{
  if(SetModelCheckClass(obj, ITSModuleStepper::Class())) {
    fM = dynamic_cast<ITSModuleStepper*>(obj);
    return kTRUE;
  }
  return kFALSE;
}

void ITSModuleStepperGL::SetBBox()
{
  // !! This ok if master sub-classed from TAttBBox
  SetAxisAlignedBBox(fM->AssertBBox());
}

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

void ITSModuleStepperGL::DirectDraw(const TGLDrawFlags & flags) const
{
  // printf("ITSModuleStepperGL::DirectDraw Style %d, LOD %d\n", flags.Style(), flags.LOD());

  ITSModuleStepper& MS = *fM;
  Int_t W = Int_t(MS.fStepper->Dx*MS.fStepper->Nx);
  Int_t H = Int_t(MS.fStepper->Dy*MS.fStepper->Ny);
  Float_t dx = W*MS.fWWidth;
  Float_t dy = 6; // H*MS.fWHeight;

  GLboolean lightp;
  glGetBooleanv(GL_LIGHTING, &lightp);
  if (lightp) glDisable(GL_LIGHTING);

  UChar_t color[4];
  ColorFromIdx(MS.fWColor, color);
  glColor4ubv(color);

  // render frame of grid stepper
  if (MS.fRnrFrame)
  {
    glBegin(GL_LINE_LOOP);
    glVertex2f(-1,  -1);
    glVertex2f(W+1, -1);
    glVertex2f(W+1,  H+1);
    glVertex2f(-1 ,  H+1);
    glEnd();
  }

  // triangles
  glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT);
  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

  Float_t sx =0 ,sy = 0;
  switch(MS.fWCorner) {
    case ITSModuleStepper::PT_BottomLeft:
      sy = -dy;
      break;
    case ITSModuleStepper::PT_BottomRight:
      sy = -dy;
      break;
    case ITSModuleStepper::PT_TopLeft:
      sy = H;
      break;
    case ITSModuleStepper::PT_TopRight:
      sy = H;
      break;
    default:
      sy = dy;
      break;
  }

  if (flags.SecSelection()) glPushName(0);
  glPushMatrix();
  glTranslatef(sx, sy, 0.);

  // pager
  if (flags.SecSelection()) glLoadName(2);
  RenderSymbol(dx, dy, 2);
  glTranslatef(dx, 0, 0);
  if (flags.SecSelection()) glLoadName(1);
  RenderSymbol(dx*1.2, dy, 1);
  glTranslatef(dx, 0, 0);
  RenderString(Form(" %d/%d ", MS.GetCurrentPage(), MS.GetPages()), dy);
  if (flags.SecSelection()) glLoadName(3);
  RenderSymbol(dx*1.2, dy, 3);
  glTranslatef(dx, 0, 0);
  if (flags.SecSelection()) glLoadName(4);
  RenderSymbol(dx, dy, 4);
  glTranslatef(2*dx, 0, 0);

  // scale info
  Int_t cnx = 0, cnz = 0;
  ITSDigitsInfo* di = MS.fDigitsInfo;
  Int_t scale = fM->fScaleInfo->GetScale() - 1;
  ITSScaledModule* sm = dynamic_cast<ITSScaledModule*>(*fM->BeginChildren());
  switch(sm->GetSubDetID())
  {
    case 0:
      cnx = di->fSPDScaleX[scale], cnz = di->fSPDScaleZ[scale];
      break;
    case 1:
      cnx = di->fSDDScaleX[scale], cnz = di->fSDDScaleZ[scale];
      break;
    case 2:
      cnx = di->fSSDScale[scale], cnz = 1;
      break;
  }
  if (flags.SecSelection()) glLoadName(0);
  RenderString(Form("Scale"), dy);
  glTranslatef(0.07*dx, 0, 0);
  // up down arrows
  if (flags.SecSelection()) glLoadName(6);
  RenderSymbol(dx*1.2, dy*0.9, 5);

  if (flags.SecSelection()) glLoadName(7);
  RenderSymbol(dx*1.2, dy*0.9, 6);

  glTranslatef(1*dx, 0, 0);
  if (flags.SecSelection()) glLoadName(0);
  RenderString(Form(" %dx%d ", cnx, cnz), dy, kFALSE);

  glPopMatrix();
  if (flags.SecSelection()) glLoadName(5);
  glPushMatrix();
  glTranslatef(W+2, 0, 0);
  RenderPalette(H, 4);
  glPopMatrix();

  if (flags.SecSelection()) glPopName();

  glPopAttrib();

  if (lightp) glEnable(GL_LIGHTING);
}

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

void ITSModuleStepperGL::RenderPalette(Float_t dx, Float_t dy) const
{
  ITSModule* qs = dynamic_cast<ITSModule*>(*fM->BeginChildren());
  RGBAPalette* p = qs->GetPalette();
  Float_t xs = dx/(p->GetMaxVal()- p->GetMinVal());
  Float_t ys = dy;

  Float_t x  = 0;
  glBegin(GL_QUAD_STRIP);
  for(Int_t i=p->GetMinVal(); i<=p->GetMaxVal(); i++)
  {
    glColor4ubv(p->ColorFromValue(i + p->GetMinVal()));
    glVertex2f(0,  x);
    glVertex2f(ys, x);
    x+=xs;
  }
  glEnd();
}

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

void ITSModuleStepperGL::RenderSymbol(Float_t dx, Float_t dy, Int_t id) const
{
  Float_t xs = dx/4, ys = dy/4;

  if(id == 0) {
    glBegin(GL_QUADS);
    glVertex2f(0,ys); glVertex2f(0, ys*3);
    glVertex2f(dx, ys*3); glVertex2f(dx, ys);
    glEnd();
    return;
  }

  glBegin(GL_TRIANGLES);
  switch (id) {
    case 1:
    {
      glVertex2f(xs*2.5, ys*3); glVertex2f(xs*1.5, ys*2); glVertex2f(xs*2.5, ys);
      break;
    }
    case 2:
    {
      glVertex2f(xs*2, ys*3); glVertex2f(xs, ys*2); glVertex2f(xs*2, ys);
      glVertex2f(xs*3, ys*3); glVertex2f(xs*2, ys*2); glVertex2f(xs*3, ys);
      break;
    }
    case 3:
    {
      glVertex2f(xs*1.5, ys);  glVertex2f(xs*2.5, ys*2); glVertex2f(xs*1.5, ys*3);
      break;
    }
    case 4:
    {
      glVertex2f(xs, ys);  glVertex2f(xs*2, ys*2); glVertex2f(xs, ys*3);
      glVertex2f(xs*2, ys); glVertex2f(xs*3, ys*2); glVertex2f(xs*2, ys*3);
      break;
    }
    case 5:
    {
      glVertex2f(xs, ys*2.5);  glVertex2f(xs*2, ys*3.5); glVertex2f(xs*3, ys*2.5);
      break;
    }
    case 6:
    {
      glVertex2f(xs, ys*1.5);  glVertex2f(xs*2, ys*0.5); glVertex2f(xs*3, ys*1.5);
      break;
    }

    default:
      break;
  }
  glEnd();
}

/**************************************************************************/
void ITSModuleStepperGL::RenderString(TString info, Float_t dy, Bool_t trans) const
{
  Float_t movex = 0;

  GLUtilNS::GL_Capability_Switch texure_on(GL_TEXTURE_2D, true);
  GLTextNS::txfBindFontTexture(GLTextNS::fgDefaultFont);

  glPushMatrix();
  glTranslatef(0, dy*0.25, 0);
  Float_t s = (dy)/ (GLTextNS::fgDefaultFont->max_height());
  Float_t sx = s*0.75; Float_t sy = s*0.8;
  glScalef(sx, sy, 1);
  txfRenderString(GLTextNS::fgDefaultFont, info.Data(), info.Length());
  Int_t w, ma, md;
  txfGetStringMetrics(GLTextNS::fgDefaultFont,info.Data(), info.Length() , w, ma, md);
  movex = w*sx;
  glPopMatrix();

  if(trans)
    glTranslatef(movex, 0, 0);
}

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

void ITSModuleStepperGL::ProcessSelection(UInt_t* ptr, TGLViewer*, TGLScene*)
{
  // Processes secondary selection from TGLViewer.
  // Calls TPointSet3D::PointSelected(Int_t) with index of selected
  // point as an argument.

  if (ptr[0] < 2) return;

  switch (ptr[4]){
    case 1:
      fM->Previous();
      break;
    case 2:
      fM->Start();
      break;
    case 3:
      fM->Next();
      break;
    case 4:
      fM->End();
      break;
    case 5:
      gReve->GetEditor()->DisplayRenderElement(*fM->BeginChildren());
      break;
    case 6:
    {
      DigitScaleInfo* si = fM->fScaleInfo;
      if(si->fScale < 5)
      {
	si->ScaleChanged(si->fScale + 1);
	gReve->GetEditor()->DisplayObject(gReve->GetEditor()->GetModel());
	gReve->Redraw3D();
      }
      break;
    }
    case 7:
    {
      DigitScaleInfo* si = fM->fScaleInfo;
      if(si->fScale > 1)
      {
	si->ScaleChanged(si->GetScale() - 1);
	gReve->GetEditor()->DisplayObject(gReve->GetEditor()->GetModel());
	gReve->Redraw3D();
      }
      break;
    }
    default:
      break;
  }
}
<|endoftext|>


<commit_before>

#include <deal.II/base/function.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/timer.h>
#include <deal.II/base/table_handler.h>

#include <deal.II/lac/vector.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/constraint_matrix.h>

#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_refinement.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_out.h>

#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>

#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/fe/fe_q.h>

#include <deal.II/numerics/vector_tools.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/numerics/data_out.h>
#include <deal.II/numerics/error_estimator.h>

#include <fstream>
#include <iostream>

namespace mandy
{

  /**
   * Solve the equations of linear elasticity on a finite element
   * grid.
   */
  template <int dim>
  class LinearElasticity
  {
  public:

    /**
     * Class constructor.
     */
    LinearElasticity (const std::string &prm_file);

    /**
     * Class destructor.
     */
    ~LinearElasticity ();

    void run ();

  private:

    /**
     * Input parameter file.
     */
    dealii::ParameterHandler parameters;

  };

  /**
   * Class constructor.
   */
  template <int dim>
  LinearElasticity<dim>::LinearElasticity (const std::string &prm_file)
  // :
  // dof_handler (triangulation),
  // fe (dealii::FE_Q<dim>(2), dim)
  {
    parameters.declare_entry ("Global mesh refinement steps", "5",
                              dealii::Patterns::Integer (0, 20),
                              "The number of times the 1-cell coarse mesh should "
                              "be refined globally for our computations.");

    parameters.declare_entry ("MaterialID", "0",
                              dealii::Patterns::Anything (),
                              "A functional description of the material ID.");

    parameters.parse_input (prm_file);
  }

  /**
   * Class destructor.
   */
  template <int dim>
  LinearElasticity<dim>::~LinearElasticity ()
  {
    // dof_handler.clear ();
  }

  template <int dim>
  void LinearElasticity<dim>::run ()
  {
  }

} // namespace ewalena

int main ()
{
  try
    {
      mandy::LinearElasticity<2> linear_elasticity ("step-4.prm");
      linear_elasticity.run ();
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    }

  return 0;
}
<commit_msg>Create initial grid.<commit_after>

#include <deal.II/base/function.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/timer.h>
#include <deal.II/base/table_handler.h>

#include <deal.II/lac/vector.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/constraint_matrix.h>

#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_refinement.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_out.h>

#include <deal.II/distributed/tria.h>
#include <deal.II/distributed/grid_refinement.h>

#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>

#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/fe/fe_q.h>

#include <deal.II/numerics/vector_tools.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/numerics/data_out.h>
#include <deal.II/numerics/error_estimator.h>

#include <fstream>
#include <iostream>

namespace mandy
{

  /**
   * Solve the equations of linear elasticity on a finite element
   * grid.
   */
  template <int dim>
  class LinearElasticity
  {
  public:

    /**
     * Class constructor.
     */
    LinearElasticity (const std::string &prm_file);

    /**
     * Class destructor.
     */
    ~LinearElasticity ();

    /**
     * Wrapper function, that controls the order of excecution.
     */
    void run ();

  private:

    /**
     * Make intial coarse grid.
     */
    void make_coarse_grid ();

    /**
     * MPI communicator.
     */
    MPI_Comm mpi_communicator;

    /**
     * A distributed grid on which all computations are done.
     */
    dealii::parallel::distributed::Triangulation<dim> triangulation;

    /**
     * Scalar DoF handler primarily used for interpolating material
     * identification.
     */
    dealii::DoFHandler<dim> dof_handler_scalar;

    // /**
    //  * Scalar valued finite element primarily used for interpolating
    //  * material iudentification.
    //  */
    // dealii::FESystem<dim> fe_scalar;

    /**
     * Index set of locally owned DoFs.
     */
    dealii::IndexSet locally_owned_dofs;

    /**
     * Index set of locally relevant DoFs.
     */
    dealii::IndexSet locally_relevant_dofs;

    /**
     * Parallel iostream.
     */
    dealii::ConditionalOStream pcout;

    /**
     * Stop clock.
     */
    dealii::TimerOutput timer;

    /**
     * Input parameter file.
     */
    dealii::ParameterHandler parameters;

  }; // LinearElasticity

  /**
   * Class constructor.
   */
  template <int dim>
  LinearElasticity<dim>::LinearElasticity (const std::string &prm_file)
    :
    mpi_communicator (MPI_COMM_WORLD),
    triangulation (mpi_communicator,
                   typename dealii::Triangulation<dim>::MeshSmoothing
                   (dealii::Triangulation<dim>::smoothing_on_refinement |
                    dealii::Triangulation<dim>::smoothing_on_coarsening)),
    dof_handler_scalar (triangulation),
    // Other initialisations go here.
    pcout (std::cout,
           (dealii::Utilities::MPI::this_mpi_process (mpi_communicator) == 0)),
    timer (mpi_communicator,
	   pcout,
	   dealii::TimerOutput::summary,
	   dealii::TimerOutput::wall_times)
  {
    parameters.declare_entry ("Global mesh refinement steps", "5",
                              dealii::Patterns::Integer (0, 20),
                              "The number of times the 1-cell coarse mesh should "
                              "be refined globally for our computations.");

    parameters.declare_entry ("MaterialID", "0",
                              dealii::Patterns::Anything (),
                              "A functional description of the material ID.");

    parameters.parse_input (prm_file);
  }

  /**
   * Class destructor.
   */
  template <int dim>
  LinearElasticity<dim>::~LinearElasticity ()
  {
    // Wipe DoF handlers.
    dof_handler_scalar.clear ();
  }

  /**
   * Make initial coarse grid.
   */
  template <int dim>
  void
  LinearElasticity<dim>::make_coarse_grid ()
  {
    dealii::TimerOutput::Scope t (timer, "make coarse grid");

    // Create a coarse grid according to the parameters given in the
    // input file.
    dealii::GridGenerator::hyper_cube (triangulation, -10, 10);

    triangulation.refine_global (parameters.get_integer ("Global mesh refinement steps"));
  }

  /**
   * Run the application in the order specified.
   */
  template <int dim>
  void
  LinearElasticity<dim>::run ()
  {
    make_coarse_grid ();
  }

} // namespace ewalena

/**
 * Main function: Initialise problem and run it.
 */
int main (int argc, char *argv[])
{
  // Initialise MPI
  dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);

  try
    {
      mandy::LinearElasticity<2> linear_elasticity ("step-4.prm");
      linear_elasticity.run ();
    }

  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;

      return 1;
    }

  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    }

  return 0;
}
<|endoftext|>


<commit_before>#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkVolume16Reader.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkOutlineFilter.h"
#include "vtkCamera.h"
#include "vtkStripper.h"
#include "vtkLookupTable.h"
#include "vtkImageDataGeometryFilter.h"
#include "vtkProperty.h"
#include "vtkPolyDataNormals.h"
#include "vtkContourFilter.h"

int main (int argc, char **argv)
{
  if (argc < 2)
    {
      cout << "Usage: " << argv[0] << " DATADIR/headsq/quarter" << endl;
    return 1;
    }

  // create the renderer stuff
  vtkRenderer *aRenderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(aRenderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  // read the volume
  vtkVolume16Reader *v16 = vtkVolume16Reader::New();
    v16->SetDataDimensions(64,64);
    v16->SetDataByteOrderToLittleEndian();
    v16->SetFilePrefix (argv[1]);
    v16->SetImageRange(1, 93);
    v16->SetDataSpacing (3.2, 3.2, 1.5);

  // extract the skin
  vtkContourFilter *skinExtractor = vtkContourFilter::New();
    skinExtractor->SetInput((vtkDataSet *) v16->GetOutput());
    skinExtractor->SetValue(0, 500);
  vtkPolyDataNormals *skinNormals = vtkPolyDataNormals::New();
    skinNormals->SetInput(skinExtractor->GetOutput());
    skinNormals->SetFeatureAngle(60.0);
  vtkStripper *skinStripper = vtkStripper::New();
    skinStripper->SetInput(skinNormals->GetOutput());
  vtkPolyDataMapper *skinMapper = vtkPolyDataMapper::New();
    skinMapper->SetInput(skinStripper->GetOutput());
    skinMapper->ScalarVisibilityOff();
  vtkActor *skin = vtkActor::New();
    skin->SetMapper(skinMapper);
    skin->GetProperty()->SetDiffuseColor(1, .49, .25);
    skin->GetProperty()->SetSpecular(.3);
    skin->GetProperty()->SetSpecularPower(20);

  // extract the bone
  vtkContourFilter *boneExtractor = vtkContourFilter::New();
    boneExtractor->SetInput((vtkDataSet *) v16->GetOutput());
    boneExtractor->SetValue(0, 1150);
  vtkPolyDataNormals *boneNormals = vtkPolyDataNormals::New();
    boneNormals->SetInput(boneExtractor->GetOutput());
    boneNormals->SetFeatureAngle(60.0);
  vtkStripper *boneStripper = vtkStripper::New();
    boneStripper->SetInput(boneNormals->GetOutput());
  vtkPolyDataMapper *boneMapper = vtkPolyDataMapper::New();
    boneMapper->SetInput(boneStripper->GetOutput());
    boneMapper->ScalarVisibilityOff();
  vtkActor *bone = vtkActor::New();
    bone->SetMapper(boneMapper);
    bone->GetProperty()->SetDiffuseColor(1, 1, .9412);

  // get an outline
  vtkOutlineFilter *outlineData = vtkOutlineFilter::New();
    outlineData->SetInput((vtkDataSet *) v16->GetOutput());
  vtkPolyDataMapper *mapOutline = vtkPolyDataMapper::New();
    mapOutline->SetInput(outlineData->GetOutput());
  vtkActor *outline = vtkActor::New();
    outline->SetMapper(mapOutline);
    outline->GetProperty()->SetColor(0,0,0);

  // create a b/w lookup table
  vtkLookupTable *bwLut = vtkLookupTable::New();
    bwLut->SetTableRange (0, 2000);
    bwLut->SetSaturationRange (0, 0);
    bwLut->SetHueRange (0, 0);
    bwLut->SetValueRange (0, 1);

  // create a hue lookup table
  vtkLookupTable *hueLut = vtkLookupTable::New();
    hueLut->SetTableRange (0, 2000);
    hueLut->SetHueRange (0, 1);
    hueLut->SetSaturationRange (1, 1);
    hueLut->SetValueRange (1, 1);

  // create a saturation lookup table
  vtkLookupTable *satLut = vtkLookupTable::New();
    satLut->SetTableRange (0, 2000);
    satLut->SetHueRange (.6, .6);
    satLut->SetSaturationRange (0, 1);
    satLut->SetValueRange (1, 1);

  // sagittal
  vtkImageDataGeometryFilter *saggitalSection =
      vtkImageDataGeometryFilter::New();
    saggitalSection->SetExtent (32,32, 0,63, 0, 93);
    saggitalSection->SetInput (v16->GetOutput());
  vtkPolyDataMapper *saggitalMapper = vtkPolyDataMapper::New();
    saggitalMapper->SetInput(saggitalSection->GetOutput());
    saggitalMapper->ScalarVisibilityOn();
    saggitalMapper->SetScalarRange (0, 2000);
    saggitalMapper->SetLookupTable (bwLut);
  vtkActor *sagittal = vtkActor::New();
    sagittal->SetMapper(saggitalMapper);

  // axial
  vtkImageDataGeometryFilter *axialSection =
      vtkImageDataGeometryFilter::New();
    axialSection->SetExtent (0,63, 0,63, 46, 46);
    axialSection->SetInput (v16->GetOutput());
  vtkPolyDataMapper *axialMapper = vtkPolyDataMapper::New();
    axialMapper->SetInput(axialSection->GetOutput());
    axialMapper->ScalarVisibilityOn();
    axialMapper->SetScalarRange (0, 2000);
    axialMapper->SetLookupTable (hueLut);
  vtkActor *axial = vtkActor::New();
    axial->SetMapper(axialMapper);

  // coronal
  vtkImageDataGeometryFilter *coronalSection =
      vtkImageDataGeometryFilter::New();
    coronalSection->SetExtent (0,63, 32, 32, 0, 92);
    coronalSection->SetInput (v16->GetOutput());
  vtkPolyDataMapper *coronalMapper = vtkPolyDataMapper::New();
    coronalMapper->SetInput(coronalSection->GetOutput());
    coronalMapper->ScalarVisibilityOn();
    coronalMapper->SetScalarRange (0, 2000);
    coronalMapper->SetLookupTable (satLut);
  vtkActor *coronal = vtkActor::New();
    coronal->SetMapper(coronalMapper);

  // create a camera with the correct view up
  vtkCamera *aCamera = vtkCamera::New();
    aCamera->SetViewUp (0, 0, -1);
    aCamera->SetPosition (0, 1, 0);
    aCamera->SetFocalPoint (0, 0, 0);
    aCamera->ComputeViewPlaneNormal();

  // now, tell the renderer our actors
  aRenderer->AddActor(outline);
  aRenderer->AddActor(sagittal);
  aRenderer->AddActor(axial);
  aRenderer->AddActor(coronal);
  aRenderer->AddActor(skin);
  aRenderer->AddActor(bone);

  // turn off bone for this examples
  bone->VisibilityOff();

  // set skin to semi-transparent
  skin->GetProperty()->SetOpacity(0.5);

  aRenderer->SetActiveCamera(aCamera);
  aRenderer->ResetCamera ();
  aCamera->Dolly(1.5);
  aRenderer->SetBackground(1,1,1);
  aRenderer->ResetCameraClippingRange ();

  // interact with data
  renWin->SetSize(640, 480);
  renWin->Render();
  iren->Start();
  return 0;
}
<commit_msg>ENH:Reworking to use texture approach and not polygonal approach<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    Medical3.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
//
// This example reads a volume dataset, extracts two isosurfaces that
// represent the skin and bone, creates three orthogonal planes (saggital,
// axial, coronal), and displays them.
//
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkVolume16Reader.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkOutlineFilter.h"
#include "vtkCamera.h"
#include "vtkStripper.h"
#include "vtkLookupTable.h"
#include "vtkImageDataGeometryFilter.h"
#include "vtkProperty.h"
#include "vtkPolyDataNormals.h"
#include "vtkContourFilter.h"
#include "vtkImageData.h"

int main (int argc, char **argv)
{
  if (argc < 2)
    {
      cout << "Usage: " << argv[0] << " DATADIR/headsq/quarter" << endl;
    return 1;
    }

  // Create the renderer, the render window, and the interactor. The renderer
  // draws into the render window, the interactor enables mouse- and
  // keyboard-based interaction with the data within the render window.
  //
  vtkRenderer *aRenderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(aRenderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  // The following reader is used to read a series of 2D slices (images)
  // that compose the volume. The slice dimensions are set, and the
  // pixel spacing. The data Endianness must also be specified. The reader
  // usese the FilePrefix in combination with the slice number to construct
  // filenames using the format FilePrefix.%d. (In this case the FilePrefix
  // is the root name of the file: quarter.)
  vtkVolume16Reader *v16 = vtkVolume16Reader::New();
    v16->SetDataDimensions(64,64);
    v16->SetDataByteOrderToLittleEndian();
    v16->SetFilePrefix (argv[1]);
    v16->SetImageRange(1, 93);
    v16->SetDataSpacing (3.2, 3.2, 1.5);

  // An isosurface, or contour value of 500 is known to correspond to the
  // skin of the patient. Once generated, a vtkPolyDataNormals filter is
  // is used to create normals for smooth surface shading during rendering.
  // The triangle stripper is used to create triangle strips from the
  // isosurface; these render much faster on may systems.
  vtkContourFilter *skinExtractor = vtkContourFilter::New();
    skinExtractor->SetInput( v16->GetOutput());
    skinExtractor->SetValue(0, 500);
  vtkPolyDataNormals *skinNormals = vtkPolyDataNormals::New();
    skinNormals->SetInput(skinExtractor->GetOutput());
    skinNormals->SetFeatureAngle(60.0);
  vtkStripper *skinStripper = vtkStripper::New();
    skinStripper->SetInput(skinNormals->GetOutput());
  vtkPolyDataMapper *skinMapper = vtkPolyDataMapper::New();
    skinMapper->SetInput(skinStripper->GetOutput());
    skinMapper->ScalarVisibilityOff();
  vtkActor *skin = vtkActor::New();
    skin->SetMapper(skinMapper);
    skin->GetProperty()->SetDiffuseColor(1, .49, .25);
    skin->GetProperty()->SetSpecular(.3);
    skin->GetProperty()->SetSpecularPower(20);

  // An isosurface, or contour value of 1150 is known to correspond to the
  // skin of the patient. Once generated, a vtkPolyDataNormals filter is
  // is used to create normals for smooth surface shading during rendering.
  // The triangle stripper is used to create triangle strips from the
  // isosurface; these render much faster on may systems.
  vtkContourFilter *boneExtractor = vtkContourFilter::New();
    boneExtractor->SetInput((vtkDataSet *) v16->GetOutput());
    boneExtractor->SetValue(0, 1150);
  vtkPolyDataNormals *boneNormals = vtkPolyDataNormals::New();
    boneNormals->SetInput(boneExtractor->GetOutput());
    boneNormals->SetFeatureAngle(60.0);
  vtkStripper *boneStripper = vtkStripper::New();
    boneStripper->SetInput(boneNormals->GetOutput());
  vtkPolyDataMapper *boneMapper = vtkPolyDataMapper::New();
    boneMapper->SetInput(boneStripper->GetOutput());
    boneMapper->ScalarVisibilityOff();
  vtkActor *bone = vtkActor::New();
    bone->SetMapper(boneMapper);
    bone->GetProperty()->SetDiffuseColor(1, 1, .9412);

  // An outline provides context around the data.
  //
  vtkOutlineFilter *outlineData = vtkOutlineFilter::New();
    outlineData->SetInput((vtkDataSet *) v16->GetOutput());
  vtkPolyDataMapper *mapOutline = vtkPolyDataMapper::New();
    mapOutline->SetInput(outlineData->GetOutput());
  vtkActor *outline = vtkActor::New();
    outline->SetMapper(mapOutline);
    outline->GetProperty()->SetColor(0,0,0);

  // create a b/w lookup table
  vtkLookupTable *bwLut = vtkLookupTable::New();
    bwLut->SetTableRange (0, 2000);
    bwLut->SetSaturationRange (0, 0);
    bwLut->SetHueRange (0, 0);
    bwLut->SetValueRange (0, 1);

  // create a hue lookup table
  vtkLookupTable *hueLut = vtkLookupTable::New();
    hueLut->SetTableRange (0, 2000);
    hueLut->SetHueRange (0, 1);
    hueLut->SetSaturationRange (1, 1);
    hueLut->SetValueRange (1, 1);

  // create a saturation lookup table
  vtkLookupTable *satLut = vtkLookupTable::New();
    satLut->SetTableRange (0, 2000);
    satLut->SetHueRange (.6, .6);
    satLut->SetSaturationRange (0, 1);
    satLut->SetValueRange (1, 1);

  // sagittal
  vtkExtractVOI *saggitalSection = vtkExtractVOI::New();
    saggitalSection->SetInput (v16->GetOutput());
    saggitalSection->SetVOI(32,32, 0,63, 0,93);
  vtkImageMapToColors *saggitalColors = vtkImageMapToColors::New();
    saggitalColors->SetInput(saggitalSection->GetOutput());
    saggitalColors->SetLookupTable(bwLut);
  vtkImageActor *sagittal = vtkImageActor::New();
    sagittal->SetInput(saggitalColors->GetOutput());

  // axial

  // coronal

  // It is convenient to create an initial view of the data. The FocalPoint
  // and Position form a vector direction. Later on (ResetCamera() method)
  // this vector is used to position the camera to look at the data in
  // this direction.
  vtkCamera *aCamera = vtkCamera::New();
    aCamera->SetViewUp (0, 0, -1);
    aCamera->SetPosition (0, 1, 0);
    aCamera->SetFocalPoint (0, 0, 0);
    aCamera->ComputeViewPlaneNormal();

  // Actors are added to the renderer.
  aRenderer->AddActor(outline);
  aRenderer->AddActor(sagittal);
//  aRenderer->AddActor(axial);
//  aRenderer->AddActor(coronal);
  aRenderer->AddActor(skin);
  aRenderer->AddActor(bone);

  // Turn off bone for this example.
  bone->VisibilityOff();

  // Set skin to semi-transparent.
  skin->GetProperty()->SetOpacity(0.5);

  // An initial camera view is created.  The Dolly() method moves
  // the camera towards the FocalPoint, thereby enlarging the image.
  aRenderer->SetActiveCamera(aCamera);
  aRenderer->ResetCamera ();
  aCamera->Dolly(1.5);

  // Set a background color for the renderer and set the size of the
  // render window (expressed in pixels).
  aRenderer->SetBackground(1,1,1);
  renWin->SetSize(640, 480);

  // Note that when camera movement occurs (as it does in the Dolly()
  // method), the clipping planes often need adjusting. Clipping planes
  // consist of two planes: near and far along the view direction. The
  // near plane clips out objects in front of the plane; the far plane
  // clips out objects behind the plane. This way only what is drawn
  // between the planes is actually rendered.
  aRenderer->ResetCameraClippingRange ();

  // interact with data
  iren->Initialize();
  iren->Start();

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Ascent MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "LogonStdAfx.h"
#include <signal.h>
#include "../shared/svn_revision.h"
#ifndef WIN32
#include <sys/resource.h>
#endif
#include "../shared/ascent_getopt.h"

#define BANNER "Ascent %s r%u/%s-%s (%s) :: Logon Server"

#ifndef WIN32
#include <sched.h>
#endif

//#include <vld.h>
//#include <vldapi.h>

// Database impl
Database * sLogonSQL;
initialiseSingleton(LogonServer);
bool mrunning = true;
Mutex _authSocketLock;
set<AuthSocket*> _authSockets;
#ifdef WIN32
CircularQueue<uint32,30> last_spells;
#endif

/*** Signal Handler ***/
void _OnSignal(int s)
{
	switch (s)
	{
#ifndef WIN32
	case SIGHUP:
	   {
		   sLog.outString("Received SIGHUP signal, reloading accounts.");
		   AccountMgr::getSingleton().ReloadAccounts(true);
	   }break;
#endif
	case SIGINT:
	case SIGTERM:
	case SIGABRT:
#ifdef _WIN32
	case SIGBREAK:
#endif
		mrunning = false;
		break;
	}

	signal(s, _OnSignal);
}

int main(int argc, char** argv)
{
#ifndef WIN32
	rlimit rl;
	if (getrlimit(RLIMIT_CORE, &rl) == -1)
		printf("getrlimit failed. This could be problem.\n");
	else
	{
		rl.rlim_cur = rl.rlim_max;
		if (setrlimit(RLIMIT_CORE, &rl) == -1)
			printf("setrlimit failed. Server may not save core.dump files.\n");
	}
#endif

	new LogonServer;

	// Run!
	LogonServer::getSingleton( ).Run(argc, argv);
	delete LogonServer::getSingletonPtr();
}

bool startdb()
{
	string lhostname, lusername, lpassword, ldatabase;
	int lport = 0;
	int ltype = 1;
	// Configure Main Database

	bool result;

	// Configure Logon Database...
	result = Config.MainConfig.GetString("LogonDatabase", "Username", &lusername);
	result = !result ? result : Config.MainConfig.GetString("LogonDatabase", "Password", &lpassword);
	result = !result ? result : Config.MainConfig.GetString("LogonDatabase", "Hostname", &lhostname);
	result = !result ? result : Config.MainConfig.GetString("LogonDatabase", "Name", &ldatabase);
	result = !result ? result : Config.MainConfig.GetInt("LogonDatabase", "Port", &lport);
	result = !result ? result : Config.MainConfig.GetInt("LogonDatabase", "Type", &ltype);

	if(result == false)
	{
		sLog.outString("sql: Logon database parameters not found.");
		return false;
	}

	sLog.SetScreenLoggingLevel(Config.MainConfig.GetIntDefault("LogLevel", "Screen", 0));
	sLogonSQL = new Database();

	// Initialize it
	if(!sLogonSQL->Initialize(lhostname.c_str(), (unsigned int)lport, lusername.c_str(),
		lpassword.c_str(), ldatabase.c_str(), Config.MainConfig.GetIntDefault("LogonDatabase", "ConnectionCount", 1),
		16384))
	{
		sLog.outError("sql: Logon database initialization failed. Exiting.");
		return false;
	}

	return true;
}

#define DEF_VALUE_NOT_SET 0xDEADBEEF

void LogonServer::Run(int argc, char ** argv)
{
	UNIXTIME = time(NULL);
#ifdef WIN32
	char * config_file = "logonserver.conf";
#else
	char * config_file = (char*)CONFDIR "/logonserver.conf";
#endif
	int file_log_level = DEF_VALUE_NOT_SET;
	int screen_log_level = DEF_VALUE_NOT_SET;
	int do_check_conf = 0;
	int do_version = 0;

	struct ascent_option longopts[] =
	{
		{ "checkconf",			ascent_no_argument,				&do_check_conf,			1		},
		{ "screenloglevel",		ascent_required_argument,		&screen_log_level,		1		},
		{ "fileloglevel",		ascent_required_argument,		&file_log_level,		1		},
		{ "version",			ascent_no_argument,				&do_version,			1		},
		{ "conf",				ascent_required_argument,		NULL,					'c'		},
		{ 0, 0, 0, 0 }
	};

	char c;
	while ((c = ascent_getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
	{
		switch (c)
		{
		case 'c':
			/* Log filename was set */
			config_file = new char[strlen(ascent_optarg)];
			strcpy(config_file,ascent_optarg);
			break;
		case 0:
			break;
		default:
			sLog.m_fileLogLevel = -1;
			sLog.m_screenLogLevel = 3;
			printf("Usage: %s [--checkconf] [--screenloglevel <level>] [--fileloglevel <level>] [--conf <filename>] [--version]\n", argv[0]);
			return;
		}
	}

	// Startup banner
	if(!do_version && !do_check_conf)
	{
		sLog.Init(-1, 3);
	}
	else
	{
		sLog.m_fileLogLevel = -1;
		sLog.m_screenLogLevel = 3;
	}

	sLog.outString(BANNER, BUILD_TAG, g_getRevision(), CONFIG, PLATFORM_TEXT, ARCH);
#ifdef REPACK
	sLog.outString("Repack: %s | Author: %s | %s\n", REPACK, REPACK_AUTHOR, REPACK_WEBSITE);
#endif
	sLog.outString("==============================================================================");
	sLog.outString("");
	if(do_version)
		return;

	if(do_check_conf)
	{
		printf("Checking config file: %s\n", config_file);
		if(Config.MainConfig.SetSource(config_file, true))
			printf("  Passed without errors.\n");
		else
			printf("  Encountered one or more errors.\n");
		/* test for die variables */
		string die;
		if(Config.MainConfig.GetString("die", "msg", &die) || Config.MainConfig.GetString("die2", "msg", &die))
			printf("Die directive received: %s", die.c_str());

		return;
	}

	sLog.outString("The key combination <Ctrl-C> will safely shut down the server at any time.");
	sLog.outString("");
	Log.Notice("System","Initializing Random Number Generators...");

	Log.Notice("Config", "Loading Config Files...");

	if(Config.MainConfig.SetSource(config_file))
	{
		Log.Success("Config", ">> logonserver.conf", config_file);
	}
	else
	{
		Log.Error("Config", ">> logonserver.conf", config_file);
		return;
	}
	Log.Notice("ThreadMgr", "Starting...");
	ThreadPool.Startup();

	if(!startdb())
		return;

	Log.Notice("AccountMgr", "Starting...");
	new AccountMgr;
	new IPBanner;

	Log.Notice("InfoCore", "Starting...");
	new InformationCore;

	new PatchMgr;
	Log.Notice("AccountMgr", "Precaching accounts...");
	sAccountMgr.ReloadAccounts(true);
	Log.Notice("AccountMgr", "%u accounts are loaded and ready.", sAccountMgr.GetCount());
	Log.Line();

	// Spawn periodic function caller thread for account reload every 10mins
	int atime = Config.MainConfig.GetIntDefault("Rates", "AccountRefresh",600);
	atime *= 1000;
	//SpawnPeriodicCallThread(AccountMgr, AccountMgr::getSingletonPtr(), &AccountMgr::ReloadAccountsCallback, time);
	PeriodicFunctionCaller<AccountMgr> * pfc = new PeriodicFunctionCaller<AccountMgr>(AccountMgr::getSingletonPtr(),
		&AccountMgr::ReloadAccountsCallback, atime);
	ThreadPool.ExecuteTask(pfc);

	// Load conf settings..
	uint32 cport = Config.MainConfig.GetIntDefault("Listen", "RealmListPort", 3724);
	uint32 sport = Config.MainConfig.GetIntDefault("Listen", "ServerPort", 8093);
	//uint32 threadcount = Config.MainConfig.GetIntDefault("Network", "ThreadCount", 5);
	//uint32 threaddelay = Config.MainConfig.GetIntDefault("Network", "ThreadDelay", 20);
	string host = Config.MainConfig.GetStringDefault("Listen", "Host", "0.0.0.0");
	string shost = Config.MainConfig.GetStringDefault("Listen", "ISHost", host.c_str());
	min_build = Config.MainConfig.GetIntDefault("Client", "MinBuild", 6180);
	max_build = Config.MainConfig.GetIntDefault("Client", "MaxBuild", 6999);
	string logon_pass = Config.MainConfig.GetStringDefault("LogonServer", "RemotePassword", "r3m0t3b4d");
	Sha1Hash hash;
	hash.UpdateData(logon_pass);
	hash.Finalize();
	memcpy(sql_hash, hash.GetDigest(), 20);

	ThreadPool.ExecuteTask(new LogonConsoleThread);

	new SocketMgr;
	new SocketGarbageCollector;
	sSocketMgr.SpawnWorkerThreads();

	ListenSocket<AuthSocket> * cl = new ListenSocket<AuthSocket>(host.c_str(), cport);
	ListenSocket<LogonCommServerSocket> * sl = new ListenSocket<LogonCommServerSocket>(shost.c_str(), sport);

	// Spawn auth listener
	// Spawn interserver listener
	bool authsockcreated = cl->IsOpen();
	bool intersockcreated = sl->IsOpen();
#ifdef WIN32
	if(authsockcreated)
		ThreadPool.ExecuteTask(cl);
	if(intersockcreated)
		ThreadPool.ExecuteTask(sl);
#endif
	// hook signals
	sLog.outString("Hooking signals...");
	signal(SIGINT, _OnSignal);
	signal(SIGTERM, _OnSignal);
	signal(SIGABRT, _OnSignal);
#ifdef _WIN32
	signal(SIGBREAK, _OnSignal);
#else
	signal(SIGHUP, _OnSignal);
#endif

		/* write pid file */
	FILE * fPid = fopen("logonserver.pid", "w");
	if(fPid)
	{
		uint32 pid;
#ifdef WIN32
		pid = GetCurrentProcessId();
#else
		pid = getpid();
#endif
		fprintf(fPid, "%u", (unsigned int)pid);
		fclose(fPid);
	}
	uint32 loop_counter = 0;
	//ThreadPool.Gobble();

	while(mrunning && authsockcreated && intersockcreated)
	{
		if(!(++loop_counter % 400))	 // 20 seconds
			CheckForDeadSockets();

		if(!(loop_counter%10000))	// 5mins
			ThreadPool.IntegrityCheck();

		if(!(loop_counter%10))
		{
			sInfoCore.TimeoutSockets();
			sSocketGarbageCollector.Update();
			CheckForDeadSockets();			  // Flood Protection
			UNIXTIME = time(NULL);
		}

		PatchMgr::getSingleton().UpdateJobs();
		Sleep(10);
	}

	sLog.outString("Shutting down...");
	ThreadPool.ShowStats();
	pfc->kill();

	cl->Close();
	sl->Close();
	sSocketMgr.CloseAll();
#ifdef WIN32
	sSocketMgr.ShutdownThreads();
#endif
	sLogonConsole.Kill();
	delete LogonConsole::getSingletonPtr();

	// kill db
	sLog.outString("Waiting for database to close..");
	sLogonSQL->EndThreads();
	sLogonSQL->Shutdown();
	delete sLogonSQL;

	ThreadPool.Shutdown();

	// delete pid file
	remove("logonserver.pid");

	delete AccountMgr::getSingletonPtr();
	delete InformationCore::getSingletonPtr();
	delete IPBanner::getSingletonPtr();
	delete SocketMgr::getSingletonPtr();
	delete SocketGarbageCollector::getSingletonPtr();
	delete pfc;
	printf("Shutdown complete.\n");
}

void OnCrash(bool Terminate)
{

}

void LogonServer::CheckForDeadSockets()
{
	_authSocketLock.Acquire();
	time_t t = time(NULL);
	time_t diff;
	set<AuthSocket*>::iterator itr = _authSockets.begin();
	set<AuthSocket*>::iterator it2;
	AuthSocket * s;

	for(itr = _authSockets.begin(); itr != _authSockets.end();)
	{
		it2 = itr;
		s = (*it2);
		++itr;

		diff = t - s->GetLastRecv();
		if(diff > 240)		   // More than 4mins -> kill the socket.
		{
			_authSockets.erase(it2);
			s->removedFromSet = true;
			s->Disconnect();
		}
	}
	_authSocketLock.Release();
}
<commit_msg>* added signal unhooking to logonserver under *nix, shouldnt be such a bitch to kill off now :P<commit_after>/*
 * Ascent MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "LogonStdAfx.h"
#include <signal.h>
#include "../shared/svn_revision.h"
#ifndef WIN32
#include <sys/resource.h>
#endif
#include "../shared/ascent_getopt.h"

#define BANNER "Ascent %s r%u/%s-%s (%s) :: Logon Server"

#ifndef WIN32
#include <sched.h>
#endif

//#include <vld.h>
//#include <vldapi.h>

// Database impl
Database * sLogonSQL;
initialiseSingleton(LogonServer);
bool mrunning = true;
Mutex _authSocketLock;
set<AuthSocket*> _authSockets;
#ifdef WIN32
CircularQueue<uint32,30> last_spells;
#endif

/*** Signal Handler ***/
void _OnSignal(int s)
{
	switch (s)
	{
#ifndef WIN32
	case SIGHUP:
	   {
		   sLog.outString("Received SIGHUP signal, reloading accounts.");
		   AccountMgr::getSingleton().ReloadAccounts(true);
	   }break;
#endif
	case SIGINT:
	case SIGTERM:
	case SIGABRT:
#ifdef _WIN32
	case SIGBREAK:
#endif
		mrunning = false;
		break;
	}

	signal(s, _OnSignal);
}

int main(int argc, char** argv)
{
#ifndef WIN32
	rlimit rl;
	if (getrlimit(RLIMIT_CORE, &rl) == -1)
		printf("getrlimit failed. This could be problem.\n");
	else
	{
		rl.rlim_cur = rl.rlim_max;
		if (setrlimit(RLIMIT_CORE, &rl) == -1)
			printf("setrlimit failed. Server may not save core.dump files.\n");
	}
#endif

	new LogonServer;

	// Run!
	LogonServer::getSingleton( ).Run(argc, argv);
	delete LogonServer::getSingletonPtr();
}

bool startdb()
{
	string lhostname, lusername, lpassword, ldatabase;
	int lport = 0;
	int ltype = 1;
	// Configure Main Database

	bool result;

	// Configure Logon Database...
	result = Config.MainConfig.GetString("LogonDatabase", "Username", &lusername);
	result = !result ? result : Config.MainConfig.GetString("LogonDatabase", "Password", &lpassword);
	result = !result ? result : Config.MainConfig.GetString("LogonDatabase", "Hostname", &lhostname);
	result = !result ? result : Config.MainConfig.GetString("LogonDatabase", "Name", &ldatabase);
	result = !result ? result : Config.MainConfig.GetInt("LogonDatabase", "Port", &lport);
	result = !result ? result : Config.MainConfig.GetInt("LogonDatabase", "Type", &ltype);

	if(result == false)
	{
		sLog.outString("sql: Logon database parameters not found.");
		return false;
	}

	sLog.SetScreenLoggingLevel(Config.MainConfig.GetIntDefault("LogLevel", "Screen", 0));
	sLogonSQL = new Database();

	// Initialize it
	if(!sLogonSQL->Initialize(lhostname.c_str(), (unsigned int)lport, lusername.c_str(),
		lpassword.c_str(), ldatabase.c_str(), Config.MainConfig.GetIntDefault("LogonDatabase", "ConnectionCount", 1),
		16384))
	{
		sLog.outError("sql: Logon database initialization failed. Exiting.");
		return false;
	}

	return true;
}

#define DEF_VALUE_NOT_SET 0xDEADBEEF

void LogonServer::Run(int argc, char ** argv)
{
	UNIXTIME = time(NULL);
#ifdef WIN32
	char * config_file = "logonserver.conf";
#else
	char * config_file = (char*)CONFDIR "/logonserver.conf";
#endif
	int file_log_level = DEF_VALUE_NOT_SET;
	int screen_log_level = DEF_VALUE_NOT_SET;
	int do_check_conf = 0;
	int do_version = 0;

	struct ascent_option longopts[] =
	{
		{ "checkconf",			ascent_no_argument,				&do_check_conf,			1		},
		{ "screenloglevel",		ascent_required_argument,		&screen_log_level,		1		},
		{ "fileloglevel",		ascent_required_argument,		&file_log_level,		1		},
		{ "version",			ascent_no_argument,				&do_version,			1		},
		{ "conf",				ascent_required_argument,		NULL,					'c'		},
		{ 0, 0, 0, 0 }
	};

	char c;
	while ((c = ascent_getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
	{
		switch (c)
		{
		case 'c':
			/* Log filename was set */
			config_file = new char[strlen(ascent_optarg)];
			strcpy(config_file,ascent_optarg);
			break;
		case 0:
			break;
		default:
			sLog.m_fileLogLevel = -1;
			sLog.m_screenLogLevel = 3;
			printf("Usage: %s [--checkconf] [--screenloglevel <level>] [--fileloglevel <level>] [--conf <filename>] [--version]\n", argv[0]);
			return;
		}
	}

	// Startup banner
	if(!do_version && !do_check_conf)
	{
		sLog.Init(-1, 3);
	}
	else
	{
		sLog.m_fileLogLevel = -1;
		sLog.m_screenLogLevel = 3;
	}

	sLog.outString(BANNER, BUILD_TAG, g_getRevision(), CONFIG, PLATFORM_TEXT, ARCH);
#ifdef REPACK
	sLog.outString("Repack: %s | Author: %s | %s\n", REPACK, REPACK_AUTHOR, REPACK_WEBSITE);
#endif
	sLog.outString("==============================================================================");
	sLog.outString("");
	if(do_version)
		return;

	if(do_check_conf)
	{
		printf("Checking config file: %s\n", config_file);
		if(Config.MainConfig.SetSource(config_file, true))
			printf("  Passed without errors.\n");
		else
			printf("  Encountered one or more errors.\n");
		/* test for die variables */
		string die;
		if(Config.MainConfig.GetString("die", "msg", &die) || Config.MainConfig.GetString("die2", "msg", &die))
			printf("Die directive received: %s", die.c_str());

		return;
	}

	sLog.outString("The key combination <Ctrl-C> will safely shut down the server at any time.");
	sLog.outString("");
	Log.Notice("System","Initializing Random Number Generators...");

	Log.Notice("Config", "Loading Config Files...");

	if(Config.MainConfig.SetSource(config_file))
	{
		Log.Success("Config", ">> logonserver.conf", config_file);
	}
	else
	{
		Log.Error("Config", ">> logonserver.conf", config_file);
		return;
	}
	Log.Notice("ThreadMgr", "Starting...");
	ThreadPool.Startup();

	if(!startdb())
		return;

	Log.Notice("AccountMgr", "Starting...");
	new AccountMgr;
	new IPBanner;

	Log.Notice("InfoCore", "Starting...");
	new InformationCore;

	new PatchMgr;
	Log.Notice("AccountMgr", "Precaching accounts...");
	sAccountMgr.ReloadAccounts(true);
	Log.Notice("AccountMgr", "%u accounts are loaded and ready.", sAccountMgr.GetCount());
	Log.Line();

	// Spawn periodic function caller thread for account reload every 10mins
	int atime = Config.MainConfig.GetIntDefault("Rates", "AccountRefresh",600);
	atime *= 1000;
	//SpawnPeriodicCallThread(AccountMgr, AccountMgr::getSingletonPtr(), &AccountMgr::ReloadAccountsCallback, time);
	PeriodicFunctionCaller<AccountMgr> * pfc = new PeriodicFunctionCaller<AccountMgr>(AccountMgr::getSingletonPtr(),
		&AccountMgr::ReloadAccountsCallback, atime);
	ThreadPool.ExecuteTask(pfc);

	// Load conf settings..
	uint32 cport = Config.MainConfig.GetIntDefault("Listen", "RealmListPort", 3724);
	uint32 sport = Config.MainConfig.GetIntDefault("Listen", "ServerPort", 8093);
	//uint32 threadcount = Config.MainConfig.GetIntDefault("Network", "ThreadCount", 5);
	//uint32 threaddelay = Config.MainConfig.GetIntDefault("Network", "ThreadDelay", 20);
	string host = Config.MainConfig.GetStringDefault("Listen", "Host", "0.0.0.0");
	string shost = Config.MainConfig.GetStringDefault("Listen", "ISHost", host.c_str());
	min_build = Config.MainConfig.GetIntDefault("Client", "MinBuild", 6180);
	max_build = Config.MainConfig.GetIntDefault("Client", "MaxBuild", 6999);
	string logon_pass = Config.MainConfig.GetStringDefault("LogonServer", "RemotePassword", "r3m0t3b4d");
	Sha1Hash hash;
	hash.UpdateData(logon_pass);
	hash.Finalize();
	memcpy(sql_hash, hash.GetDigest(), 20);

	ThreadPool.ExecuteTask(new LogonConsoleThread);

	new SocketMgr;
	new SocketGarbageCollector;
	sSocketMgr.SpawnWorkerThreads();

	ListenSocket<AuthSocket> * cl = new ListenSocket<AuthSocket>(host.c_str(), cport);
	ListenSocket<LogonCommServerSocket> * sl = new ListenSocket<LogonCommServerSocket>(shost.c_str(), sport);

	// Spawn auth listener
	// Spawn interserver listener
	bool authsockcreated = cl->IsOpen();
	bool intersockcreated = sl->IsOpen();
#ifdef WIN32
	if(authsockcreated)
		ThreadPool.ExecuteTask(cl);
	if(intersockcreated)
		ThreadPool.ExecuteTask(sl);
#endif
	// hook signals
	sLog.outString("Hooking signals...");
	signal(SIGINT, _OnSignal);
	signal(SIGTERM, _OnSignal);
	signal(SIGABRT, _OnSignal);
#ifdef _WIN32
	signal(SIGBREAK, _OnSignal);
#else
	signal(SIGHUP, _OnSignal);
#endif

		/* write pid file */
	FILE * fPid = fopen("logonserver.pid", "w");
	if(fPid)
	{
		uint32 pid;
#ifdef WIN32
		pid = GetCurrentProcessId();
#else
		pid = getpid();
#endif
		fprintf(fPid, "%u", (unsigned int)pid);
		fclose(fPid);
	}
	uint32 loop_counter = 0;
	//ThreadPool.Gobble();

	while(mrunning && authsockcreated && intersockcreated)
	{
		if(!(++loop_counter % 400))	 // 20 seconds
			CheckForDeadSockets();

		if(!(loop_counter%10000))	// 5mins
			ThreadPool.IntegrityCheck();

		if(!(loop_counter%10))
		{
			sInfoCore.TimeoutSockets();
			sSocketGarbageCollector.Update();
			CheckForDeadSockets();			  // Flood Protection
			UNIXTIME = time(NULL);
		}

		PatchMgr::getSingleton().UpdateJobs();
		Sleep(10);
	}

	sLog.outString("Shutting down...");
        signal(SIGINT, 0);
        signal(SIGTERM, 0);
        signal(SIGABRT, 0);
#ifdef _WIN32
        signal(SIGBREAK, 0);
#else
        signal(SIGHUP, 0);
#endif

	pfc->kill();

	cl->Close();
	sl->Close();
	sSocketMgr.CloseAll();
#ifdef WIN32
	sSocketMgr.ShutdownThreads();
#endif
	sLogonConsole.Kill();
	delete LogonConsole::getSingletonPtr();

	// kill db
	sLog.outString("Waiting for database to close..");
	sLogonSQL->EndThreads();
	sLogonSQL->Shutdown();
	delete sLogonSQL;

	ThreadPool.Shutdown();

	// delete pid file
	remove("logonserver.pid");

	delete AccountMgr::getSingletonPtr();
	delete InformationCore::getSingletonPtr();
	delete IPBanner::getSingletonPtr();
	delete SocketMgr::getSingletonPtr();
	delete SocketGarbageCollector::getSingletonPtr();
	delete pfc;
	printf("Shutdown complete.\n");
}

void OnCrash(bool Terminate)
{

}

void LogonServer::CheckForDeadSockets()
{
	_authSocketLock.Acquire();
	time_t t = time(NULL);
	time_t diff;
	set<AuthSocket*>::iterator itr = _authSockets.begin();
	set<AuthSocket*>::iterator it2;
	AuthSocket * s;

	for(itr = _authSockets.begin(); itr != _authSockets.end();)
	{
		it2 = itr;
		s = (*it2);
		++itr;

		diff = t - s->GetLastRecv();
		if(diff > 240)		   // More than 4mins -> kill the socket.
		{
			_authSockets.erase(it2);
			s->removedFromSet = true;
			s->Disconnect();
		}
	}
	_authSocketLock.Release();
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <vector>

#include <boost/container/small_vector.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/any_range.hpp>
#include <boost/range/join.hpp>
#include <boost/variant/variant.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>

#define FMT_HEADER_ONLY
#include <cppformat/format.h>

#include "blackhole/cpp17/string_view.hpp"
#include "blackhole/formatter.hpp"
#include "blackhole/handler.hpp"
#include "blackhole/sandbox.hpp"
#include "blackhole/record.hpp"
#include "blackhole/sink.hpp"

namespace blackhole {

namespace cppformat = fmt;

using cpp17::string_view;

class scoped_t {};

using inner1_t = boost::variant<
    std::int64_t,
    double,
    string_view
>;

// mpl::transform + into_owned.
using inner2_t = boost::variant<
    std::int64_t,
    double,
    std::string
>;

class owned_attribute_value_t {
public:
    inner2_t inner;

    owned_attribute_value_t(int v):
        inner(static_cast<std::int64_t>(v))
    {}

    owned_attribute_value_t(double v):
        inner(v)
    {}

    owned_attribute_value_t(std::string v):
        inner(std::move(v))
    {}
};

struct from_owned_t : public boost::static_visitor<inner1_t> {
    template<typename T>
    inner1_t
    operator()(const T& v) const {
        return v;
    }
};

class attribute_value_t {
public:
    inner1_t inner;

    attribute_value_t(int v):
        inner(static_cast<std::int64_t>(v))
    {}

    attribute_value_t(double v):
        inner(v)
    {}

    attribute_value_t(string_view v):
        inner(v)
    {}

    attribute_value_t(const owned_attribute_value_t& v):
        inner(boost::apply_visitor(from_owned_t(), v.inner))
    {}
};

// using attributes_t = std::vector<std::pair<string_view, attribute_value_t>>;
// TODO: Try to encapsulate.
using attributes_t = boost::container::small_vector<std::pair<string_view, attribute_value_t>, 16>;

typedef boost::any_range<
    std::pair<string_view, attribute_value_t>,
    boost::forward_traversal_tag
> range_type;

typedef std::function<auto(cppformat::MemoryWriter&) -> void> format_callback;

// TODO: Rename to `logger_t`.
class logger_interface_t {
public:
    virtual ~logger_interface_t() {}

    template<typename T, typename... Args>
    auto log(int severity, string_view format, const T& arg, const Args&... args) const -> void {
        const auto callback = [&](cppformat::MemoryWriter& wr) {
            wr.write(format.data(), arg, args...);
        };

        std::vector<std::pair<string_view, attribute_value_t>> attributes;
        log(severity, boost::make_iterator_range(attributes), format, std::cref(callback));
    }

    /// Entry point.
    ///
    /// \note you must include `<blakhole/extensions/format.hpp>` manually to be able to compile
    /// this method.
    template<typename... Args>
    auto log(int severity, const attributes_t& attributes, string_view format, const Args&... args) const -> void {
        const auto callback = [&](cppformat::MemoryWriter& wr) {
            wr.write(format.data(), args...);
        };

        log(severity, boost::make_iterator_range(attributes), format, std::cref(callback));
    }

#ifdef __cpp_constexpr
    template<std::size_t N, typename T, typename... Args>
    auto log(const detail::formatter<N>& formatter, const T& arg, const Args&... args) const -> void {
        const auto callback = [&](cppformat::MemoryWriter& wr) {
            formatter.format(wr, arg, args...);
        };

        log(0, "", format_callback(std::cref(callback)));
    }
#endif

    virtual auto log(int severity, string_view message) const -> void = 0;
    virtual auto log(int severity, string_view format, const format_callback& callback) const -> void = 0;
    virtual auto log(int severity, const range_type& range, string_view format, const format_callback& callback) const -> void = 0;
//  virtual
//  auto
//  log(int severity, const range_t& range, string_view format, const format_t& fn) const -> void = 0;
//  Better for reading ^.
};

class logger_t : public logger_interface_t {
    typedef std::function<auto(const record_t&) -> bool> filter_type;

private:
    struct inner_t;
    std::shared_ptr<inner_t> inner;

public:
    /// \note you can create a logger with no handlers, it'll just drop all messages.
    logger_t(std::vector<std::unique_ptr<handler_t>> handlers);
    logger_t(filter_type filter, std::vector<std::unique_ptr<handler_t>> handlers);

    logger_t(const logger_t& other) = delete;
    logger_t(logger_t&& other);

    auto operator=(const logger_t& other) -> logger_t& = delete;
    auto operator=(logger_t&& other) -> logger_t&;

    ~logger_t();

    auto filter(filter_type fn) -> void;

    using logger_interface_t::log;

    auto log(int severity, string_view message) const -> void;
    auto log(int severity, string_view format, const format_callback& callback) const -> void;

    auto log(int severity, const range_type& range, string_view format, const format_callback& callback) const -> void;

    scoped_t
    scoped(attributes_t);
};

using owned_attributes_t = boost::container::small_vector<std::pair<std::string, owned_attribute_value_t>, 16>;

// TODO: Add in place wrapper (generates attributes each time instead of saving).
class wrapper_t : public logger_interface_t {
public:
    logger_interface_t& inner;
    owned_attributes_t owned;
    attributes_t attributes;

    wrapper_t(logger_interface_t& log, owned_attributes_t owned_):
        inner(log),
        owned(std::move(owned_))
    {
        for (const auto& a : owned) {
            attributes.push_back(std::make_pair(a.first, a.second));
        }
    }

    using logger_interface_t::log;

    auto log(int severity, string_view message) const -> void { std::terminate(); }
    auto log(int severity, string_view format, const format_callback& callback) const -> void { std::terminate(); }

    auto log(int severity, const range_type& range, string_view format, const format_callback& callback) const -> void {
        const auto& r = this->attributes;
        inner.log(severity, boost::range::join(r, attributes), format, callback);
    }
};

}  // namespace blackhole
<commit_msg>style(logger): add minor style change<commit_after>#pragma once

#include <string>
#include <vector>

#include <boost/container/small_vector.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/any_range.hpp>
#include <boost/range/join.hpp>
#include <boost/variant/variant.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>

#define FMT_HEADER_ONLY
#include <cppformat/format.h>

#include "blackhole/cpp17/string_view.hpp"
#include "blackhole/formatter.hpp"
#include "blackhole/handler.hpp"
#include "blackhole/sandbox.hpp"
#include "blackhole/record.hpp"
#include "blackhole/sink.hpp"

namespace blackhole {

namespace cppformat = fmt;

using cpp17::string_view;

class scoped_t {};

using inner1_t = boost::variant<
    std::int64_t,
    double,
    string_view
>;

// mpl::transform + into_owned.
using inner2_t = boost::variant<
    std::int64_t,
    double,
    std::string
>;

class owned_attribute_value_t {
public:
    inner2_t inner;

    owned_attribute_value_t(int v):
        inner(static_cast<std::int64_t>(v))
    {}

    owned_attribute_value_t(double v):
        inner(v)
    {}

    owned_attribute_value_t(std::string v):
        inner(std::move(v))
    {}
};

struct from_owned_t : public boost::static_visitor<inner1_t> {
    template<typename T>
    inner1_t
    operator()(const T& v) const {
        return v;
    }
};

class attribute_value_t {
public:
    inner1_t inner;

    attribute_value_t(int v):
        inner(static_cast<std::int64_t>(v))
    {}

    attribute_value_t(double v):
        inner(v)
    {}

    attribute_value_t(string_view v):
        inner(v)
    {}

    attribute_value_t(const owned_attribute_value_t& v):
        inner(boost::apply_visitor(from_owned_t(), v.inner))
    {}
};

// using attributes_t = std::vector<std::pair<string_view, attribute_value_t>>;
// TODO: Try to encapsulate.
using attributes_t = boost::container::small_vector<std::pair<string_view, attribute_value_t>, 16>;

typedef boost::any_range<
    std::pair<string_view, attribute_value_t>,
    boost::forward_traversal_tag
> range_type;

typedef std::function<auto(cppformat::MemoryWriter&) -> void> format_callback;

// TODO: Rename to `logger_t`.
class logger_interface_t {
public:
    virtual ~logger_interface_t() {}

    template<typename T, typename... Args>
    auto log(int severity, string_view format, const T& arg, const Args&... args) const -> void {
        const auto callback = [&](cppformat::MemoryWriter& wr) {
            wr.write(format.data(), arg, args...);
        };

        std::vector<std::pair<string_view, attribute_value_t>> attributes;
        log(severity, boost::make_iterator_range(attributes), format, std::cref(callback));
    }

    /// Entry point.
    ///
    /// \note you must include `<blakhole/extensions/format.hpp>` manually to be able to compile
    /// this method.
    template<typename... Args>
    auto log(int severity, const attributes_t& attributes, string_view format, const Args&... args) const -> void {
        const auto callback = [&](cppformat::MemoryWriter& wr) {
            wr.write(format.data(), args...);
        };

        log(severity, boost::make_iterator_range(attributes), format, std::cref(callback));
    }

#ifdef __cpp_constexpr
    template<std::size_t N, typename T, typename... Args>
    auto log(const detail::formatter<N>& formatter, const T& arg, const Args&... args) const -> void {
        const auto callback = [&](cppformat::MemoryWriter& wr) {
            formatter.format(wr, arg, args...);
        };

        log(0, "", format_callback(std::cref(callback)));
    }
#endif

    virtual auto log(int severity, string_view message) const -> void = 0;
    virtual auto log(int severity, string_view format, const format_callback& callback) const -> void = 0;
    virtual auto log(int severity, const range_type& range, string_view format, const format_callback& callback) const -> void = 0;
//  virtual
//  auto
//  log(int severity, const range_t& range, string_view format, const format_t& fn) const -> void = 0;
//  Better for reading ^.
};

class logger_t : public logger_interface_t {
    typedef std::function<auto(const record_t&) -> bool> filter_type;

private:
    struct inner_t;
    std::shared_ptr<inner_t> inner;

public:
    /// \note you can create a logger with no handlers, it'll just drop all messages.
    logger_t(std::vector<std::unique_ptr<handler_t>> handlers);
    logger_t(filter_type filter, std::vector<std::unique_ptr<handler_t>> handlers);

    logger_t(const logger_t& other) = delete;
    logger_t(logger_t&& other);

    ~logger_t();

    auto operator=(const logger_t& other) -> logger_t& = delete;
    auto operator=(logger_t&& other) -> logger_t&;

    auto filter(filter_type fn) -> void;

    using logger_interface_t::log;

    auto log(int severity, string_view message) const -> void;
    auto log(int severity, string_view format, const format_callback& callback) const -> void;
    auto log(int severity, const range_type& range, string_view format, const format_callback& callback) const -> void;

    scoped_t
    scoped(attributes_t);
};

using owned_attributes_t = boost::container::small_vector<std::pair<std::string, owned_attribute_value_t>, 16>;

// TODO: Add in place wrapper (generates attributes each time instead of saving).
class wrapper_t : public logger_interface_t {
public:
    logger_interface_t& inner;
    owned_attributes_t owned;
    attributes_t attributes;

    wrapper_t(logger_interface_t& log, owned_attributes_t owned_):
        inner(log),
        owned(std::move(owned_))
    {
        for (const auto& a : owned) {
            attributes.push_back(std::make_pair(a.first, a.second));
        }
    }

    using logger_interface_t::log;

    auto log(int severity, string_view message) const -> void { std::terminate(); }
    auto log(int severity, string_view format, const format_callback& callback) const -> void { std::terminate(); }

    auto log(int severity, const range_type& range, string_view format, const format_callback& callback) const -> void {
        const auto& r = this->attributes;
        inner.log(severity, boost::range::join(r, attributes), format, callback);
    }
};

}  // namespace blackhole
<|endoftext|>


<commit_before>#include "macros.h"

#if defined(MACROS_TEST_MAIN) || 1

#include "assert.h"
#include "strings.h"

struct testStruct {
	int x;
	int y;
};

int main(int argc, char** argv) {

	{
		int counter = 0;
		for (int i = 0; i < 10; i++) {
			BNS_DO_EXACTLY_ONCE() {
				counter++;
			}
		}

		ASSERT(counter == 1);
	}

	{
		// Ideally, these would be static asserts, but clang trips up on them...:\
		ASSERT(BNS_OFFSET_OF(testStruct, x) == 0);

		//possible packing issue?
		ASSERT(BNS_OFFSET_OF(testStruct, y) == 4);
	}

	{
		int arr[3] = { 1, 2, 3 };
		static_assert(BNS_ARRAY_COUNT(arr) == 3, "check BNS_ARRAY_COUNT macro");
	}

	{
		int arr_23 = 0;
		BNS_GLUE_TOKS(arr, _23) = 5;
		BNS_GLUE_TOKS(arr_, 23) = 6;
		// No need to assert or anything.  This will fail to compile if there's an issue
	}

	{
		int arr1[3] = { 100, 1033, -23 };
		int arr2[3] = {};
		BNS_MEMCPY(arr2, arr1, sizeof(arr1));
		for (int i = 0; i < 3; i++) {
			ASSERT(arr1[i] == arr2[i]);
		}

		ASSERT(arr1[0] ==  100);
		ASSERT(arr1[1] == 1033);
		ASSERT(arr1[2] ==  -23);
	}

	static_assert(BNS_MIN(2, 3) == 2, "check BNS_MIN macro");
	static_assert(BNS_MAX(2, 3) == 3, "check BNS_MIN macro");

	static_assert(BNS_ABS(3)  == 3, "check BNS_ABS macro");
	static_assert(BNS_ABS(-3) == 3, "check BNS_ABS macro");
	static_assert(BNS_ABS(0)  == 0, "check BNS_ABS macro");

	{
		ASSERT(StrEqual(BNS_STRINGIFY(the), "the"));
		static_assert(sizeof(BNS_STRINGIFY(the)) == 4, "check BNS_STRINGIFY macro");
	}

	return 0;
}

#endif

<commit_msg>Note to self...backslashes in comments will mess up C code...:\<commit_after>#include "macros.h"

#if defined(MACROS_TEST_MAIN) || 1

#include "assert.h"
#include "strings.h"

struct testStruct {
	int x;
	int y;
};

int main(int argc, char** argv) {

	{
		int counter = 0;
		for (int i = 0; i < 10; i++) {
			BNS_DO_EXACTLY_ONCE() {
				counter++;
			}
		}

		ASSERT(counter == 1);
	}

	{
		// Ideally, these would be static asserts, but clang trips up on them...:\...
		ASSERT(BNS_OFFSET_OF(testStruct, x) == 0);

		//possible packing issue?
		ASSERT(BNS_OFFSET_OF(testStruct, y) == 4);
	}

	{
		int arr[3] = { 1, 2, 3 };
		static_assert(BNS_ARRAY_COUNT(arr) == 3, "check BNS_ARRAY_COUNT macro");
	}

	{
		int arr_23 = 0;
		BNS_GLUE_TOKS(arr, _23) = 5;
		BNS_GLUE_TOKS(arr_, 23) = 6;
		// No need to assert or anything.  This will fail to compile if there's an issue
	}

	{
		int arr1[3] = { 100, 1033, -23 };
		int arr2[3] = {};
		BNS_MEMCPY(arr2, arr1, sizeof(arr1));
		for (int i = 0; i < 3; i++) {
			ASSERT(arr1[i] == arr2[i]);
		}

		ASSERT(arr1[0] ==  100);
		ASSERT(arr1[1] == 1033);
		ASSERT(arr1[2] ==  -23);
	}

	static_assert(BNS_MIN(2, 3) == 2, "check BNS_MIN macro");
	static_assert(BNS_MAX(2, 3) == 3, "check BNS_MIN macro");

	static_assert(BNS_ABS(3)  == 3, "check BNS_ABS macro");
	static_assert(BNS_ABS(-3) == 3, "check BNS_ABS macro");
	static_assert(BNS_ABS(0)  == 0, "check BNS_ABS macro");

	{
		ASSERT(StrEqual(BNS_STRINGIFY(the), "the"));
		static_assert(sizeof(BNS_STRINGIFY(the)) == 4, "check BNS_STRINGIFY macro");
	}

	return 0;
}

#endif

<|endoftext|>


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

#include <kaa/profile/DefaultProfileContainer.hpp>

#include <kaa/configuration/storage/IConfigurationPersistenceManager.hpp>
#include <kaa/configuration/manager/IConfigurationReceiver.hpp>
#include <kaa/configuration/storage/FileConfigurationStorage.hpp>

#include <kaa/logging/Log.hpp>

#include <stdio.h>

using namespace kaa;

using std::cout;
using std::endl;

const char savedConfig[] = "saved_config.cfg";

class UserConfigurationReceiver : public IConfigurationReceiver {
public:
    void displayConfiguration(const KaaRootConfiguration &configuration)
    {
        if (!configuration.AddressList.is_null()) {
            cout << "Configuration body:" << endl;
            auto links = configuration.AddressList.get_array();
            for(auto& e : links) {
                cout << e.label << " - " << e.url << endl;
            }
        }
    }
    virtual void onConfigurationUpdated(const KaaRootConfiguration &configuration)
    {
        cout << "Configuration was updated" << endl;
        displayConfiguration(configuration);
    }
};

int main()
{
    Kaa::init();
    cout << "Configuration demo started" << endl;
    cout << "--= Press any key to exit =--" << endl;
    IKaaClient& kaaClient = Kaa::getKaaClient();
    // Set up default profile container
    kaaClient.setProfileContainer(std::make_shared<DefaultProfileContainer>());
    kaaClient.updateProfile();
    // Set up a configuration subunit
    IConfigurationStoragePtr storage(std::make_shared<FileConfigurationStorage>(savedConfig));
    kaaClient.setConfigurationStorage(storage);
    UserConfigurationReceiver receiver;
    kaaClient.addConfigurationListener(receiver);
    Kaa::start();
    std::cin.get();
    // Waiting for enter key pressed before exiting.
    Kaa::stop();
    cout << "Configuration demo stopped" << endl;
    return 0;
}
<commit_msg>KAA-449: Corrects message.<commit_after>/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <memory>
#include <thread>
#include <kaa/Kaa.hpp>
#include <kaa/IKaaClient.hpp>

#include <kaa/profile/DefaultProfileContainer.hpp>

#include <kaa/configuration/storage/IConfigurationPersistenceManager.hpp>
#include <kaa/configuration/manager/IConfigurationReceiver.hpp>
#include <kaa/configuration/storage/FileConfigurationStorage.hpp>

#include <kaa/logging/Log.hpp>

#include <stdio.h>

using namespace kaa;

using std::cout;
using std::endl;

const char savedConfig[] = "saved_config.cfg";

class UserConfigurationReceiver : public IConfigurationReceiver {
public:
    void displayConfiguration(const KaaRootConfiguration &configuration)
    {
        if (!configuration.AddressList.is_null()) {
            cout << "Configuration body:" << endl;
            auto links = configuration.AddressList.get_array();
            for(auto& e : links) {
                cout << e.label << " - " << e.url << endl;
            }
        }
    }
    virtual void onConfigurationUpdated(const KaaRootConfiguration &configuration)
    {
        displayConfiguration(configuration);
    }
};

int main()
{
    Kaa::init();
    cout << "Configuration demo started" << endl;
    cout << "--= Press Enter to exit =--" << endl;
    IKaaClient& kaaClient = Kaa::getKaaClient();
    // Set up default profile container
    kaaClient.setProfileContainer(std::make_shared<DefaultProfileContainer>());
    kaaClient.updateProfile();
    // Set up a configuration subunit
    IConfigurationStoragePtr storage(std::make_shared<FileConfigurationStorage>(savedConfig));
    kaaClient.setConfigurationStorage(storage);
    UserConfigurationReceiver receiver;
    kaaClient.addConfigurationListener(receiver);
    Kaa::start();
    std::cin.get();
    // Waiting for Enter key pressed before exiting.
    Kaa::stop();
    cout << "Configuration demo stopped" << endl;
    return 0;
}
<|endoftext|>