11:点云处理—三维显示公共类(另一个版本)

halconAlg.h

#ifndef __KD_HALCON_ALG_H__
#define __KD_HALCON_ALG_H__


#include "HalconCpp.h"
#include "HDevThread.h"
#include 
using namespace HalconCpp;
void action(long win,int  width,int height,HTuple ObjectModel3D);
void visualize_object_model_3d_color (HTuple WindowHandle, HTuple ObjectModel3D,
    HTuple CamParam, HTuple PoseIn, HTuple GenParamName, HTuple GenParamValue,
    HTuple Title, HTuple Label, HTuple Information, HTuple *PoseOut);

void visualize_object_model_3d (HTuple WindowHandle, HTuple ObjectModel3D,
    HTuple CamParam, HTuple PoseIn, HTuple GenParamName, HTuple GenParamValue,
    HTuple Title, HTuple Label, HTuple Information, HTuple *PoseOut);


void dev_open_window_fit_image(HObject Image,HTuple width,HTuple height,HTuple Row, HTuple Column,
                               HTuple WidthLimit, HTuple HeightLimit, HTuple *WindowHandle, HTuple FatherWindow);


void disp_message (HTuple WindowHandle, HTuple String, HTuple CoordSystem,
    HTuple Row, HTuple Column, HTuple Color, HTuple Box);

void LoadGrabParameters(int nIndex,double &OffsetRow,double & OffsetColumn,double & TPhi,double &TLength1,
                        double & TLength2,int & Modelmode);
void autogetFileNameCalib(int CalibNumber,HTuple &FilenameCalib,QString &path);
void autogetFileNameModel(int ModelNumber,HTuple &FileNameModel);
void ReadSelf3DPose (HTuple &Pose1, HTuple &Pose2, HTuple &Pose3, HTuple &Pose4);

void gen_cam_par_area_scan_division (HTuple Focus, HTuple Kappa, HTuple Sx,
    HTuple Sy, HTuple Cx, HTuple Cy, HTuple ImageWidth, HTuple ImageHeight,
    HTuple *CameraParam);
void get_cam_par_data (HTuple CameraParam, HTuple ParamName, HTuple *ParamValue);

void set_cam_par_data (HTuple CameraParamIn, HTuple ParamName, HTuple ParamValue,
    HTuple *CameraParamOut);
void get_cam_par_names (HTuple CameraParam, HTuple *CameraType, HTuple *ParamNames);

void fit_3d_plane_xyz1 (HTuple X, HTuple Y, HTuple Z, HTuple *Ox, HTuple *Oy,
    HTuple *Oz, HTuple *Nx, HTuple *Ny, HTuple *Nz, HTuple *MeanResidual);
void gen_LightPlanePose (HTuple X, HTuple Y, HTuple Z, HTuple WindowHandle,
    HTuple *LightPlanePose);
void get_light_plane_pose (HTuple OriginX, HTuple OriginY, HTuple OriginZ,
    HTuple NormalVectorX, HTuple NormalVectorY, HTuple NormalVectorZ, HTuple *LightPlanePose);
void project_object_model_3d_lines_to_contour_xld (HObject *ho_IntersectionX, HTuple ObjectModel3DIntersection,
    HTuple CutPlanePose);

void GenSelfPointCloud (HTuple ObjectModel3DScene1, HTuple *ObjectModel3DScene) ; //去除噪声

void GenSelfKindsOfParameters (HTuple *DispPose, HTuple *GenParNames, HTuple *GenParValues,
    HTuple *Instructions, HTuple *CamParam);        //设置三维显示参数

bool isFileExist(QString fullFileName);
#endif // ! __KD_HALCON_ALG_H__

halconAlg.cpp




#include "HalconCpp.h"
#include "HDevThread.h"
#include 
#include "halconAlg.h"
#include 

using namespace HalconCpp;
extern int G_ObjectNum;
extern int G_CaptureNum;
HTuple  gInfoDecor;
HTuple  gInfoPos;
HTuple  gTitlePos;
HTuple  gTitleDecor;
HTuple  gDispObjOffset;
HTuple  gLabelsDecor;
HTuple  gTerminationButtonLabel;
HTuple  gAlphaDeselected;
HTuple  gIsSinglePose;
HTuple  gUsesOpenGL;
HTuple ExpGetGlobalVar_gInfoDecor(void)
{
  return gInfoDecor;
}
void ExpSetGlobalVar_gInfoDecor(HTuple val)
{
  gInfoDecor = val;
}

HTuple ExpGetGlobalVar_gInfoPos(void)
{
  return gInfoPos;
}
void ExpSetGlobalVar_gInfoPos(HTuple val)
{
  gInfoPos = val;
}

HTuple ExpGetGlobalVar_gTitlePos(void)
{
  return gTitlePos;
}
void ExpSetGlobalVar_gTitlePos(HTuple val)
{
  gTitlePos = val;
}

HTuple ExpGetGlobalVar_gTitleDecor(void)
{
  return gTitleDecor;
}
void ExpSetGlobalVar_gTitleDecor(HTuple val)
{
  gTitleDecor = val;
}

HTuple ExpGetGlobalVar_gDispObjOffset(void)
{
  return gDispObjOffset;
}
void ExpSetGlobalVar_gDispObjOffset(HTuple val)
{
  gDispObjOffset = val;
}

HTuple ExpGetGlobalVar_gLabelsDecor(void)
{
  return gLabelsDecor;
}
void ExpSetGlobalVar_gLabelsDecor(HTuple val)
{
  gLabelsDecor = val;
}

HTuple ExpGetGlobalVar_gTerminationButtonLabel(void)
{
  return gTerminationButtonLabel;
}
void ExpSetGlobalVar_gTerminationButtonLabel(HTuple val)
{
  gTerminationButtonLabel = val;
}

HTuple ExpGetGlobalVar_gAlphaDeselected(void)
{
  return gAlphaDeselected;
}
void ExpSetGlobalVar_gAlphaDeselected(HTuple val)
{
  gAlphaDeselected = val;
}

HTuple ExpGetGlobalVar_gIsSinglePose(void)
{
  return gIsSinglePose;
}
void ExpSetGlobalVar_gIsSinglePose(HTuple val)
{
  gIsSinglePose = val;
}

HTuple ExpGetGlobalVar_gUsesOpenGL(void)
{
  return gUsesOpenGL;
}
void ExpSetGlobalVar_gUsesOpenGL(HTuple val)
{
  gUsesOpenGL = val;
}


void dev_update_off ();
// Chapter: Graphics / Text
// Short Description: Set font independent of OS
void set_display_font (HTuple WindowHandle, HTuple Size, HTuple Font, HTuple Bold,
    HTuple Slant);
// Chapter: Graphics / Text
// Short Description: This procedure writes a text message.
// Chapter: Graphics / Output
void disp_title_and_information (HTuple WindowHandle, HTuple Title, HTuple Information);
// Chapter: Graphics / Output
// Short Description: Can replace disp_object_model_3d if there is no OpenGL available.
void disp_object_model_no_opengl (HObject *ModelContours, HTuple ObjectModel3DID,
    HTuple GenParamName, HTuple GenParamValue, HTuple WindowHandleBuffer,
    HTuple CamParam, HTuple PosesOut);
// Chapter: Graphics / Output
// Short Description: Interactively display 3D object models

// Chapter: Graphics / Output
// Short Description: Determine the optimum distance of the object to obtain a reasonable visualization
void determine_optimum_pose_distance (HTuple ObjectModel3DID, HTuple CamParam,
    HTuple ImageCoverage, HTuple PoseIn, HTuple *PoseOut);
// Chapter: Graphics / Output
// Short Description: Reflect the pose change that was introduced by the user by moving the mouse
void analyze_graph_event (HObject BackgroundImage, HTuple MouseMapping, HTuple Button,
    HTuple Row, HTuple Column, HTuple WindowHandle, HTuple WindowHandleBuffer,
    HTuple VirtualTrackball, HTuple TrackballSize, HTuple SelectedObjectIn,
    HTuple Scene3D, HTuple AlphaOrig, HTuple ObjectModel3DID, HTuple CamParam,
    HTuple Labels, HTuple Title, HTuple Information, HTuple GenParamName,
    HTuple GenParamValue, HTuple PosesIn, HTuple ButtonHoldIn, HTuple TBCenter,
    HTuple TBSize, HTuple WindowCenteredRotationlIn, HTuple MaxNumModels,
    HTuple *PosesOut, HTuple *SelectedObjectOut, HTuple *ButtonHoldOut,
    HTuple *WindowCenteredRotationOut);
// Chapter: Graphics / Output
// Short Description: Project an image point onto the trackball
void project_point_on_trackball (HTuple X, HTuple Y, HTuple VirtualTrackball,
    HTuple TrackballSize, HTuple *V);
// Chapter: Graphics / Text
// Short Description: This procedure writes a text message.
void disp_text_button (HTuple WindowHandle, HTuple String, HTuple CoordSystem,
    HTuple Row, HTuple Column, HTuple TextColor, HTuple ButtonColor);
// Chapter: Graphics / Output
// Short Description: Renders 3d object models in a buffer window.
void dump_image_output (HObject BackgroundImage, HTuple WindowHandleBuffer,
    HTuple Scene3D, HTuple AlphaOrig, HTuple ObjectModel3DID, HTuple GenParamName,
    HTuple GenParamValue, HTuple CamParam, HTuple Poses, HTuple ColorImage,
    HTuple Title, HTuple Information, HTuple Labels, HTuple VisualizeTrackball,
    HTuple DisplayContinueButton, HTuple TrackballCenterRow, HTuple TrackballCenterCol,
    HTuple TrackballRadiusPixel, HTuple SelectedObject, HTuple VisualizeRotationCenter,
    HTuple RotationCenter);
// Chapter: Graphics / Output
// Short Description: Get the center of the virtual trackback that is used to move the camera.
void get_trackball_center (HTuple SelectedObject, HTuple TrackballRadiusPixel,
    HTuple ObjectModel3D, HTuple Poses, HTuple *TBCenter, HTuple *TBSize);
// Chapter: Tuple / Arithmetic
// Short Description: Calculates the cross product of two vectors of length 3.
void tuple_vector_cross_product (HTuple V1, HTuple V2, HTuple *VC);
// Chapter: Graphics / Output
// Short Description: Compute the 3d rotation from the mose movement
void trackball (HTuple MX1, HTuple MY1, HTuple MX2, HTuple MY2, HTuple VirtualTrackball,
    HTuple TrackballSize, HTuple SensFactor, HTuple *QuatRotation);
// Chapter: Graphics / Output
// Short Description: Get string extends of several lines.
void max_line_width (HTuple WindowHandle, HTuple Lines, HTuple *MaxWidth);
// Chapter: Graphics / Output
// Short Description: Compute the center of all given 3D object models.
void get_object_models_center (HTuple ObjectModel3DID, HTuple *Center);
// Chapter: Graphics / Output
// Short Description: Displays a continue button.
void disp_continue_button (HTuple WindowHandle);
// Chapter: Graphics / Parameters
void color_string_to_rgb (HTuple Color, HTuple *RGB);
// Chapter: Graphics / Output
// Short Description: Get the center of the virtual trackback that is used to move the camera (version for inspection_mode = 'surface').
void get_trackball_center_fixed (HTuple SelectedObject, HTuple TrackballCenterRow,
    HTuple TrackballCenterCol, HTuple TrackballRadiusPixel, HTuple Scene3D,
    HTuple ObjectModel3DID, HTuple Poses, HTuple WindowHandleBuffer, HTuple CamParam,
    HTuple GenParamName, HTuple GenParamValue, HTuple *TBCenter, HTuple *TBSize);

// Procedures
// External procedures
// Chapter: Develop
// Short Description: Open a new graphics window that preserves the aspect ratio of the given image.

void dev_open_window_fit_image(HObject Image,HTuple width,HTuple height, HTuple Row, HTuple Column, HTuple WidthLimit, HTuple HeightLimit, HTuple *WindowHandle, HTuple FatherWindow)
{
    // Local iconic variables

    // Local control variables
    HTuple  MinWidth, MaxWidth, MinHeight;
    HTuple  MaxHeight, ResizeFactor, ImageWidth, ImageHeight;
    HTuple  TempWidth, TempHeight, WindowWidth, WindowHeight;

    if (0 != (HTuple((WidthLimit.TupleLength()) == 0).TupleOr(WidthLimit<0)))
    {
        MinWidth = 500;
        MaxWidth = 800;

    }
    else if (0 != ((WidthLimit.TupleLength()) == 1))
    {
        MinWidth = 0;
        MaxWidth = WidthLimit;
    }
    else
    {
        MinWidth = ((const HTuple&)WidthLimit)[0];
        MaxWidth = ((const HTuple&)WidthLimit)[1];
    }
    //Parse input tuple HeightLimit
    if (0 != (HTuple((HeightLimit.TupleLength()) == 0).TupleOr(HeightLimit<0)))
    {
        MinHeight = 400;
        MaxHeight = 600;
    }
    else if (0 != ((HeightLimit.TupleLength()) == 1))
    {
        MinHeight = 0;
        MaxHeight = HeightLimit;
    }
    else
    {
        MinHeight = ((const HTuple&)HeightLimit)[0];
        MaxHeight = ((const HTuple&)HeightLimit)[1];
    }
    //
    //Test, if window size has to be changed.
    ResizeFactor = 1;
    //GetImageSize(Image, &ImageWidth, &ImageHeight);
    ImageWidth=width;
    ImageHeight=height;
    //First, expand window to the minimum extents (if necessary).

    if (0 != (HTuple(MinWidth>ImageWidth).TupleOr(MinHeight>ImageHeight)))
    {
        ResizeFactor = (((MinWidth.TupleReal()) / ImageWidth).TupleConcat((MinHeight.TupleReal()) / ImageHeight)).TupleMax();
    }
    TempWidth = ImageWidth*ResizeFactor;
    TempHeight = ImageHeight*ResizeFactor;
    //Then, shrink window to maximum extents (if necessary).
    if (0 != (HTuple(MaxWidth display a shadow in a default color
  //       'false' -> display no shadow (same as if no second value is given)
  //       otherwise -> use given string as color string for the shadow color
  //
  //Prepare window
  GetRgb(WindowHandle, &Red, &Green, &Blue);
  GetPart(WindowHandle, &Row1Part, &Column1Part, &Row2Part, &Column2Part);
  GetWindowExtents(WindowHandle, &RowWin, &ColumnWin, &WidthWin, &HeightWin);
  SetPart(WindowHandle, 0, 0, HeightWin-1, WidthWin-1);
  //
  //default settings
  if (0 != (Row==-1))
  {
    Row = 12;
  }
  if (0 != (Column==-1))
  {
    Column = 12;
  }
  if (0 != (Color==HTuple()))
  {
    Color = "";
  }
  //
  String = ((""+String)+"").TupleSplit("\n");
  //
  //Estimate extentions of text depending on font size.
  GetFontExtents(WindowHandle, &MaxAscent, &MaxDescent, &MaxWidth, &MaxHeight);
  if (0 != (CoordSystem==HTuple("window")))
  {
    R1 = Row;
    C1 = Column;
  }
  else
  {
    //Transform image to window coordinates
    FactorRow = (1.*HeightWin)/((Row2Part-Row1Part)+1);
    FactorColumn = (1.*WidthWin)/((Column2Part-Column1Part)+1);
    R1 = ((Row-Row1Part)+0.5)*FactorRow;
    C1 = ((Column-Column1Part)+0.5)*FactorColumn;
  }
  //
  //Display text box depending on text size
  UseShadow = 1;
  ShadowColor = "gray";
  if (0 != (HTuple(Box[0])==HTuple("true")))
  {
    Box[0] = "#fce9d4";
    ShadowColor = "#f28d26";
  }
  if (0 != ((Box.TupleLength())>1))
  {
    if (0 != (HTuple(Box[1])==HTuple("true")))
    {
      //Use default ShadowColor set above
    }
    else if (0 != (HTuple(Box[1])==HTuple("false")))
    {
      UseShadow = 0;
    }
    else
    {
      ShadowColor = ((const HTuple&)Box)[1];
      //Valid color?
      try
      {
        SetColor(WindowHandle, HTuple(Box[1]));
      }
      // catch (Exception)
      catch (HalconCpp::HException &HDevExpDefaultException)
      {
        HDevExpDefaultException.ToHTuple(&Exception);
        Exception = "Wrong value of control parameter Box[1] (must be a 'true', 'false', or a valid color string)";
        throw HalconCpp::HException(Exception);
      }
    }
  }
  if (0 != (HTuple(Box[0])!=HTuple("false")))
  {
    //Valid color?
    try
    {
      SetColor(WindowHandle, HTuple(Box[0]));
    }
    // catch (Exception)
    catch (HalconCpp::HException &HDevExpDefaultException)
    {
      HDevExpDefaultException.ToHTuple(&Exception);
      Exception = "Wrong value of control parameter Box[0] (must be a 'true', 'false', or a valid color string)";
      throw HalconCpp::HException(Exception);
    }
    //Calculate box extents
    String = (" "+String)+" ";
    Width = HTuple();
    {
    HTuple end_val93 = (String.TupleLength())-1;
    HTuple step_val93 = 1;
    for (Index=0; Index.Continue(end_val93, step_val93); Index += step_val93)
    {
      GetStringExtents(WindowHandle, HTuple(String[Index]), &Ascent,
          &Descent, &W, &H);
      Width = Width.TupleConcat(W);
    }
    }
    FrameHeight = MaxHeight*(String.TupleLength());
    FrameWidth = (HTuple(0).TupleConcat(Width)).TupleMax();
    R2 = R1+FrameHeight;
    C2 = C1+FrameWidth;
    //Display rectangles
    GetDraw(WindowHandle, &DrawMode);
    SetDraw(WindowHandle, "fill");
    //Set shadow color
    SetColor(WindowHandle, ShadowColor);
    if (0 != UseShadow)
    {
      DispRectangle1(WindowHandle, R1+1, C1+1, R2+1, C2+1);
    }
    //Set box color
    SetColor(WindowHandle, HTuple(Box[0]));
    DispRectangle1(WindowHandle, R1, C1, R2, C2);
    SetDraw(WindowHandle, DrawMode);
  }
  //Write text.
  {
  HTuple end_val115 = (String.TupleLength())-1;
  HTuple step_val115 = 1;
  for (Index=0; Index.Continue(end_val115, step_val115); Index += step_val115)
  {
    CurrentColor = ((const HTuple&)Color)[Index%(Color.TupleLength())];
    if (0 != (HTuple(CurrentColor!=HTuple("")).TupleAnd(CurrentColor!=HTuple("auto"))))
    {
      SetColor(WindowHandle, CurrentColor);
    }
    else
    {
      SetRgb(WindowHandle, Red, Green, Blue);
    }
    Row = R1+(MaxHeight*Index);
    SetTposition(WindowHandle, Row, C1);
    WriteString(WindowHandle, HTuple(String[Index]));
  }
  }
  //Reset changed window settings
  SetRgb(WindowHandle, Red, Green, Blue);
  SetPart(WindowHandle, Row1Part, Column1Part, Row2Part, Column2Part);
  return;
}

// Chapter: Graphics / Output
void disp_title_and_information (HTuple WindowHandle, HTuple Title, HTuple Information)
{

  // Local iconic variables

  // Local control variables
  HTuple  WinRow, WinColumn, WinWidth;
  HTuple  WinHeight, NumTitleLines, Row, Column;
  HTuple  TextWidth, NumInfoLines, Ascent, Descent;
  HTuple  Width, Height;

  //global tuple gInfoDecor
  //global tuple gInfoPos
  //global tuple gTitlePos
  //global tuple gTitleDecor
  //
  GetWindowExtents(WindowHandle, &WinRow, &WinColumn, &WinWidth, &WinHeight);
  Title = ((""+Title)+"").TupleSplit("\n");
  NumTitleLines = Title.TupleLength();
  if (0 != (NumTitleLines>0))
  {
    Row = 12;
    if (0 != (ExpGetGlobalVar_gTitlePos()==HTuple("UpperLeft")))
    {
      Column = 12;
    }
    else if (0 != (ExpGetGlobalVar_gTitlePos()==HTuple("UpperCenter")))
    {
      max_line_width(WindowHandle, Title, &TextWidth);
      Column = (WinWidth/2)-(TextWidth/2);
    }
    else if (0 != (ExpGetGlobalVar_gTitlePos()==HTuple("UpperRight")))
    {
      if (0 != (HTuple(ExpGetGlobalVar_gTitleDecor()[1])==HTuple("true")))
      {
        max_line_width(WindowHandle, Title+"  ", &TextWidth);
      }
      else
      {
        max_line_width(WindowHandle, Title, &TextWidth);
      }
      Column = (WinWidth-TextWidth)-10;
    }
    else
    {
      //Unknown position!
      // stop(); only in hdevelop
    }
    disp_message(WindowHandle, Title, "window", Row, Column, HTuple(ExpGetGlobalVar_gTitleDecor()[0]),
        HTuple(ExpGetGlobalVar_gTitleDecor()[1]));
  }
  Information = ((""+Information)+"").TupleSplit("\n");
  NumInfoLines = Information.TupleLength();
  if (0 != (NumInfoLines>0))
  {
    if (0 != (ExpGetGlobalVar_gInfoPos()==HTuple("UpperLeft")))
    {
      Row = 12;
      Column = 12;
    }
    else if (0 != (ExpGetGlobalVar_gInfoPos()==HTuple("UpperRight")))
    {
      if (0 != (HTuple(ExpGetGlobalVar_gInfoDecor()[1])==HTuple("true")))
      {
        max_line_width(WindowHandle, Information+"  ", &TextWidth);
      }
      else
      {
        max_line_width(WindowHandle, Information, &TextWidth);
      }
      Row = 12;
      Column = (WinWidth-TextWidth)-12;
    }
    else if (0 != (ExpGetGlobalVar_gInfoPos()==HTuple("LowerLeft")))
    {
      GetStringExtents(WindowHandle, Information, &Ascent, &Descent,
          &Width, &Height);
      Row = (WinHeight-(NumInfoLines*Height))-12;
      Column = 12;
    }
    else
    {
      //Unknown position!
      // stop(); only in hdevelop
    }
    disp_message(WindowHandle, Information, "window", Row, Column, HTuple(ExpGetGlobalVar_gInfoDecor()[0]),
        HTuple(ExpGetGlobalVar_gInfoDecor()[1]));
  }
  //
  return;
}

// Chapter: Graphics / Output
// Short Description: Can replace disp_object_model_3d if there is no OpenGL available.
void disp_object_model_no_opengl (HObject *ModelContours, HTuple ObjectModel3DID,
    HTuple GenParamName, HTuple GenParamValue, HTuple WindowHandleBuffer,
    HTuple CamParam, HTuple PosesOut)
{

  // Local iconic variables

  // Local control variables
  HTuple  Idx, CustomParamName, CustomParamValue;
  HTuple  Font, IndicesDispBackGround, Indices, HasPolygons;
  HTuple  HasTri, HasPoints, HasLines, NumPoints;
  HTuple  IsPrimitive, Center, Diameter, OpenGlHiddenSurface;
  HTuple  CenterX, CenterY, CenterZ, PosObjectsZ;
  HTuple  I, Pose, HomMat3DObj, PosObjCenterX;
  HTuple  PosObjCenterY, PosObjCenterZ, PosObjectsX;
  HTuple  PosObjectsY, Color, Indices1, IndicesIntensities;
  HTuple  Indices2, J, Indices3, HomMat3D, SampledObjectModel3D;
  HTuple  X, Y, Z, HomMat3D1, Qx, Qy, Qz;
  HTuple  Row, Column, ObjectModel3DConvexHull, Exception;

  //This procedure allows to use project_object_model_3d to simulate a disp_object_model_3d
  //call for small objects. Large objects are sampled down to display.
  Idx = GenParamName.TupleFind("point_size");
  if (0 != (HTuple(Idx.TupleLength()).TupleAnd(Idx!=-1)))
  {
    CustomParamName = "point_size";
    CustomParamValue = ((const HTuple&)GenParamValue)[Idx];
    if (0 != (CustomParamValue==1))
    {
      CustomParamValue = 0;
    }
  }
  else
  {
    CustomParamName = HTuple();
    CustomParamValue = HTuple();
  }
  GetFont(WindowHandleBuffer, &Font);
  TupleFind(GenParamName, "disp_background", &IndicesDispBackGround);
  if (0 != (IndicesDispBackGround!=-1))
  {
    TupleFind(HTuple(GenParamName[IndicesDispBackGround]), "false", &Indices);
    if (0 != (Indices!=-1))
    {
      ClearWindow(WindowHandleBuffer);
    }
  }
  set_display_font(WindowHandleBuffer, 11, "mono", "false", "false");
  disp_message(WindowHandleBuffer, "OpenGL missing!", "image", 5, HTuple(CamParam[6])-130,
      "red", "false");
  SetFont(WindowHandleBuffer, Font);
  GetObjectModel3dParams(ObjectModel3DID, "has_polygons", &HasPolygons);
  GetObjectModel3dParams(ObjectModel3DID, "has_triangles", &HasTri);
  GetObjectModel3dParams(ObjectModel3DID, "has_points", &HasPoints);
  GetObjectModel3dParams(ObjectModel3DID, "has_lines", &HasLines);
  GetObjectModel3dParams(ObjectModel3DID, "num_points", &NumPoints);
  GetObjectModel3dParams(ObjectModel3DID, "has_primitive_data", &IsPrimitive);
  GetObjectModel3dParams(ObjectModel3DID, "center", &Center);
  GetObjectModel3dParams(ObjectModel3DID, "diameter", &Diameter);
  GetSystem("opengl_hidden_surface_removal_enable", &OpenGlHiddenSurface);
  SetSystem("opengl_hidden_surface_removal_enable", "false");
  //Sort the objects by inverse z
  CenterX = ((const HTuple&)Center)[HTuple::TupleGenSequence(0,(Center.TupleLength())-1,3)];
  CenterY = ((const HTuple&)Center)[HTuple::TupleGenSequence(0,(Center.TupleLength())-1,3)+1];
  CenterZ = ((const HTuple&)Center)[HTuple::TupleGenSequence(0,(Center.TupleLength())-1,3)+2];
  PosObjectsZ = HTuple();
  if (0 != ((PosesOut.TupleLength())>7))
  {
    {
    HTuple end_val40 = (ObjectModel3DID.TupleLength())-1;
    HTuple step_val40 = 1;
    for (I=0; I.Continue(end_val40, step_val40); I += step_val40)
    {
      Pose = PosesOut.TupleSelectRange(I*7,(I*7)+6);
      PoseToHomMat3d(Pose, &HomMat3DObj);
      AffineTransPoint3d(HomMat3DObj, HTuple(CenterX[I]), HTuple(CenterY[I]),
          HTuple(CenterZ[I]), &PosObjCenterX, &PosObjCenterY, &PosObjCenterZ);
      PosObjectsZ = PosObjectsZ.TupleConcat(PosObjCenterZ);
    }
    }
  }
  else
  {
    Pose = PosesOut.TupleSelectRange(0,6);
    PoseToHomMat3d(Pose, &HomMat3DObj);
    AffineTransPoint3d(HomMat3DObj, CenterX, CenterY, CenterZ, &PosObjectsX,
        &PosObjectsY, &PosObjectsZ);
  }
  Idx = (PosObjectsZ.TupleSortIndex()).TupleInverse();
  Color = "white";
  SetColor(WindowHandleBuffer, Color);
  if (0 != ((GenParamName.TupleLength())>0))
  {
    TupleFind(GenParamName, "colored", &Indices1);
    TupleFind(GenParamName, "intensity", &IndicesIntensities);
    TupleFind(GenParamName, "color", &Indices2);
    if (0 != (HTuple(Indices1[0])!=-1))
    {
      if (0 != (HTuple(GenParamValue[HTuple(Indices1[0])])==3))
      {
        Color.Clear();
        Color[0] = "red";
        Color[1] = "green";
        Color[2] = "blue";
      }
      else if (0 != (HTuple(GenParamValue[HTuple(Indices1[0])])==6))
      {
        Color.Clear();
        Color[0] = "red";
        Color[1] = "green";
        Color[2] = "blue";
        Color[3] = "cyan";
        Color[4] = "magenta";
        Color[5] = "yellow";
      }
      else if (0 != (HTuple(GenParamValue[HTuple(Indices1[0])])==12))
      {
        Color.Clear();
        Color[0] = "red";
        Color[1] = "green";
        Color[2] = "blue";
        Color[3] = "cyan";
        Color[4] = "magenta";
        Color[5] = "yellow";
        Color[6] = "coral";
        Color[7] = "slate blue";
        Color[8] = "spring green";
        Color[9] = "orange red";
        Color[10] = "pink";
        Color[11] = "gold";
      }
    }
    else if (0 != (HTuple(Indices2[0])!=-1))
    {
      Color = ((const HTuple&)GenParamValue)[HTuple(Indices2[0])];
    }
    else if (0 != (HTuple(IndicesIntensities[0])!=-1))
    {
    }
  }
  {
  HTuple end_val71 = (ObjectModel3DID.TupleLength())-1;
  HTuple step_val71 = 1;
  for (J=0; J.Continue(end_val71, step_val71); J += step_val71)
  {
    I = ((const HTuple&)Idx)[J];
    if (0 != (HTuple(HTuple(HTuple(HTuple(HasPolygons[I])==HTuple("true")).TupleOr(HTuple(HasTri[I])==HTuple("true"))).TupleOr(HTuple(HasPoints[I])==HTuple("true"))).TupleOr(HTuple(HasLines[I])==HTuple("true"))))
    {
      if (0 != ((GenParamName.TupleLength())>0))
      {
        TupleFind(GenParamName, "color_"+I, &Indices3);
        if (0 != (HTuple(Indices3[0])!=-1))
        {
          SetColor(WindowHandleBuffer, HTuple(GenParamValue[HTuple(Indices3[0])]));
        }
        else
        {
          SetColor(WindowHandleBuffer, HTuple(Color[I%(Color.TupleLength())]));
        }
      }
      if (0 != ((PosesOut.TupleLength())>=((I*7)+6)))
      {
        Pose = PosesOut.TupleSelectRange(I*7,(I*7)+6);
      }
      else
      {
        Pose = PosesOut.TupleSelectRange(0,6);
      }
      if (0 != (HTuple(NumPoints[I])<10000))
      {
        ProjectObjectModel3d(&(*ModelContours), HTuple(ObjectModel3DID[I]),
            CamParam, Pose, CustomParamName, CustomParamValue);
        DispObj((*ModelContours), WindowHandleBuffer);
      }
      else
      {
        PoseToHomMat3d(Pose, &HomMat3D);
        SampleObjectModel3d(HTuple(ObjectModel3DID[I]), "fast", 0.01*HTuple(Diameter[I]),
            HTuple(), HTuple(), &SampledObjectModel3D);
        ProjectObjectModel3d(&(*ModelContours), SampledObjectModel3D, CamParam,
            Pose, "point_size", 1);
        GetObjectModel3dParams(SampledObjectModel3D, "point_coord_x", &X);
        GetObjectModel3dParams(SampledObjectModel3D, "point_coord_y", &Y);
        GetObjectModel3dParams(SampledObjectModel3D, "point_coord_z", &Z);
        PoseToHomMat3d(Pose, &HomMat3D1);
        AffineTransPoint3d(HomMat3D1, X, Y, Z, &Qx, &Qy, &Qz);
        Project3dPoint(Qx, Qy, Qz, CamParam, &Row, &Column);
        DispObj((*ModelContours), WindowHandleBuffer);
        ClearObjectModel3d(SampledObjectModel3D);
      }
    }
    else
    {
      if (0 != ((GenParamName.TupleLength())>0))
      {
        TupleFind(GenParamName, "color_"+I, &Indices3);
        if (0 != (HTuple(Indices3[0])!=-1))
        {
          SetColor(WindowHandleBuffer, HTuple(GenParamValue[HTuple(Indices3[0])]));
        }
        else
        {
          SetColor(WindowHandleBuffer, HTuple(Color[I%(Color.TupleLength())]));
        }
      }
      if (0 != ((PosesOut.TupleLength())>=((I*7)+6)))
      {
        Pose = PosesOut.TupleSelectRange(I*7,(I*7)+6);
      }
      else
      {
        Pose = PosesOut.TupleSelectRange(0,6);
      }
      if (0 != (HTuple(IsPrimitive[I])==HTuple("true")))
      {
        try
        {
          ConvexHullObjectModel3d(HTuple(ObjectModel3DID[I]), &ObjectModel3DConvexHull);
          if (0 != (HTuple(NumPoints[I])<10000))
          {
            ProjectObjectModel3d(&(*ModelContours), ObjectModel3DConvexHull,
                CamParam, Pose, CustomParamName, CustomParamValue);
            DispObj((*ModelContours), WindowHandleBuffer);
          }
          else
          {
            PoseToHomMat3d(Pose, &HomMat3D);
            SampleObjectModel3d(ObjectModel3DConvexHull, "fast", 0.01*HTuple(Diameter[I]),
                HTuple(), HTuple(), &SampledObjectModel3D);
            ProjectObjectModel3d(&(*ModelContours), SampledObjectModel3D, CamParam,
                Pose, "point_size", 1);
            DispObj((*ModelContours), WindowHandleBuffer);
            ClearObjectModel3d(SampledObjectModel3D);
          }
          ClearObjectModel3d(ObjectModel3DConvexHull);
        }
        // catch (Exception)
        catch (HalconCpp::HException &HDevExpDefaultException)
        {
          HDevExpDefaultException.ToHTuple(&Exception);
        }
      }
    }
  }
  }
  SetSystem("opengl_hidden_surface_removal_enable", OpenGlHiddenSurface);
  return;
}

// Chapter: Graphics / Output
// Short Description: Interactively display 3D object models
void visualize_object_model_3d_color (HTuple WindowHandle, HTuple ObjectModel3D,
    HTuple CamParam, HTuple PoseIn, HTuple GenParamName, HTuple GenParamValue,
    HTuple Title, HTuple Label, HTuple Information, HTuple *PoseOut)
{

  // Local iconic variables
  HObject  ho_Image, ho_ImageDump;

  // Local control variables
  HTuple  ExpTmpLocalVar_gDispObjOffset, ExpTmpLocalVar_gLabelsDecor;
  HTuple  ExpTmpLocalVar_gInfoDecor, ExpTmpLocalVar_gInfoPos;
  HTuple  ExpTmpLocalVar_gTitlePos, ExpTmpLocalVar_gTitleDecor;
  HTuple  ExpTmpLocalVar_gTerminationButtonLabel, ExpTmpLocalVar_gAlphaDeselected;
  HTuple  ExpTmpLocalVar_gIsSinglePose, ExpTmpLocalVar_gUsesOpenGL;
  HTuple  Scene3DTest, Scene3D, WindowHandleBuffer;
  HTuple  TrackballSize, VirtualTrackball, MouseMapping;
  HTuple  WaitForButtonRelease, MaxNumModels, WindowCenteredRotation;
  HTuple  NumModels, SelectedObject, ClipRegion;
  HTuple  CPLength, RowNotUsed, ColumnNotUsed, Width;
  HTuple  Height, WPRow1, WPColumn1, WPRow2, WPColumn2;
  HTuple  CamParamValue, CamWidth, CamHeight, Scale;
  HTuple  Indices, DispBackground, Mask, Center;
  HTuple  Poses, HomMat3Ds, Sequence, PoseEstimated;
  HTuple  Font, Exception, OpenGLInfo, DummyObjectModel3D;
  HTuple  CameraIndexTest, PoseTest, InstanceIndexTest;
  HTuple  MinImageSize, TrackballRadiusPixel, Ascent;
  HTuple  Descent, TextWidth, TextHeight, NumChannels;
  HTuple  ColorImage, CameraIndex, AllInstances;
  HTuple  SetLight, LightParam, LightPosition, LightKind;
  HTuple  LightIndex, PersistenceParamName, PersistenceParamValue;
  HTuple  AlphaOrig, I, ParamName, ParamValue;
  HTuple  ParamNameTrunk, Instance, HomMat3D, Qx;
  HTuple  Qy, Qz, TBCenter, TBSize, ButtonHold;
  HTuple  VisualizeTB, MaxIndex, TrackballCenterRow;
  HTuple  TrackballCenterCol, GraphEvent, Exit, GraphButtonRow;
  HTuple  GraphButtonColumn, GraphButton, ButtonReleased;
  HTuple  e;

  //The procedure visualize_object_model_3d can be used to display
  //one or more 3d object models and to interactively modify
  //the object poses by using the mouse.
  //
  //The pose can be modified by moving the mouse while
  //pressing a mouse button. The default settings are:
  //
  // Rotate: Left mouse button
  // Zoom: Shift + Left mouse button (or Center mouse button)
  // Pan: Ctrl + Left mouse button
  //
  //Furthermore, it is possible to select and deselect objects,
  //to decrease the mouse sensitivity, and to toggle the
  //inspection mode (see the description of the generic parameter
  //'inspection_mode' below):
  //
  // (De-)select object(s): Right mouse button
  // Low mouse sensitivity: Alt + Mouse button
  // Toggle inspection mode: Ctrl + Alt + Left mouse button
  //
  //In GenParamName and GenParamValue all generic Parameters
  //of disp_object_model_3d are supported.
  //
  //**********************************************************
  //Define global variables
  //**********************************************************
  //
  //global def tuple gDispObjOffset
  //global def tuple gLabelsDecor
  //global def tuple gInfoDecor
  //global def tuple gInfoPos
  //global def tuple gTitlePos
  //global def tuple gTitleDecor
  //global def tuple gTerminationButtonLabel
  //global def tuple gAlphaDeselected
  //global def tuple gIsSinglePose
  //global def tuple gUsesOpenGL
  //
  //**********************************************************
  //Initialize Handles to enable correct handling in error case
  //**********************************************************
  Scene3DTest = HTuple();
  Scene3D = HTuple();
  WindowHandleBuffer = HTuple();

  //**********************************************************
  //Some user defines that may be adapted if desired
  //**********************************************************
  //
  //TrackballSize defines the diameter of the trackball in
  //the image with respect to the smaller image dimension.
  TrackballSize = 0.8;
  //
  //VirtualTrackball defines the type of virtual trackball that
  //shall be used ('shoemake' or 'bell').
  VirtualTrackball = "shoemake";
  //VirtualTrackball := 'bell'
  //
  //Functionality of mouse buttons
  //    1: Left Button
  //    2: Middle Button
  //    4: Right Button
  //    5: Left+Right Mousebutton
  //  8+x: Shift + Mousebutton
  // 16+x: Ctrl + Mousebutton
  // 48+x: Ctrl + Alt + Mousebutton
  //in the order [Translate, Rotate, Scale, ScaleAlternative1, ScaleAlternative2, SelectObjects, ToggleSelectionMode]
  MouseMapping.Clear();
  MouseMapping[0] = 17;
  MouseMapping[1] = 1;
  MouseMapping[2] = 2;
  MouseMapping[3] = 5;
  MouseMapping[4] = 9;
  MouseMapping[5] = 4;
  MouseMapping[6] = 49;
  //
  //The labels of the objects appear next to their projected
  //center. With gDispObjOffset a fixed offset is added
  //                  R,  C
  ExpTmpLocalVar_gDispObjOffset.Clear();
  ExpTmpLocalVar_gDispObjOffset[0] = -30;
  ExpTmpLocalVar_gDispObjOffset[1] = 0;
  ExpSetGlobalVar_gDispObjOffset(ExpTmpLocalVar_gDispObjOffset);
  //
  //Customize the decoration of the different text elements
  //              Color,   Box
  ExpTmpLocalVar_gInfoDecor.Clear();
  ExpTmpLocalVar_gInfoDecor[0] = "white";
  ExpTmpLocalVar_gInfoDecor[1] = "false";
  ExpSetGlobalVar_gInfoDecor(ExpTmpLocalVar_gInfoDecor);
  ExpTmpLocalVar_gLabelsDecor.Clear();
  ExpTmpLocalVar_gLabelsDecor[0] = "white";
  ExpTmpLocalVar_gLabelsDecor[1] = "false";
  ExpSetGlobalVar_gLabelsDecor(ExpTmpLocalVar_gLabelsDecor);
  ExpTmpLocalVar_gTitleDecor.Clear();
  ExpTmpLocalVar_gTitleDecor[0] = "black";
  ExpTmpLocalVar_gTitleDecor[1] = "true";
  ExpSetGlobalVar_gTitleDecor(ExpTmpLocalVar_gTitleDecor);
  //
  //Customize the position of some text elements
  //  gInfoPos has one of the values
  //  {'UpperLeft', 'LowerLeft', 'UpperRight'}
  ExpTmpLocalVar_gInfoPos = "LowerLeft";
  ExpSetGlobalVar_gInfoPos(ExpTmpLocalVar_gInfoPos);
  //  gTitlePos has one of the values
  //  {'UpperLeft', 'UpperCenter', 'UpperRight'}
  ExpTmpLocalVar_gTitlePos = "UpperLeft";
  ExpSetGlobalVar_gTitlePos(ExpTmpLocalVar_gTitlePos);
  //Alpha value (=1-transparency) that is used for visualizing
  //the objects that are not selected
  ExpTmpLocalVar_gAlphaDeselected = 0.3;
  ExpSetGlobalVar_gAlphaDeselected(ExpTmpLocalVar_gAlphaDeselected);
  //Customize the label of the continue button
  ExpTmpLocalVar_gTerminationButtonLabel = " Continue ";
  ExpSetGlobalVar_gTerminationButtonLabel(ExpTmpLocalVar_gTerminationButtonLabel);
  //Define if the continue button responds to a single click event or
  //if it responds only if the mouse button is released while being placed
  //over the continue button.
  //'true':  Wait until the continue button has been released.
  //         This should be used to avoid unwanted continuations of
  //         subsequent calls of visualize_object_model_3d, which can
  //         otherwise occur if the mouse button remains pressed while the
  //         next visualization is active.
  //'false': Continue the execution already if the continue button is
  //         pressed. This option allows a fast forwarding through
  //         subsequent calls of visualize_object_model_3d.
  WaitForButtonRelease = "true";
  //Number of 3D Object models that can be selected and handled individually.
  //If there are more models passed then this number, some calculations
  //are performed differently and the individual selection and handling
  //of models is not supported anymore. Note that the value of MaxNumModels
  //can be overwritten with the generic parameter max_num_selectable_models.
  MaxNumModels = 1000;
  //Defines the default for the initial state of the rotation center:
  //(1) The rotation center is fixed in the center of the image and lies
  //    on the surface of the object.
  //(2) The rotation center lies in the center of the object.
  WindowCenteredRotation = 2;
  //
  //**********************************************************
  //
  //Initialize some values
  NumModels = ObjectModel3D.TupleLength();
  SelectedObject = HTuple(NumModels,1);
  //
  //Apply some system settings
  // dev_set_preferences(...); only in hdevelop
  // dev_get_preferences(...); only in hdevelop
  // dev_set_preferences(...); only in hdevelop
  GetSystem("clip_region", &ClipRegion);
  SetSystem("clip_region", "false");
  dev_update_off();
  //
  //Check if GenParamName matches GenParamValue
  if (0 != (int((GenParamName.TupleLength())!=(GenParamValue.TupleLength()))))
  {
    throw HException("Number of generic parameters does not match number of generic parameter values");
  }
  //
  try
  {
    //
    //Refactor camera parameters to fit to window size
    //
    CPLength = CamParam.TupleLength();
    GetWindowExtents(WindowHandle, &RowNotUsed, &ColumnNotUsed, &Width,
        &Height);
    GetPart(WindowHandle, &WPRow1, &WPColumn1, &WPRow2, &WPColumn2);
    SetPart(WindowHandle, 0, 0, Height-1, Width-1);
    if (0 != (int(CPLength==0)))
    {
      gen_cam_par_area_scan_division(0.06, 0, 8.5e-6, 8.5e-6, Width/2, Height/2,
          Width, Height, &CamParam);
    }
    else
    {
      get_cam_par_data(CamParam, (((((HTuple("sx").Append("sy")).Append("cx")).Append("cy")).Append("image_width")).Append("image_height")),
          &CamParamValue);
      CamWidth = HTuple(CamParamValue[4]).TupleReal();
      CamHeight = HTuple(CamParamValue[5]).TupleReal();
      Scale = ((Width/CamWidth).TupleConcat(Height/CamHeight)).TupleMin();
      set_cam_par_data(CamParam, "sx", HTuple(CamParamValue[0])/Scale, &CamParam);
      set_cam_par_data(CamParam, "sy", HTuple(CamParamValue[1])/Scale, &CamParam);
      set_cam_par_data(CamParam, "cx", HTuple(CamParamValue[2])*Scale, &CamParam);
      set_cam_par_data(CamParam, "cy", HTuple(CamParamValue[3])*Scale, &CamParam);
      set_cam_par_data(CamParam, "image_width", (HTuple(CamParamValue[4])*Scale).TupleInt(),
          &CamParam);
      set_cam_par_data(CamParam, "image_height", (HTuple(CamParamValue[5])*Scale).TupleInt(),
          &CamParam);
    }
    //
    //Check the generic parameters for max_num_selectable_models
    //(Note that the default is set above to MaxNumModels := 1000)
    Indices = GenParamName.TupleFind("max_num_selectable_models");
    if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
    {
      if (0 != (HTuple(GenParamValue[HTuple(Indices[0])]).TupleIsNumber()))
      {
        if (0 != (int(((HTuple(GenParamValue[HTuple(Indices[0])]).TupleNumber()).TupleInt())<1)))
        {
          //Wrong parameter value: Only integer values greater than 0 are allowed
          throw HException("Wrong value for parameter 'max_num_selectable_models' (must be an integer value greater than 0)");
        }
      }
      else
      {
        //Wrong parameter value: Only integer values greater than 0 are allowed
        throw HException("Wrong value for parameter 'max_num_selectable_models' (must be an integer value greater than 0)");
      }
      MaxNumModels = (HTuple(GenParamValue[HTuple(Indices[0])]).TupleNumber()).TupleInt();
      GenParamName = GenParamName.TupleRemove(Indices);
      GenParamValue = GenParamValue.TupleRemove(Indices);
    }
    //
    //Check the generic parameters for window_centered_rotation
    //(Note that the default is set above to WindowCenteredRotation := 2)
    Indices = GenParamName.TupleFind("inspection_mode");
    if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
    {
      if (0 != (int(HTuple(GenParamValue[HTuple(Indices[0])])==HTuple("surface"))))
      {
        WindowCenteredRotation = 1;
      }
      else if (0 != (int(HTuple(GenParamValue[HTuple(Indices[0])])==HTuple("standard"))))
      {
        WindowCenteredRotation = 2;
      }
      else
      {
        //Wrong parameter value, use default value
      }
      GenParamName = GenParamName.TupleRemove(Indices);
      GenParamValue = GenParamValue.TupleRemove(Indices);
    }
    //
    //Check the generic parameters for disp_background
    //(The former parameter name 'use_background' is still supported
    // for compatibility reasons)
    DispBackground = "false";
    if (0 != (int((GenParamName.TupleLength())>0)))
    {
      Mask = (GenParamName.TupleEqualElem("disp_background")).TupleOr(GenParamName.TupleEqualElem("use_background"));
      Indices = Mask.TupleFind(1);
    }
    else
    {
      Indices = -1;
    }
    if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
    {
      DispBackground = HTuple(GenParamValue[HTuple(Indices[0])]);
      if (0 != (HTuple(int(DispBackground!=HTuple("true"))).TupleAnd(int(DispBackground!=HTuple("false")))))
      {
        //Wrong parameter value: Only 'true' and 'false' are allowed
        throw HException("Wrong value for parameter 'disp_background' (must be either 'true' or 'false')");
      }
      //Note that the background is handled explicitly in this procedure
      //and therefore, the parameter is removed from the list of
      //parameters and disp_background is always set to true (see below)
      GenParamName = GenParamName.TupleRemove(Indices);
      GenParamValue = GenParamValue.TupleRemove(Indices);
    }
    //
    //Read and check the parameter Label for each object
    if (0 != (int((Label.TupleLength())==0)))
    {
      //no labels set -> leave as []
    }
    else if (0 != (int((Label.TupleLength())==1)))
    {
      //a single label set for all models
      Label = HTuple(NumModels,Label);
    }
    else
    {
      if (0 != (int((Label.TupleLength())!=NumModels)))
      {
        //Number of elements in Label does not match
        //the number of object models.
        throw HException(((HTuple(HTuple("Number of elements in Label (")+(Label.TupleLength()))+") does not match the number of object models(")+NumModels)+").");
      }
    }
    //Convert labels into strings
    Label = ""+Label;
    //
    //Read and check the parameter PoseIn for each object
    get_object_models_center(ObjectModel3D, &Center);
    if (0 != (int(Center==HTuple())))
    {
      Center.Clear();
      Center[0] = 0;
      Center[1] = 0;
      Center[2] = 0;
    }
    if (0 != (int((PoseIn.TupleLength())==0)))
    {
      //If no pose was specified by the caller, automatically calculate
      //a pose that is appropriate for the visualization.
      //Set the initial model reference pose. The orientation is parallel
      //to the object coordinate system, the position is at the center
      //of gravity of all models.
      CreatePose(-HTuple(Center[0]), -HTuple(Center[1]), -HTuple(Center[2]),
          0, 0, 0, "Rp+T", "gba", "point", &PoseIn);
      determine_optimum_pose_distance(ObjectModel3D, CamParam, 0.9, PoseIn,
          &PoseEstimated);
      Poses = HTuple();
      HomMat3Ds = HTuple();
      Sequence = HTuple::TupleGenSequence(0,(NumModels*7)-1,1);
      Poses = HTuple(PoseEstimated[Sequence%7]);
      ExpTmpLocalVar_gIsSinglePose = 1;
      ExpSetGlobalVar_gIsSinglePose(ExpTmpLocalVar_gIsSinglePose);
    }
    else if (0 != (int((PoseIn.TupleLength())==7)))
    {
      Poses = HTuple();
      HomMat3Ds = HTuple();
      Sequence = HTuple::TupleGenSequence(0,(NumModels*7)-1,1);
      Poses = HTuple(PoseIn[Sequence%7]);
      ExpTmpLocalVar_gIsSinglePose = 1;
      ExpSetGlobalVar_gIsSinglePose(ExpTmpLocalVar_gIsSinglePose);
    }
    else
    {
      if (0 != (int((PoseIn.TupleLength())!=((ObjectModel3D.TupleLength())*7))))
      {
        //Wrong number of values of input control parameter 'PoseIn'
        throw HException("Wrong number of values of input control parameter 'PoseIn'.");
      }
      else
      {
        Poses = PoseIn;
      }
      ExpTmpLocalVar_gIsSinglePose = 0;
      ExpSetGlobalVar_gIsSinglePose(ExpTmpLocalVar_gIsSinglePose);
    }

    //
    //Open (invisible) buffer window to avoid flickering
    OpenWindow(0, 0, Width, Height, 0, "buffer", "", &WindowHandleBuffer);
    SetPart(WindowHandleBuffer, 0, 0, Height-1, Width-1);
    GetFont(WindowHandle, &Font);
    try
    {
      SetFont(WindowHandleBuffer, Font);
    }
    // catch (Exception)
    catch (HException &HDevExpDefaultException)
    {
      HDevExpDefaultException.ToHTuple(&Exception);
    }
    //
    // Is OpenGL available and should it be used?
    ExpTmpLocalVar_gUsesOpenGL = "true";
    ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
    Indices = GenParamName.TupleFind("opengl");
    if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
    {
      ExpTmpLocalVar_gUsesOpenGL = HTuple(GenParamValue[HTuple(Indices[0])]);
      ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
      GenParamName = GenParamName.TupleRemove(Indices);
      GenParamValue = GenParamValue.TupleRemove(Indices);
      if (0 != (HTuple(int(ExpGetGlobalVar_gUsesOpenGL()!=HTuple("true"))).TupleAnd(int(ExpGetGlobalVar_gUsesOpenGL()!=HTuple("false")))))
      {
        //Wrong parameter value: Only 'true' and 'false' are allowed
        throw HException("Wrong value for parameter 'opengl' (must be either 'true' or 'false')");
      }
    }
    if (0 != (int(ExpGetGlobalVar_gUsesOpenGL()==HTuple("true"))))
    {
      GetSystem("opengl_info", &OpenGLInfo);
      if (0 != (int(OpenGLInfo==HTuple("No OpenGL support included."))))
      {
        ExpTmpLocalVar_gUsesOpenGL = "false";
        ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
      }
      else
      {
        GenObjectModel3dFromPoints(0, 0, 0, &DummyObjectModel3D);
        CreateScene3d(&Scene3DTest);
        AddScene3dCamera(Scene3DTest, CamParam, &CameraIndexTest);
        determine_optimum_pose_distance(DummyObjectModel3D, CamParam, 0.9,
            ((((((HTuple(0).Append(0)).Append(0)).Append(0)).Append(0)).Append(0)).Append(0)),
            &PoseTest);
        AddScene3dInstance(Scene3DTest, DummyObjectModel3D, PoseTest, &InstanceIndexTest);
        try
        {
          DisplayScene3d(WindowHandleBuffer, Scene3DTest, InstanceIndexTest);
        }
        // catch (Exception)
        catch (HException &HDevExpDefaultException)
        {
          HDevExpDefaultException.ToHTuple(&Exception);
          ExpTmpLocalVar_gUsesOpenGL = "false";
          ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
        }
        ClearScene3d(Scene3DTest);
        Scene3DTest = HTuple();
        ClearObjectModel3d(DummyObjectModel3D);
      }
    }
    //
    //Compute the trackball
    MinImageSize = (Width.TupleConcat(Height)).TupleMin();
    TrackballRadiusPixel = (TrackballSize*MinImageSize)/2.0;
    //
    //Measure the text extents for the continue button in the
    //graphics window
    GetStringExtents(WindowHandleBuffer, ExpGetGlobalVar_gTerminationButtonLabel()+"  ",
        &Ascent, &Descent, &TextWidth, &TextHeight);
    //
    //Store background image
    if (0 != (int(DispBackground==HTuple("false"))))
    {
      ClearWindow(WindowHandle);
    }
    DumpWindowImage(&ho_Image, WindowHandle);
    //Special treatment for color background images necessary
    CountChannels(ho_Image, &NumChannels);
    ColorImage = int(NumChannels==3);
    //
    CreateScene3d(&Scene3D);
    AddScene3dCamera(Scene3D, CamParam, &CameraIndex);
    AddScene3dInstance(Scene3D, ObjectModel3D, Poses, &AllInstances);
    //Always set 'disp_background' to true,  because it is handled explicitly
    //in this procedure (see above)
    SetScene3dParam(Scene3D, "disp_background", "true");
    //Check if we have to set light specific parameters
    SetLight = GenParamName.TupleRegexpTest("light_");
    if (0 != SetLight)
    {
      //set position of light source
      Indices = GenParamName.TupleFind("light_position");
      if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
      {
        //If multiple light positions are given, use the last one
        LightParam = (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])]).TupleSplit(HTuple(", "))).TupleNumber();
        if (0 != (int((LightParam.TupleLength())!=4)))
        {
          throw HException("light_position must be given as a string that contains four space separated floating point numbers");
        }
        LightPosition = LightParam.TupleSelectRange(0,2);
        LightKind = "point_light";
        if (0 != (int(HTuple(LightParam[3])==0)))
        {
          LightKind = "directional_light";
        }
        //Currently, only one light source is supported
        RemoveScene3dLight(Scene3D, 0);
        AddScene3dLight(Scene3D, LightPosition, LightKind, &LightIndex);
        TupleRemove(GenParamName, Indices, &GenParamName);
        TupleRemove(GenParamValue, Indices, &GenParamValue);
      }
      //set ambient part of light source
      Indices = GenParamName.TupleFind("light_ambient");
      if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
      {
        //If the ambient part is set multiple times, use the last setting
        LightParam = (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])]).TupleSplit(HTuple(", "))).TupleNumber();
        if (0 != (int((LightParam.TupleLength())<3)))
        {
          throw HException("light_ambient must be given as a string that contains three space separated floating point numbers");
        }
        SetScene3dLightParam(Scene3D, 0, "ambient", LightParam.TupleSelectRange(0,2));
        TupleRemove(GenParamName, Indices, &GenParamName);
        TupleRemove(GenParamValue, Indices, &GenParamValue);
      }
      //Set diffuse part of light source
      Indices = GenParamName.TupleFind("light_diffuse");
      if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
      {
        //If the diffuse part is set multiple times, use the last setting
        LightParam = (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])]).TupleSplit(HTuple(", "))).TupleNumber();
        if (0 != (int((LightParam.TupleLength())<3)))
        {
          throw HException("light_diffuse must be given as a string that contains three space separated floating point numbers");
        }
        SetScene3dLightParam(Scene3D, 0, "diffuse", LightParam.TupleSelectRange(0,2));
        TupleRemove(GenParamName, Indices, &GenParamName);
        TupleRemove(GenParamValue, Indices, &GenParamValue);
      }
    }
    //
    //Handle persistence parameters separately because persistence will
    //only be activated immediately before leaving the visualization
    //procedure
    PersistenceParamName = HTuple();
    PersistenceParamValue = HTuple();
    //Set position of light source
    Indices = GenParamName.TupleFind("object_index_persistence");
    if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
    {
      if (0 != (int(HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])])==HTuple("true"))))
      {
        PersistenceParamName = PersistenceParamName.TupleConcat("object_index_persistence");
        PersistenceParamValue = PersistenceParamValue.TupleConcat("true");
      }
      else if (0 != (int(HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])])==HTuple("false"))))
      {
      }
      else
      {
        throw HException("Wrong value for parameter 'object_index_persistence' (must be either 'true' or 'false')");
      }
      TupleRemove(GenParamName, Indices, &GenParamName);
      TupleRemove(GenParamValue, Indices, &GenParamValue);
    }
    Indices = GenParamName.TupleFind("depth_persistence");
    if (0 != (HTuple(int(Indices!=-1)).TupleAnd(int(Indices!=HTuple()))))
    {
      if (0 != (int(HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])])==HTuple("true"))))
      {
        PersistenceParamName = PersistenceParamName.TupleConcat("depth_persistence");
        PersistenceParamValue = PersistenceParamValue.TupleConcat("true");
      }
      else if (0 != (int(HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])])==HTuple("false"))))
      {
      }
      else
      {
        throw HException("Wrong value for parameter 'depth_persistence' (must be either 'true' or 'false')");
      }
      TupleRemove(GenParamName, Indices, &GenParamName);
      TupleRemove(GenParamValue, Indices, &GenParamValue);
    }
    //
    //Parse the generic parameters
    //- First, all parameters that are understood by set_scene_3d_instance_param
    AlphaOrig = HTuple(NumModels,1);
    {
    HTuple end_val412 = (GenParamName.TupleLength())-1;
    HTuple step_val412 = 1;
    for (I=0; I.Continue(end_val412, step_val412); I += step_val412)
    {
      ParamName = HTuple(GenParamName[I]);
      ParamValue = HTuple(GenParamValue[I]);
      //Check if this parameter is understood by set_scene_3d_param
      if (0 != (int(ParamName==HTuple("alpha"))))
      {
        AlphaOrig = HTuple(NumModels,ParamValue);
      }
      try
      {
        SetScene3dParam(Scene3D, ParamName, ParamValue);
        continue;
      }
      // catch (Exception)
      catch (HException &HDevExpDefaultException)
      {
        HDevExpDefaultException.ToHTuple(&Exception);
        if (0 != (HTuple(int(HTuple(Exception[0])==1203)).TupleOr(int(HTuple(Exception[0])==1303))))
        {
          if (0 != (HTuple(HTuple(HTuple(int(ParamName==HTuple("color_attrib"))).TupleOr(int(ParamName==HTuple("red_channel_attrib")))).TupleOr(int(ParamName==HTuple("green_channel_attrib")))).TupleOr(int(ParamName==HTuple("blue_channel_attrib")))))
          {
            throw HException(((((("Wrong type or value for parameter "+ParamName)+": ")+ParamValue)+". ")+ParamValue)+" may not be attached to the points of the 3D object model. Compare the parameter AttachExtAttribTo of set_object_model_3d_attrib.");
          }
          else
          {
            throw HException((("Wrong type or value for parameter "+ParamName)+": ")+ParamValue);
          }
        }
      }
      //Check if it is a parameter that is valid for only one instance
      //and therefore can be set only with set_scene_3d_instance_param
      ParamNameTrunk = ParamName.TupleRegexpReplace("_\\d+$","");
      if (0 != (int(ParamName==ParamNameTrunk)))
      {
        Instance = HTuple::TupleGenSequence(0,NumModels-1,1);
      }
      else
      {
        Instance = (ParamName.TupleRegexpReplace(("^"+ParamNameTrunk)+"_(\\d+)$","$1")).TupleNumber();
        if (0 != (HTuple(int(Instance<0)).TupleOr(int(Instance>(NumModels-1)))))
        {
          throw HException(("Parameter "+ParamName)+" refers to a non existing 3D object model");
        }
      }
      try
      {
        SetScene3dInstanceParam(Scene3D, Instance, ParamNameTrunk, ParamValue);
      }
      // catch (Exception)
      catch (HException &HDevExpDefaultException)
      {
        HDevExpDefaultException.ToHTuple(&Exception);
        if (0 != (HTuple(int(HTuple(Exception[0])==1204)).TupleOr(int(HTuple(Exception[0])==1304))))
        {
          if (0 != (HTuple(HTuple(HTuple(int(ParamNameTrunk==HTuple("color_attrib"))).TupleOr(int(ParamNameTrunk==HTuple("red_channel_attrib")))).TupleOr(int(ParamNameTrunk==HTuple("green_channel_attrib")))).TupleOr(int(ParamNameTrunk==HTuple("blue_channel_attrib")))))
          {
            throw HException(((((("Wrong type or value for parameter "+ParamName)+": ")+ParamValue)+". ")+ParamValue)+" may not be attached to the points of the 3D object model. Compare the parameter AttachExtAttribTo of set_object_model_3d_attrib.");
          }
          else
          {
            throw HException((("Wrong type or value for parameter "+ParamName)+": ")+ParamValue);
          }
        }
        else if (0 != (HTuple(int(HTuple(Exception[0])==1203)).TupleOr(int(HTuple(Exception[0])==1303))))
        {
          throw HException("Wrong parameter name "+ParamName);
        }
        else
        {
          throw HException(Exception);
        }
      }
      if (0 != (int(ParamNameTrunk==HTuple("alpha"))))
      {
        AlphaOrig[Instance] = ParamValue;
      }
    }
    }
    //
    //Start the visualization loop
    PoseToHomMat3d(Poses.TupleSelectRange(0,6), &HomMat3D);
    AffineTransPoint3d(HomMat3D, HTuple(Center[0]), HTuple(Center[1]), HTuple(Center[2]),
        &Qx, &Qy, &Qz);
    TBCenter.Clear();
    TBCenter.Append(Qx);
    TBCenter.Append(Qy);
    TBCenter.Append(Qz);
    TBSize = (0.5+((0.5*(SelectedObject.TupleSum()))/NumModels))*TrackballRadiusPixel;
    ButtonHold = 0;
    while (0 != 1)
    {
      VisualizeTB = int((SelectedObject.TupleMax())!=0);
      MaxIndex = ((HTuple(ObjectModel3D.TupleLength()).TupleConcat(MaxNumModels)).TupleMin())-1;
      //Set trackball fixed in the center of the window
      TrackballCenterRow = Height/2;
      TrackballCenterCol = Width/2;
      if (0 != (int(WindowCenteredRotation==1)))
      {
        try
        {
          get_trackball_center_fixed(SelectedObject.TupleSelectRange(0,MaxIndex),
              TrackballCenterRow, TrackballCenterCol, TrackballRadiusPixel,
              Scene3D, ObjectModel3D.TupleSelectRange(0,MaxIndex), Poses.TupleSelectRange(0,((MaxIndex+1)*7)-1),
              WindowHandleBuffer, CamParam, GenParamName, GenParamValue,
              &TBCenter, &TBSize);
        }
        // catch (Exception)
        catch (HException &HDevExpDefaultException)
        {
          HDevExpDefaultException.ToHTuple(&Exception);
          disp_message(WindowHandle, "Surface inspection mode is not available.",
              "image", 5, 20, "red", "true");
          WindowCenteredRotation = 2;
          get_trackball_center(SelectedObject.TupleSelectRange(0,MaxIndex),
              TrackballRadiusPixel, ObjectModel3D.TupleSelectRange(0,MaxIndex),
              Poses.TupleSelectRange(0,((MaxIndex+1)*7)-1), &TBCenter, &TBSize);
          WaitSeconds(1);
        }
      }
      else
      {
        get_trackball_center(SelectedObject.TupleSelectRange(0,MaxIndex), TrackballRadiusPixel,
            ObjectModel3D.TupleSelectRange(0,MaxIndex), Poses.TupleSelectRange(0,((MaxIndex+1)*7)-1),
            &TBCenter, &TBSize);
      }
      dump_image_output(ho_Image, WindowHandleBuffer, Scene3D, AlphaOrig,
          ObjectModel3D, GenParamName, GenParamValue, CamParam, Poses,
          ColorImage, Title, Information, Label, VisualizeTB, "true",
          TrackballCenterRow, TrackballCenterCol, TBSize, SelectedObject,
          WindowCenteredRotation, TBCenter);
      DumpWindowImage(&ho_ImageDump, WindowHandleBuffer);
      HDevWindowStack::SetActive(WindowHandle);
      if (HDevWindowStack::IsOpen())
        DispObj(ho_ImageDump, HDevWindowStack::GetActive());
      //
      //Check for mouse events
      GraphEvent = 0;
      Exit = 0;
      while (0 != 1)
      {
        //
        //Check graphic event
        try
        {
          GetMpositionSubPix(WindowHandle, &GraphButtonRow, &GraphButtonColumn,
              &GraphButton);
          if (0 != (int(GraphButton!=0)))
          {
            if (0 != (HTuple(HTuple(HTuple(int(GraphButtonRow>((Height-TextHeight)-25))).TupleAnd(int(GraphButtonRow((Width-TextWidth)-15)))).TupleAnd(int(GraphButtonColumn((Height-TextHeight)-25))).TupleAnd(int(GraphButtonRow((Width-TextWidth)-15)))).TupleAnd(int(GraphButtonColumn0)))
    {
      DispObjectModel3d(WindowHandle, ObjectModel3D, CamParam, Poses,
          (HTuple("disp_background").Append("alpha")).TupleConcat(PersistenceParamName),
          (HTuple("true").Append(0.0)).TupleConcat(PersistenceParamValue));
    }
    //
    //Compute the output pose
    if (0 != ExpGetGlobalVar_gIsSinglePose())
    {
      (*PoseOut) = Poses.TupleSelectRange(0,6);
    }
    else
    {
      (*PoseOut) = Poses;
    }
    //
    //Clean up
    SetSystem("clip_region", ClipRegion);
    // dev_set_preferences(...); only in hdevelop
    // dev_set_preferences(...); only in hdevelop
    dump_image_output(ho_Image, WindowHandleBuffer, Scene3D, AlphaOrig,
        ObjectModel3D, GenParamName, GenParamValue, CamParam, Poses,
        ColorImage, Title, HTuple(), Label, 0, "false", TrackballCenterRow,
        TrackballCenterCol, TBSize, SelectedObject, WindowCenteredRotation,
        TBCenter);
    DumpWindowImage(&ho_ImageDump, WindowHandleBuffer);
    HDevWindowStack::SetActive(WindowHandle);
    if (HDevWindowStack::IsOpen())
      DispObj(ho_ImageDump, HDevWindowStack::GetActive());
    CloseWindow(WindowHandleBuffer);
    SetPart(WindowHandle, WPRow1, WPColumn1, WPRow2, WPColumn2);
    ClearScene3d(Scene3D);
    Scene3D = HTuple();
  }
  // catch (Exception)
  catch (HException &HDevExpDefaultException)
  {
    HDevExpDefaultException.ToHTuple(&Exception);
    try
    {
      if (0 != (int(0<(Scene3DTest.TupleLength()))))
      {
        ClearScene3d(Scene3DTest);
        Scene3DTest = HTuple();
      }
      if (0 != (int(0<(Scene3D.TupleLength()))))
      {
        ClearScene3d(Scene3D);
        Scene3D = HTuple();
      }
      if (0 != (int(0<(WindowHandleBuffer.TupleLength()))))
      {
        CloseWindow(WindowHandleBuffer);
        WindowHandleBuffer = HTuple();
      }
    }
    // catch (e)
    catch (HException &HDevExpDefaultException)
    {
      HDevExpDefaultException.ToHTuple(&e);
      //suppress all further exceptions to return the original exception
    }

    throw HException(Exception);
  }
  return;
}



// Chapter: Graphics / Output
// Short Description: Determine the optimum distance of the object to obtain a reasonable visualization
void determine_optimum_pose_distance (HTuple ObjectModel3DID, HTuple CamParam,
    HTuple ImageCoverage, HTuple PoseIn, HTuple *PoseOut)
{

  // Local iconic variables

  // Local control variables
  HTuple  NumModels, Rows, Cols, MinMinZ;
  HTuple  BB, Seq, DXMax, DYMax, DZMax, Diameter;
  HTuple  ZAdd, IBB, BB0, BB1, BB2, BB3;
  HTuple  BB4, BB5, X, Y, Z, PoseInter;
  HTuple  HomMat3D, CX, CY, CZ, DR, DC;
  HTuple  MaxDist, HomMat3DRotate, MinImageSize;
  HTuple  Zs, ZDiff, ScaleZ, ZNew;

  //Determine the optimum distance of the object to obtain
  //a reasonable visualization
  //
  NumModels = ObjectModel3DID.TupleLength();
  Rows = HTuple();
  Cols = HTuple();
  MinMinZ = 1e30;
  GetObjectModel3dParams(ObjectModel3DID, "bounding_box1", &BB);
  //Calculate diameter over all objects to be visualized
  Seq = HTuple::TupleGenSequence(0,(BB.TupleLength())-1,6);
  DXMax = (HTuple(BB[Seq+3]).TupleMax())-(HTuple(BB[Seq]).TupleMin());
  DYMax = (HTuple(BB[Seq+4]).TupleMax())-(HTuple(BB[Seq+1]).TupleMin());
  DZMax = (HTuple(BB[Seq+5]).TupleMax())-(HTuple(BB[Seq+2]).TupleMin());
  Diameter = (((DXMax*DXMax)+(DYMax*DYMax))+(DZMax*DZMax)).TupleSqrt();
  if (0 != (((BB.TupleAbs()).TupleSum())==0.0))
  {
    BB.Clear();
    BB.Append(-(HTuple(HTuple::TupleRand(3)*1e-20).TupleAbs()));
    BB.Append(HTuple(HTuple::TupleRand(3)*1e-20).TupleAbs());
  }
  //Allow the visualization of single points or extremely small objects
  ZAdd = 0.0;
  if (0 != ((Diameter.TupleMax())<1e-10))
  {
    ZAdd = 0.01;
  }
  //Set extremely small diameters to 1e-10 to avoid CZ == 0.0, which would lead
  //to projection errors
  if (0 != ((Diameter.TupleMin())<1e-10))
  {
    Diameter = Diameter-(((((Diameter-1e-10).TupleSgn())-1).TupleSgn())*1e-10);
  }
  IBB = HTuple::TupleGenSequence(0,(BB.TupleLength())-1,6);
  BB0 = ((const HTuple&)BB)[IBB];
  BB1 = ((const HTuple&)BB)[IBB+1];
  BB2 = ((const HTuple&)BB)[IBB+2];
  BB3 = ((const HTuple&)BB)[IBB+3];
  BB4 = ((const HTuple&)BB)[IBB+4];
  BB5 = ((const HTuple&)BB)[IBB+5];
  X.Clear();
  X.Append(BB0);
  X.Append(BB3);
  X.Append(BB0);
  X.Append(BB0);
  X.Append(BB3);
  X.Append(BB3);
  X.Append(BB0);
  X.Append(BB3);
  Y.Clear();
  Y.Append(BB1);
  Y.Append(BB1);
  Y.Append(BB4);
  Y.Append(BB1);
  Y.Append(BB4);
  Y.Append(BB1);
  Y.Append(BB4);
  Y.Append(BB4);
  Z.Clear();
  Z.Append(BB2);
  Z.Append(BB2);
  Z.Append(BB2);
  Z.Append(BB5);
  Z.Append(BB2);
  Z.Append(BB5);
  Z.Append(BB5);
  Z.Append(BB5);
  PoseInter = PoseIn.TupleReplace(2,(-(Z.TupleMin()))+(2*(Diameter.TupleMax())));
  PoseToHomMat3d(PoseInter, &HomMat3D);
  //Determine the maximum extention of the projection
  AffineTransPoint3d(HomMat3D, X, Y, Z, &CX, &CY, &CZ);
  Project3dPoint(CX, CY, CZ, CamParam, &Rows, &Cols);
  MinMinZ = CZ.TupleMin();
  DR = Rows-HTuple(CamParam[(CamParam.TupleLength())-3]);
  DC = Cols-HTuple(CamParam[(CamParam.TupleLength())-4]);
  DR = (DR.TupleMax())-(DR.TupleMin());
  DC = (DC.TupleMax())-(DC.TupleMin());
  MaxDist = ((DR*DR)+(DC*DC)).TupleSqrt();
  //
  if (0 != (MaxDist<1e-10))
  {
    //If the object has no extension in the above projection (looking along
    //a line), we determine the extension of the object in a rotated view
    HomMat3dRotateLocal(HomMat3D, HTuple(90).TupleRad(), "x", &HomMat3DRotate);
    AffineTransPoint3d(HomMat3DRotate, X, Y, Z, &CX, &CY, &CZ);
    Project3dPoint(CX, CY, CZ, CamParam, &Rows, &Cols);
    DR = Rows-HTuple(CamParam[(CamParam.TupleLength())-3]);
    DC = Cols-HTuple(CamParam[(CamParam.TupleLength())-4]);
    DR = (DR.TupleMax())-(DR.TupleMin());
    DC = (DC.TupleMax())-(DC.TupleMin());
    MaxDist = (MaxDist.TupleConcat(((DR*DR)+(DC*DC)).TupleSqrt())).TupleMax();
  }
  //
  MinImageSize = (HTuple(CamParam[(CamParam.TupleLength())-2]).TupleConcat(HTuple(CamParam[(CamParam.TupleLength())-1]))).TupleMin();
  //
  Z = ((const HTuple&)PoseInter)[2];
  Zs = MinMinZ;
  ZDiff = Z-Zs;
  ScaleZ = MaxDist/(((0.5*MinImageSize)*ImageCoverage)*2.0);
  ZNew = ((ScaleZ*Zs)+ZDiff)+ZAdd;
  (*PoseOut) = PoseInter.TupleReplace(2,ZNew);
  //
  return;
}

// Chapter: Graphics / Output
// Short Description: Reflect the pose change that was introduced by the user by moving the mouse
void analyze_graph_event (HObject BackgroundImage, HTuple MouseMapping, HTuple Button,
    HTuple Row, HTuple Column, HTuple WindowHandle, HTuple WindowHandleBuffer,
    HTuple VirtualTrackball, HTuple TrackballSize, HTuple SelectedObjectIn,
    HTuple Scene3D, HTuple AlphaOrig, HTuple ObjectModel3DID, HTuple CamParam,
    HTuple Labels, HTuple Title, HTuple Information, HTuple GenParamName,
    HTuple GenParamValue, HTuple PosesIn, HTuple ButtonHoldIn, HTuple TBCenter,
    HTuple TBSize, HTuple WindowCenteredRotationlIn, HTuple MaxNumModels,
    HTuple *PosesOut, HTuple *SelectedObjectOut, HTuple *ButtonHoldOut,
    HTuple *WindowCenteredRotationOut)
{

  // Local iconic variables
  HObject  ImageDump;

  // Local control variables
  HTuple  ExpTmpLocalVar_gIsSinglePose, VisualizeTB;
  HTuple  InvLog2, Seconds, ModelIndex, Exception1;
  HTuple  HomMat3DIdentity, NumModels, Width, Height;
  HTuple  MinImageSize, TrackballRadiusPixel, TrackballCenterRow;
  HTuple  TrackballCenterCol, NumChannels, ColorImage;
  HTuple  BAnd, SensFactor, IsButtonTrans, IsButtonRot;
  HTuple  IsButtonDist, MRow1, MCol1, ButtonLoop;
  HTuple  MRow2, MCol2, PX, PY, PZ, QX1;
  HTuple  QY1, QZ1, QX2, QY2, QZ2, Len;
  HTuple  Dist, Translate, Index, PoseIn, HomMat3DIn;
  HTuple  HomMat3DOut, PoseOut, Indices, Sequence;
  HTuple  Mod, SequenceReal, Sequence2Int, Selected;
  HTuple  InvSelected, Exception, DRow, TranslateZ;
  HTuple  MX1, MY1, MX2, MY2, RelQuaternion;
  HTuple  HomMat3DRotRel, HomMat3DInTmp1, HomMat3DInTmp;
  HTuple  PosesOut2;

  //This procedure reflects
  //- the pose change that was introduced by the user by
  //  moving the mouse
  //- the selection of a single object
  //
  //global tuple gIsSinglePose
  //
  (*ButtonHoldOut) = ButtonHoldIn;
  (*PosesOut) = PosesIn;
  (*SelectedObjectOut) = SelectedObjectIn;
  (*WindowCenteredRotationOut) = WindowCenteredRotationlIn;
  VisualizeTB = ((*SelectedObjectOut).TupleMax())!=0;
  InvLog2 = 1.0/(HTuple(2).TupleLog());
  //
  if (0 != (Button==HTuple(MouseMapping[6])))
  {
    if (0 != (*ButtonHoldOut))
    {
      return;
    }
    //Ctrl (16) + Alt (32) + left mouse button (1) => Toggle rotation center position
    //If WindowCenteredRotation is not 1, set it to 1, otherwise, set it to 2
    CountSeconds(&Seconds);
    if (0 != ((*WindowCenteredRotationOut)==1))
    {
      (*WindowCenteredRotationOut) = 2;
    }
    else
    {
      (*WindowCenteredRotationOut) = 1;
    }
    (*ButtonHoldOut) = 1;
    return;
  }
  if (0 != (HTuple(Button==HTuple(MouseMapping[5])).TupleAnd((ObjectModel3DID.TupleLength())<=MaxNumModels)))
  {
    if (0 != (*ButtonHoldOut))
    {
      return;
    }
    //Ctrl (16) + left mouse button (1) => Select an object
    try
    {
      SetScene3dParam(Scene3D, "object_index_persistence", "true");
      DisplayScene3d(WindowHandleBuffer, Scene3D, 0);
      GetDisplayScene3dInfo(WindowHandleBuffer, Scene3D, Row, Column,
          "object_index", &ModelIndex);
      SetScene3dParam(Scene3D, "object_index_persistence", "false");
    }
    // catch (Exception1)
    catch (HalconCpp::HException &HDevExpDefaultException)
    {
      HDevExpDefaultException.ToHTuple(&Exception1);
      //* NO OpenGL, no selection possible
      return;
    }
    if (0 != (ModelIndex==-1))
    {
      //Background click:
      if (0 != (((*SelectedObjectOut).TupleSum())==((*SelectedObjectOut).TupleLength())))
      {
        //If all objects are already selected, deselect all
        (*SelectedObjectOut) = HTuple(ObjectModel3DID.TupleLength(),0);
      }
      else
      {
        //Otherwise select all
        (*SelectedObjectOut) = HTuple(ObjectModel3DID.TupleLength(),1);
      }
    }
    else
    {
      //Object click:
      (*SelectedObjectOut)[ModelIndex] = HTuple((*SelectedObjectOut)[ModelIndex]).TupleNot();
    }
    (*ButtonHoldOut) = 1;
  }
  else
  {
    //Change the pose
    HomMat3dIdentity(&HomMat3DIdentity);
    NumModels = ObjectModel3DID.TupleLength();
    Width = ((const HTuple&)CamParam)[(CamParam.TupleLength())-2];
    Height = ((const HTuple&)CamParam)[(CamParam.TupleLength())-1];
    MinImageSize = (Width.TupleConcat(Height)).TupleMin();
    TrackballRadiusPixel = (TrackballSize*MinImageSize)/2.0;
    //Set trackball fixed in the center of the window
    TrackballCenterRow = Height/2;
    TrackballCenterCol = Width/2;
    if (0 != ((ObjectModel3DID.TupleLength()) lower sensitivity
    TupleRsh(Button, 5, &BAnd);
    if (0 != (BAnd%2))
    {
      SensFactor = 0.1;
    }
    else
    {
      SensFactor = 1.0;
    }
    IsButtonTrans = HTuple(HTuple(MouseMapping[0])==Button).TupleOr((32+HTuple(MouseMapping[0]))==Button);
    IsButtonRot = HTuple(HTuple(MouseMapping[1])==Button).TupleOr((32+HTuple(MouseMapping[1]))==Button);
    IsButtonDist = HTuple(HTuple(HTuple(HTuple(HTuple(HTuple(MouseMapping[2])==Button).TupleOr((32+HTuple(MouseMapping[2]))==Button)).TupleOr(HTuple(MouseMapping[3])==Button)).TupleOr((32+HTuple(MouseMapping[3]))==Button)).TupleOr(HTuple(MouseMapping[4])==Button)).TupleOr((32+HTuple(MouseMapping[4]))==Button);
    if (0 != IsButtonTrans)
    {
      //Translate in XY-direction
      MRow1 = Row;
      MCol1 = Column;
      while (0 != IsButtonTrans)
      {
        try
        {
          GetMpositionSubPix(WindowHandle, &Row, &Column, &ButtonLoop);
          IsButtonTrans = ButtonLoop==Button;
          MRow2 = MRow1+((Row-MRow1)*SensFactor);
          MCol2 = MCol1+((Column-MCol1)*SensFactor);
          GetLineOfSight(MRow1, MCol1, CamParam, &PX, &PY, &PZ,
              &QX1, &QY1, &QZ1);
          GetLineOfSight(MRow2, MCol2, CamParam, &PX, &PY, &PZ,
              &QX2, &QY2, &QZ2);
          Len = (((QX1*QX1)+(QY1*QY1))+(QZ1*QZ1)).TupleSqrt();
          Dist = (((HTuple(TBCenter[0])*HTuple(TBCenter[0]))+(HTuple(TBCenter[1])*HTuple(TBCenter[1])))+(HTuple(TBCenter[2])*HTuple(TBCenter[2]))).TupleSqrt();
          Translate = ((((QX2-QX1).TupleConcat(QY2-QY1)).TupleConcat(QZ2-QZ1))*Dist)/Len;
          (*PosesOut) = HTuple();
          if (0 != (NumModels<=MaxNumModels))
          {
            {
            HTuple end_val110 = NumModels-1;
            HTuple step_val110 = 1;
            for (Index=0; Index.Continue(end_val110, step_val110); Index += step_val110)
            {
              PoseIn = PosesIn.TupleSelectRange(Index*7,(Index*7)+6);
              if (0 != (HTuple((*SelectedObjectOut)[Index])))
              {
                PoseToHomMat3d(PoseIn, &HomMat3DIn);
                HomMat3dTranslate(HomMat3DIn, HTuple(Translate[0]), HTuple(Translate[1]),
                    HTuple(Translate[2]), &HomMat3DOut);
                HomMat3dToPose(HomMat3DOut, &PoseOut);
                SetScene3dInstancePose(Scene3D, Index, PoseOut);
              }
              else
              {
                PoseOut = PoseIn;
              }
              (*PosesOut) = (*PosesOut).TupleConcat(PoseOut);
            }
            }
          }
          else
          {
            TupleFind((*SelectedObjectOut), 1, &Indices);
            PoseIn = PosesIn.TupleSelectRange(HTuple(Indices[0])*7,(HTuple(Indices[0])*7)+6);
            PoseToHomMat3d(PoseIn, &HomMat3DIn);
            HomMat3dTranslate(HomMat3DIn, HTuple(Translate[0]), HTuple(Translate[1]),
                HTuple(Translate[2]), &HomMat3DOut);
            HomMat3dToPose(HomMat3DOut, &PoseOut);
            Sequence = HTuple::TupleGenSequence(0,(NumModels*7)-1,1);
            TupleMod(Sequence, 7, &Mod);
            SequenceReal = HTuple::TupleGenSequence(0,NumModels-(1.0/7.0),1.0/7.0);
            Sequence2Int = SequenceReal.TupleInt();
            TupleSelect((*SelectedObjectOut), Sequence2Int, &Selected);
            InvSelected = 1-Selected;
            TupleSelect(PoseOut, Mod, &(*PosesOut));
            (*PosesOut) = ((*PosesOut)*Selected)+(PosesIn*InvSelected);
            SetScene3dInstancePose(Scene3D, HTuple::TupleGenSequence(0,NumModels-1,1),
                (*PosesOut));
          }
          dump_image_output(BackgroundImage, WindowHandleBuffer, Scene3D,
              AlphaOrig, ObjectModel3DID, GenParamName, GenParamValue,
              CamParam, (*PosesOut), ColorImage, Title, Information,
              Labels, VisualizeTB, "true", TrackballCenterRow, TrackballCenterCol,
              TBSize, (*SelectedObjectOut), (*WindowCenteredRotationOut)==1,
              TBCenter);
          DumpWindowImage(&ImageDump, WindowHandleBuffer);
          HDevWindowStack::SetActive(WindowHandle);
          if (HDevWindowStack::IsOpen())
            DispObj(ImageDump, HDevWindowStack::GetActive());
          //
          MRow1 = Row;
          MCol1 = Column;
          PosesIn = (*PosesOut);
        }
        // catch (Exception)
        catch (HalconCpp::HException &HDevExpDefaultException)
        {
          HDevExpDefaultException.ToHTuple(&Exception);
          //Keep waiting
        }
      }
    }
    else if (0 != IsButtonDist)
    {
      //Change the Z distance
      MRow1 = Row;
      while (0 != IsButtonDist)
      {
        try
        {
          GetMpositionSubPix(WindowHandle, &Row, &Column, &ButtonLoop);
          IsButtonDist = ButtonLoop==Button;
          MRow2 = Row;
          DRow = MRow2-MRow1;
          Dist = (((HTuple(TBCenter[0])*HTuple(TBCenter[0]))+(HTuple(TBCenter[1])*HTuple(TBCenter[1])))+(HTuple(TBCenter[2])*HTuple(TBCenter[2]))).TupleSqrt();
          TranslateZ = (((-Dist)*DRow)*0.003)*SensFactor;
          TBCenter[2] = HTuple(TBCenter[2])+TranslateZ;
          (*PosesOut) = HTuple();
          if (0 != (NumModels<=MaxNumModels))
          {
            {
            HTuple end_val164 = NumModels-1;
            HTuple step_val164 = 1;
            for (Index=0; Index.Continue(end_val164, step_val164); Index += step_val164)
            {
              PoseIn = PosesIn.TupleSelectRange(Index*7,(Index*7)+6);
              if (0 != (HTuple((*SelectedObjectOut)[Index])))
              {
                //Transform the whole scene or selected object only
                PoseToHomMat3d(PoseIn, &HomMat3DIn);
                HomMat3dTranslate(HomMat3DIn, 0, 0, TranslateZ, &HomMat3DOut);
                HomMat3dToPose(HomMat3DOut, &PoseOut);
                SetScene3dInstancePose(Scene3D, Index, PoseOut);
              }
              else
              {
                PoseOut = PoseIn;
              }
              (*PosesOut) = (*PosesOut).TupleConcat(PoseOut);
            }
            }
          }
          else
          {
            TupleFind((*SelectedObjectOut), 1, &Indices);
            PoseIn = PosesIn.TupleSelectRange(HTuple(Indices[0])*7,(HTuple(Indices[0])*7)+6);
            PoseToHomMat3d(PoseIn, &HomMat3DIn);
            HomMat3dTranslate(HomMat3DIn, 0, 0, TranslateZ, &HomMat3DOut);
            HomMat3dToPose(HomMat3DOut, &PoseOut);
            Sequence = HTuple::TupleGenSequence(0,(NumModels*7)-1,1);
            TupleMod(Sequence, 7, &Mod);
            SequenceReal = HTuple::TupleGenSequence(0,NumModels-(1.0/7.0),1.0/7.0);
            Sequence2Int = SequenceReal.TupleInt();
            TupleSelect((*SelectedObjectOut), Sequence2Int, &Selected);
            InvSelected = 1-Selected;
            TupleSelect(PoseOut, Mod, &(*PosesOut));
            (*PosesOut) = ((*PosesOut)*Selected)+(PosesIn*InvSelected);
            SetScene3dInstancePose(Scene3D, HTuple::TupleGenSequence(0,NumModels-1,1),
                (*PosesOut));
          }
          dump_image_output(BackgroundImage, WindowHandleBuffer, Scene3D,
              AlphaOrig, ObjectModel3DID, GenParamName, GenParamValue,
              CamParam, (*PosesOut), ColorImage, Title, Information,
              Labels, VisualizeTB, "true", TrackballCenterRow, TrackballCenterCol,
              TBSize, (*SelectedObjectOut), (*WindowCenteredRotationOut),
              TBCenter);
          DumpWindowImage(&ImageDump, WindowHandleBuffer);
          HDevWindowStack::SetActive(WindowHandle);
          if (HDevWindowStack::IsOpen())
            DispObj(ImageDump, HDevWindowStack::GetActive());
          //
          MRow1 = Row;
          PosesIn = (*PosesOut);
        }
        // catch (Exception)
        catch (HalconCpp::HException &HDevExpDefaultException)
        {
          HDevExpDefaultException.ToHTuple(&Exception);
          //Keep waiting
        }
      }
    }
    else if (0 != IsButtonRot)
    {
      //Rotate the object
      MRow1 = Row;
      MCol1 = Column;
      while (0 != IsButtonRot)
      {
        try
        {
          GetMpositionSubPix(WindowHandle, &Row, &Column, &ButtonLoop);
          IsButtonRot = ButtonLoop==Button;
          MRow2 = Row;
          MCol2 = Column;
          //Transform the pixel coordinates to relative image coordinates
          MX1 = (TrackballCenterCol-MCol1)/(0.5*MinImageSize);
          MY1 = (TrackballCenterRow-MRow1)/(0.5*MinImageSize);
          MX2 = (TrackballCenterCol-MCol2)/(0.5*MinImageSize);
          MY2 = (TrackballCenterRow-MRow2)/(0.5*MinImageSize);
          //Compute the quaternion rotation that corresponds to the mouse
          //movement
          trackball(MX1, MY1, MX2, MY2, VirtualTrackball, TrackballSize,
              SensFactor, &RelQuaternion);
          //Transform the quaternion to a rotation matrix
          QuatToHomMat3d(RelQuaternion, &HomMat3DRotRel);
          (*PosesOut) = HTuple();
          if (0 != (NumModels<=MaxNumModels))
          {
            {
            HTuple end_val226 = NumModels-1;
            HTuple step_val226 = 1;
            for (Index=0; Index.Continue(end_val226, step_val226); Index += step_val226)
            {
              PoseIn = PosesIn.TupleSelectRange(Index*7,(Index*7)+6);
              if (0 != (HTuple((*SelectedObjectOut)[Index])))
              {
                //Transform the whole scene or selected object only
                PoseToHomMat3d(PoseIn, &HomMat3DIn);
                HomMat3dTranslate(HomMat3DIn, -HTuple(TBCenter[0]), -HTuple(TBCenter[1]),
                    -HTuple(TBCenter[2]), &HomMat3DIn);
                HomMat3dCompose(HomMat3DRotRel, HomMat3DIn, &HomMat3DIn);
                HomMat3dTranslate(HomMat3DIn, HTuple(TBCenter[0]), HTuple(TBCenter[1]),
                    HTuple(TBCenter[2]), &HomMat3DOut);
                HomMat3dToPose(HomMat3DOut, &PoseOut);
                SetScene3dInstancePose(Scene3D, Index, PoseOut);
              }
              else
              {
                PoseOut = PoseIn;
              }
              (*PosesOut) = (*PosesOut).TupleConcat(PoseOut);
            }
            }
          }
          else
          {
            TupleFind((*SelectedObjectOut), 1, &Indices);
            PoseIn = PosesIn.TupleSelectRange(HTuple(Indices[0])*7,(HTuple(Indices[0])*7)+6);
            PoseToHomMat3d(PoseIn, &HomMat3DIn);
            HomMat3dTranslate(HomMat3DIn, -HTuple(TBCenter[0]), -HTuple(TBCenter[1]),
                -HTuple(TBCenter[2]), &HomMat3DInTmp1);
            HomMat3dCompose(HomMat3DRotRel, HomMat3DInTmp1, &HomMat3DInTmp);
            HomMat3dTranslate(HomMat3DInTmp, HTuple(TBCenter[0]), HTuple(TBCenter[1]),
                HTuple(TBCenter[2]), &HomMat3DOut);
            HomMat3dToPose(HomMat3DOut, &PoseOut);
            Sequence = HTuple::TupleGenSequence(0,(NumModels*7)-1,1);
            TupleMod(Sequence, 7, &Mod);
            SequenceReal = HTuple::TupleGenSequence(0,NumModels-(1.0/7.0),1.0/7.0);
            Sequence2Int = SequenceReal.TupleInt();
            TupleSelect((*SelectedObjectOut), Sequence2Int, &Selected);
            InvSelected = 1-Selected;
            TupleSelect(PoseOut, Mod, &(*PosesOut));
            PosesOut2 = ((*PosesOut)*Selected)+(PosesIn*InvSelected);
            (*PosesOut) = PosesOut2;
            SetScene3dInstancePose(Scene3D, HTuple::TupleGenSequence(0,NumModels-1,1),
                (*PosesOut));
          }
          dump_image_output(BackgroundImage, WindowHandleBuffer, Scene3D,
              AlphaOrig, ObjectModel3DID, GenParamName, GenParamValue,
              CamParam, (*PosesOut), ColorImage, Title, Information,
              Labels, VisualizeTB, "true", TrackballCenterRow, TrackballCenterCol,
              TBSize, (*SelectedObjectOut), (*WindowCenteredRotationOut),
              TBCenter);
          DumpWindowImage(&ImageDump, WindowHandleBuffer);
          HDevWindowStack::SetActive(WindowHandle);
          if (HDevWindowStack::IsOpen())
            DispObj(ImageDump, HDevWindowStack::GetActive());
          //
          MRow1 = Row;
          MCol1 = Column;
          PosesIn = (*PosesOut);
        }
        // catch (Exception)
        catch (HalconCpp::HException &HDevExpDefaultException)
        {
          HDevExpDefaultException.ToHTuple(&Exception);
          //Keep waiting
        }
      }
    }
    (*PosesOut) = PosesIn;
  }
  return;
}

// Chapter: Graphics / Output
// Short Description: Project an image point onto the trackball
void project_point_on_trackball (HTuple X, HTuple Y, HTuple VirtualTrackball,
    HTuple TrackballSize, HTuple *V)
{

  // Local iconic variables

  // Local control variables
  HTuple  R, XP, YP, ZP;

  if (0 != (VirtualTrackball==HTuple("shoemake")))
  {
    //Virtual Trackball according to Shoemake
    R = ((X*X)+(Y*Y)).TupleSqrt();
    if (0 != (R<=TrackballSize))
    {
      XP = X;
      YP = Y;
      ZP = ((TrackballSize*TrackballSize)-(R*R)).TupleSqrt();
    }
    else
    {
      XP = (X*TrackballSize)/R;
      YP = (Y*TrackballSize)/R;
      ZP = 0;
    }
  }
  else
  {
    //Virtual Trackball according to Bell
    R = ((X*X)+(Y*Y)).TupleSqrt();
    if (0 != (R<=(TrackballSize*0.70710678)))
    {
      XP = X;
      YP = Y;
      ZP = ((TrackballSize*TrackballSize)-(R*R)).TupleSqrt();
    }
    else
    {
      XP = X;
      YP = Y;
      ZP = ((0.6*TrackballSize)*TrackballSize)/R;
    }
  }
  (*V).Clear();
  (*V).Append(XP);
  (*V).Append(YP);
  (*V).Append(ZP);
  return;
}

// Chapter: Graphics / Text
// Short Description: This procedure writes a text message.
void disp_text_button (HTuple WindowHandle, HTuple String, HTuple CoordSystem,
    HTuple Row, HTuple Column, HTuple TextColor, HTuple ButtonColor)
{

  // Local iconic variables
  HObject  UpperLeft, LowerRight, Rectangle;

  // Local control variables
  HTuple  Red, Green, Blue, Row1Part;
  HTuple  Column1Part, Row2Part, Column2Part, RowWin;
  HTuple  ColumnWin, WidthWin, HeightWin, Exception;
  HTuple  Fac, RGBL, RGB, RGBD, ButtonColorBorderL;
  HTuple  ButtonColorBorderD, MaxAscent, MaxDescent;
  HTuple  MaxWidth, MaxHeight, R1, C1, FactorRow;
  HTuple  FactorColumn, Width, Index, Ascent;
  HTuple  Descent, W, H, FrameHeight, FrameWidth;
  HTuple  R2, C2, ClipRegion, DrawMode, BorderWidth;
  HTuple  CurrentColor;

  //This procedure displays text in a graphics window.
  //
  //Input parameters:
  //WindowHandle: The WindowHandle of the graphics window, where
  //   the message should be displayed
  //String: A tuple of strings containing the text message to be displayed
  //CoordSystem: If set to 'window', the text position is given
  //   with respect to the window coordinate system.
  //   If set to 'image', image coordinates are used.
  //   (This may be useful in zoomed images.)
  //Row: The row coordinate of the desired text position
  //   If set to -1, a default value of 12 is used.
  //Column: The column coordinate of the desired text position
  //   If set to -1, a default value of 12 is used.
  //Color: defines the color of the text as string.
  //   If set to [], '' or 'auto' the currently set color is used.
  //   If a tuple of strings is passed, the colors are used cyclically
  //   for each new textline.
  //ButtonColor: Must be set to a color string (e.g. 'white', '#FF00CC', etc.).
  //             The text is written in a box of that color.
  //
  //prepare window
  GetRgb(WindowHandle, &Red, &Green, &Blue);
  GetPart(WindowHandle, &Row1Part, &Column1Part, &Row2Part, &Column2Part);
  GetWindowExtents(WindowHandle, &RowWin, &ColumnWin, &WidthWin, &HeightWin);
  SetPart(WindowHandle, 0, 0, HeightWin-1, WidthWin-1);
  //
  //default settings
  if (0 != (Row==-1))
  {
    Row = 12;
  }
  if (0 != (Column==-1))
  {
    Column = 12;
  }
  if (0 != (TextColor==HTuple()))
  {
    TextColor = "";
  }
  //
  try
  {
    color_string_to_rgb(ButtonColor, &RGB);
  }
  // catch (Exception)
  catch (HalconCpp::HException &HDevExpDefaultException)
  {
    HDevExpDefaultException.ToHTuple(&Exception);
    Exception = "Wrong value of control parameter ButtonColor (must be a valid color string)";
    throw HalconCpp::HException(Exception);
  }
  Fac = 0.4;
  RGBL = RGB+((((255.0-RGB)*Fac)+0.5).TupleInt());
  RGBD = RGB-(((RGB*Fac)+0.5).TupleInt());
  ButtonColorBorderL = "#"+((""+(RGBL.TupleString("02x"))).TupleSum());
  ButtonColorBorderD = "#"+((""+(RGBD.TupleString("02x"))).TupleSum());
  //
  String = ((""+String)+"").TupleSplit("\n");
  //
  //Estimate extentions of text depending on font size.
  GetFontExtents(WindowHandle, &MaxAscent, &MaxDescent, &MaxWidth, &MaxHeight);
  if (0 != (CoordSystem==HTuple("window")))
  {
    R1 = Row;
    C1 = Column;
  }
  else
  {
    //transform image to window coordinates
    FactorRow = (1.*HeightWin)/((Row2Part-Row1Part)+1);
    FactorColumn = (1.*WidthWin)/((Column2Part-Column1Part)+1);
    R1 = ((Row-Row1Part)+0.5)*FactorRow;
    C1 = ((Column-Column1Part)+0.5)*FactorColumn;
  }
  //
  //display text box depending on text size
  //
  //calculate box extents
  String = (" "+String)+" ";
  Width = HTuple();
  {
  HTuple end_val70 = (String.TupleLength())-1;
  HTuple step_val70 = 1;
  for (Index=0; Index.Continue(end_val70, step_val70); Index += step_val70)
  {
    GetStringExtents(WindowHandle, HTuple(String[Index]), &Ascent, &Descent,
        &W, &H);
    Width = Width.TupleConcat(W);
  }
  }
  FrameHeight = MaxHeight*(String.TupleLength());
  FrameWidth = (HTuple(0).TupleConcat(Width)).TupleMax();
  R2 = R1+FrameHeight;
  C2 = C1+FrameWidth;
  //display rectangles
  GetSystem("clip_region", &ClipRegion);
  SetSystem("clip_region", "false");
  GetDraw(WindowHandle, &DrawMode);
  SetDraw(WindowHandle, "fill");
  BorderWidth = 2;
  GenRegionPolygonFilled(&UpperLeft, ((((R1-BorderWidth).TupleConcat(R1-BorderWidth)).TupleConcat(R1)).TupleConcat(R2)).TupleConcat(R2+BorderWidth),
      ((((C1-BorderWidth).TupleConcat(C2+BorderWidth)).TupleConcat(C2)).TupleConcat(C1)).TupleConcat(C1-BorderWidth));
  GenRegionPolygonFilled(&LowerRight, ((((R2+BorderWidth).TupleConcat(R1-BorderWidth)).TupleConcat(R1)).TupleConcat(R2)).TupleConcat(R2+BorderWidth),
      ((((C2+BorderWidth).TupleConcat(C2+BorderWidth)).TupleConcat(C2)).TupleConcat(C1)).TupleConcat(C1-BorderWidth));
  GenRectangle1(&Rectangle, R1, C1, R2, C2);
  SetColor(WindowHandle, ButtonColorBorderL);
  DispObj(UpperLeft, WindowHandle);
  SetColor(WindowHandle, ButtonColorBorderD);
  DispObj(LowerRight, WindowHandle);
  SetColor(WindowHandle, ButtonColor);
  DispObj(Rectangle, WindowHandle);
  SetDraw(WindowHandle, DrawMode);
  SetSystem("clip_region", ClipRegion);
  //Write text.
  {
  HTuple end_val96 = (String.TupleLength())-1;
  HTuple step_val96 = 1;
  for (Index=0; Index.Continue(end_val96, step_val96); Index += step_val96)
  {
    CurrentColor = ((const HTuple&)TextColor)[Index%(TextColor.TupleLength())];
    if (0 != (HTuple(CurrentColor!=HTuple("")).TupleAnd(CurrentColor!=HTuple("auto"))))
    {
      SetColor(WindowHandle, CurrentColor);
    }
    else
    {
      SetRgb(WindowHandle, Red, Green, Blue);
    }
    Row = R1+(MaxHeight*Index);
    SetTposition(WindowHandle, Row, C1);
    WriteString(WindowHandle, HTuple(String[Index]));
  }
  }
  //reset changed window settings
  SetRgb(WindowHandle, Red, Green, Blue);
  SetPart(WindowHandle, Row1Part, Column1Part, Row2Part, Column2Part);
  return;
}

// Chapter: Graphics / Output
// Short Description: Renders 3d object models in a buffer window.
void dump_image_output (HObject BackgroundImage, HTuple WindowHandleBuffer,
    HTuple Scene3D, HTuple AlphaOrig, HTuple ObjectModel3DID, HTuple GenParamName,
    HTuple GenParamValue, HTuple CamParam, HTuple Poses, HTuple ColorImage,
    HTuple Title, HTuple Information, HTuple Labels, HTuple VisualizeTrackball,
    HTuple DisplayContinueButton, HTuple TrackballCenterRow, HTuple TrackballCenterCol,
    HTuple TrackballRadiusPixel, HTuple SelectedObject, HTuple VisualizeRotationCenter,
    HTuple RotationCenter)
{

  // Local iconic variables
  HObject  ModelContours, Image, TrackballContour;
  HObject  CrossRotCenter;

  // Local control variables
  HTuple  ExpTmpLocalVar_gUsesOpenGL, Exception;
  HTuple  Index, Position, PosIdx, Substrings;
  HTuple  I, HasExtended, ExtendedAttributeNames;
  HTuple  Matches, Exception1, DeselectedIdx, DeselectedName;
  HTuple  DeselectedValue, Pose, HomMat3D, Center;
  HTuple  CenterCamX, CenterCamY, CenterCamZ, CenterRow;
  HTuple  CenterCol, Label, Ascent, Descent, TextWidth;
  HTuple  TextHeight, RotCenterRow, RotCenterCol;
  HTuple  Orientation, Colors;

  //global tuple gAlphaDeselected
  //global tuple gTerminationButtonLabel
  //global tuple gDispObjOffset
  //global tuple gLabelsDecor
  //global tuple gUsesOpenGL
  //
  //Display background image
  ClearWindow(WindowHandleBuffer);
  if (0 != ColorImage)
  {
    DispColor(BackgroundImage, WindowHandleBuffer);
  }
  else
  {
    DispImage(BackgroundImage, WindowHandleBuffer);
  }
  //
  //Display objects
  if (0 != ((SelectedObject.TupleSum())==(SelectedObject.TupleLength())))
  {
    if (0 != (ExpGetGlobalVar_gUsesOpenGL()==HTuple("true")))
    {
      try
      {
        DisplayScene3d(WindowHandleBuffer, Scene3D, 0);
      }
      // catch (Exception)
      catch (HalconCpp::HException &HDevExpDefaultException)
      {
        HDevExpDefaultException.ToHTuple(&Exception);
        if (0 != (HTuple(HTuple(HTuple(HTuple(Exception[0])==1306).TupleOr(HTuple(Exception[0])==1305)).TupleOr(HTuple(Exception[0])==1406)).TupleOr(HTuple(Exception[0])==1405)))
        {
          if (0 != ((GenParamName.TupleLength())==(GenParamValue.TupleLength())))
          {
            //This case means we have a Parameter with structure parameter_x with x > |ObjectModel3DID|-1
            {
            HTuple end_val23 = (2*(ObjectModel3DID.TupleLength()))+1;
            HTuple step_val23 = 1;
            for (Index=ObjectModel3DID.TupleLength(); Index.Continue(end_val23, step_val23); Index += step_val23)
            {
              TupleStrstr(GenParamName, ""+Index, &Position);
              {
              HTuple end_val25 = (Position.TupleLength())-1;
              HTuple step_val25 = 1;
              for (PosIdx=0; PosIdx.Continue(end_val25, step_val25); PosIdx += step_val25)
              {
                if (0 != (HTuple(Position[PosIdx])!=-1))
                {
                  throw HalconCpp::HException((("One of the parameters is refferring to a non-existing object model 3D:\n"+HTuple(GenParamName[PosIdx]))+" -> ")+HTuple(GenParamValue[PosIdx]));
                }
              }
              }
            }
            }
            //Test for non-existing extended attributes:
            TupleStrstr(GenParamName, "intensity", &Position);
            {
            HTuple end_val33 = (Position.TupleLength())-1;
            HTuple step_val33 = 1;
            for (PosIdx=0; PosIdx.Continue(end_val33, step_val33); PosIdx += step_val33)
            {
              if (0 != (HTuple(Position[PosIdx])!=-1))
              {
                TupleSplit(HTuple(GenParamName[PosIdx]), "_", &Substrings);
                if (0 != (HTuple((Substrings.TupleLength())>1).TupleAnd(HTuple(Substrings[1]).TupleIsNumber())))
                {
                  I = HTuple(Substrings[1]).TupleNumber();
                  GetObjectModel3dParams(HTuple(ObjectModel3DID[I]), "has_extended_attribute",
                      &HasExtended);
                  if (0 != HasExtended)
                  {
                    GetObjectModel3dParams(HTuple(ObjectModel3DID[I]), "extended_attribute_names",
                        &ExtendedAttributeNames);
                    TupleFind(ExtendedAttributeNames, HTuple(GenParamValue[PosIdx]),
                        &Matches);
                  }
                  if (0 != (HTuple(HasExtended.TupleNot()).TupleOr(HTuple(Matches==-1).TupleOr((Matches.TupleLength())==0))))
                  {
                    throw HalconCpp::HException((((("One of the parameters is refferring to an extended attribute that is not contained in the object model 3d with the handle "+HTuple(ObjectModel3DID[I]))+":\n")+HTuple(GenParamName[PosIdx]))+" -> ")+HTuple(GenParamValue[PosIdx]));
                  }
                }
                else
                {
                  {
                  HTuple end_val47 = (ObjectModel3DID.TupleLength())-1;
                  HTuple step_val47 = 1;
                  for (I=0; I.Continue(end_val47, step_val47); I += step_val47)
                  {
                    GetObjectModel3dParams(HTuple(ObjectModel3DID[I]), "extended_attribute_names",
                        &ExtendedAttributeNames);
                    TupleFind(ExtendedAttributeNames, HTuple(GenParamValue[PosIdx]),
                        &Matches);
                    if (0 != (HTuple(Matches==-1).TupleOr((Matches.TupleLength())==0)))
                    {
                      throw HalconCpp::HException((("One of the parameters is refferring to an extended attribute that is not contained in all object models:\n"+HTuple(GenParamName[PosIdx]))+" -> ")+HTuple(GenParamValue[PosIdx]));
                    }
                  }
                  }
                }
              }
            }
            }
            //
            throw HalconCpp::HException((HTuple("Wrong generic parameters for display\n")+"Wrong Values are:\n")+((((("    "+((GenParamName+" -> ")+GenParamValue))+"\n").TupleSum())+"Exeption was:\n    ")+HTuple(Exception[2])));
          }
          else
          {
            throw HalconCpp::HException(Exception);
          }
        }
        else if (0 != (HTuple(HTuple(HTuple(Exception[0])==5185).TupleOr(HTuple(Exception[0])==5188)).TupleOr(HTuple(Exception[0])==5187)))
        {
          ExpTmpLocalVar_gUsesOpenGL = "false";
          ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
        }
        else
        {
          throw HalconCpp::HException(Exception);
        }
      }
    }
    if (0 != (ExpGetGlobalVar_gUsesOpenGL()==HTuple("false")))
    {
      //* NO OpenGL, use fallback
      disp_object_model_no_opengl(&ModelContours, ObjectModel3DID, GenParamName,
          GenParamValue, WindowHandleBuffer, CamParam, Poses);
    }
  }
  else
  {
    {
    HTuple end_val74 = (AlphaOrig.TupleLength())-1;
    HTuple step_val74 = 1;
    for (Index=0; Index.Continue(end_val74, step_val74); Index += step_val74)
    {
      if (0 != (HTuple(SelectedObject[Index])==1))
      {
        SetScene3dInstanceParam(Scene3D, Index, "alpha", HTuple(AlphaOrig[Index]));
      }
      else
      {
        SetScene3dInstanceParam(Scene3D, Index, "alpha", ExpGetGlobalVar_gAlphaDeselected());
      }
    }
    }
    try
    {
      if (0 != (ExpGetGlobalVar_gUsesOpenGL()==HTuple("false")))
      {
        throw HalconCpp::HException(HTuple());
      }
      DisplayScene3d(WindowHandleBuffer, Scene3D, 0);
    }
    // catch (Exception1)
    catch (HalconCpp::HException &HDevExpDefaultException)
    {
      HDevExpDefaultException.ToHTuple(&Exception1);
      //* NO OpenGL, use fallback
      DeselectedIdx = SelectedObject.TupleFind(0);
      if (0 != (DeselectedIdx!=-1))
      {
        DeselectedName = "color_"+DeselectedIdx;
        DeselectedValue = HTuple(DeselectedName.TupleLength(),"gray");
      }
      disp_object_model_no_opengl(&ModelContours, ObjectModel3DID, GenParamName.TupleConcat(DeselectedName),
          GenParamValue.TupleConcat(DeselectedValue), WindowHandleBuffer,
          CamParam, Poses);
    }
    {
    HTuple end_val95 = (AlphaOrig.TupleLength())-1;
    HTuple step_val95 = 1;
    for (Index=0; Index.Continue(end_val95, step_val95); Index += step_val95)
    {
      SetScene3dInstanceParam(Scene3D, Index, "alpha", HTuple(AlphaOrig[Index]));
    }
    }
  }
  DumpWindowImage(&Image, WindowHandleBuffer);
  //
  //Display labels
  if (0 != (Labels!=0))
  {
    SetColor(WindowHandleBuffer, HTuple(ExpGetGlobalVar_gLabelsDecor()[0]));
    {
    HTuple end_val104 = (ObjectModel3DID.TupleLength())-1;
    HTuple step_val104 = 1;
    for (Index=0; Index.Continue(end_val104, step_val104); Index += step_val104)
    {
      //Project the center point of the current model
      Pose = Poses.TupleSelectRange(Index*7,(Index*7)+6);
      PoseToHomMat3d(Pose, &HomMat3D);
      GetObjectModel3dParams(HTuple(ObjectModel3DID[Index]), "center", &Center);
      AffineTransPoint3d(HomMat3D, HTuple(Center[0]), HTuple(Center[1]),
          HTuple(Center[2]), &CenterCamX, &CenterCamY, &CenterCamZ);
      Project3dPoint(CenterCamX, CenterCamY, CenterCamZ, CamParam, &CenterRow,
          &CenterCol);
      Label = ((const HTuple&)Labels)[Index];
      if (0 != (Label!=HTuple("")))
      {
        GetStringExtents(WindowHandleBuffer, Label, &Ascent, &Descent,
            &TextWidth, &TextHeight);
        disp_message(WindowHandleBuffer, Label, "window", (CenterRow-(TextHeight/2))+HTuple(ExpGetGlobalVar_gDispObjOffset()[0]),
            (CenterCol-(TextWidth/2))+HTuple(ExpGetGlobalVar_gDispObjOffset()[1]),
            HTuple(), HTuple(ExpGetGlobalVar_gLabelsDecor()[1]));
      }
    }
    }
  }
  //
  //Visualize the trackball if desired
  if (0 != VisualizeTrackball)
  {
    SetLineWidth(WindowHandleBuffer, 1);
    GenEllipseContourXld(&TrackballContour, TrackballCenterRow, TrackballCenterCol,
        0, TrackballRadiusPixel, TrackballRadiusPixel, 0, 6.28318, "positive",
        1.5);
    SetColor(WindowHandleBuffer, "dim gray");
    DispXld(TrackballContour, WindowHandleBuffer);
  }
  //
  //Visualize the rotation center if desired
  if (0 != (HTuple(VisualizeRotationCenter!=0).TupleAnd((RotationCenter.TupleLength())==3)))
  {
    if (0 != (HTuple(RotationCenter[2])<1e-10))
    {
      RotationCenter[2] = 1e-10;
    }
    Project3dPoint(HTuple(RotationCenter[0]), HTuple(RotationCenter[1]), HTuple(RotationCenter[2]),
        CamParam, &RotCenterRow, &RotCenterCol);
    Orientation = HTuple(90).TupleRad();
    if (0 != (VisualizeRotationCenter==1))
    {
      Orientation = HTuple(45).TupleRad();
    }
    GenCrossContourXld(&CrossRotCenter, RotCenterRow, RotCenterCol, TrackballRadiusPixel/25.0,
        Orientation);
    SetLineWidth(WindowHandleBuffer, 3);
    QueryColor(WindowHandleBuffer, &Colors);
    SetColor(WindowHandleBuffer, "light gray");
    DispXld(CrossRotCenter, WindowHandleBuffer);
    SetLineWidth(WindowHandleBuffer, 1);
    SetColor(WindowHandleBuffer, "dim gray");
    DispXld(CrossRotCenter, WindowHandleBuffer);
  }
  //
  //Display title
  disp_title_and_information(WindowHandleBuffer, Title, Information);
  //
  //Display the 'Exit' button
  if (0 != (DisplayContinueButton==HTuple("true")))
  {
    disp_continue_button(WindowHandleBuffer);
  }
  //
  return;
}

// Chapter: Graphics / Output
// Short Description: Get the center of the virtual trackback that is used to move the camera.
void get_trackball_center (HTuple SelectedObject, HTuple TrackballRadiusPixel,
    HTuple ObjectModel3D, HTuple Poses, HTuple *TBCenter, HTuple *TBSize)
{

  // Local iconic variables

  // Local control variables
  HTuple  NumModels, Centers, Diameter;
  HTuple  MD, Weight, SumW, Index, ObjectModel3DIDSelected;
  HTuple  PoseSelected, HomMat3D, TBCenterCamX, TBCenterCamY;
  HTuple  TBCenterCamZ, InvSum;

  NumModels = ObjectModel3D.TupleLength();
  (*TBCenter)[0] = 0;
  (*TBCenter)[1] = 0;
  (*TBCenter)[2] = 0;
  GetObjectModel3dParams(ObjectModel3D, "center", &Centers);
  GetObjectModel3dParams(ObjectModel3D, "diameter_axis_aligned_bounding_box",
      &Diameter);
  //Normalize Diameter to use it as weights for a weighted mean of the individual centers
  MD = Diameter.TupleMean();
  if (0 != (MD>1e-10))
  {
    Weight = Diameter/MD;
  }
  else
  {
    Weight = Diameter;
  }
  SumW = (Weight.TupleSelectMask((SelectedObject.TupleSgn()).TupleAbs())).TupleSum();
  if (0 != (SumW<1e-10))
  {
    Weight = HTuple(Weight.TupleLength(),1.0);
    SumW = (Weight.TupleSelectMask((SelectedObject.TupleSgn()).TupleAbs())).TupleSum();
  }
  {
  HTuple end_val18 = NumModels-1;
  HTuple step_val18 = 1;
  for (Index=0; Index.Continue(end_val18, step_val18); Index += step_val18)
  {
    if (0 != (HTuple(SelectedObject[Index])))
    {
      ObjectModel3DIDSelected = ((const HTuple&)ObjectModel3D)[Index];
      PoseSelected = Poses.TupleSelectRange(Index*7,(Index*7)+6);
      PoseToHomMat3d(PoseSelected, &HomMat3D);
      AffineTransPoint3d(HomMat3D, HTuple(Centers[(Index*3)+0]), HTuple(Centers[(Index*3)+1]),
          HTuple(Centers[(Index*3)+2]), &TBCenterCamX, &TBCenterCamY,
          &TBCenterCamZ);
      (*TBCenter)[0] = HTuple((*TBCenter)[0])+(TBCenterCamX*HTuple(Weight[Index]));
      (*TBCenter)[1] = HTuple((*TBCenter)[1])+(TBCenterCamY*HTuple(Weight[Index]));
      (*TBCenter)[2] = HTuple((*TBCenter)[2])+(TBCenterCamZ*HTuple(Weight[Index]));
    }
  }
  }
  if (0 != ((SelectedObject.TupleMax())!=0))
  {
    InvSum = 1.0/SumW;
    (*TBCenter)[0] = HTuple((*TBCenter)[0])*InvSum;
    (*TBCenter)[1] = HTuple((*TBCenter)[1])*InvSum;
    (*TBCenter)[2] = HTuple((*TBCenter)[2])*InvSum;
    (*TBSize) = (0.5+((0.5*(SelectedObject.TupleSum()))/NumModels))*TrackballRadiusPixel;
  }
  else
  {
    (*TBCenter) = HTuple();
    (*TBSize) = 0;
  }
  return;
}

// Chapter: Tuple / Arithmetic
// Short Description: Calculates the cross product of two vectors of length 3.
void tuple_vector_cross_product (HTuple V1, HTuple V2, HTuple *VC)
{

  // Local iconic variables

  //The caller must ensure that the length of both input vectors is 3
  (*VC) = (HTuple(V1[1])*HTuple(V2[2]))-(HTuple(V1[2])*HTuple(V2[1]));
  (*VC) = (*VC).TupleConcat((HTuple(V1[2])*HTuple(V2[0]))-(HTuple(V1[0])*HTuple(V2[2])));
  (*VC) = (*VC).TupleConcat((HTuple(V1[0])*HTuple(V2[1]))-(HTuple(V1[1])*HTuple(V2[0])));
  return;
}

// Chapter: Graphics / Output
// Short Description: Compute the 3d rotation from the mose movement
void trackball (HTuple MX1, HTuple MY1, HTuple MX2, HTuple MY2, HTuple VirtualTrackball,
    HTuple TrackballSize, HTuple SensFactor, HTuple *QuatRotation)
{

  // Local iconic variables

  // Local control variables
  HTuple  D, P2, P1, T, RotAngle;
  HTuple  Len, RotAxis;

  //Compute the 3d rotation from the mouse movement
  //
  if (0 != (HTuple(MX1==MX2).TupleAnd(MY1==MY2)))
  {
    (*QuatRotation).Clear();
    (*QuatRotation)[0] = 1;
    (*QuatRotation)[1] = 0;
    (*QuatRotation)[2] = 0;
    (*QuatRotation)[3] = 0;
    return;
  }
  //Project the image point onto the trackball
  project_point_on_trackball(MX1, MY1, VirtualTrackball, TrackballSize,
      &P1);
  project_point_on_trackball(MX2, MY2, VirtualTrackball, TrackballSize,
      &P2);
  //The cross product of the projected points defines the rotation axis
  tuple_vector_cross_product(P1, P2, &RotAxis);
  //Compute the rotation angle
  D = P2-P1;
  T = (((D*D).TupleSum()).TupleSqrt())/(2.0*TrackballSize);
  if (0 != (T>1.0))
  {
    T = 1.0;
  }
  if (0 != (T<-1.0))
  {
    T = -1.0;
  }
  RotAngle = (2.0*(T.TupleAsin()))*SensFactor;
  Len = ((RotAxis*RotAxis).TupleSum()).TupleSqrt();
  if (0 != (Len>0.0))
  {
    RotAxis = RotAxis/Len;
  }
  AxisAngleToQuat(HTuple(RotAxis[0]), HTuple(RotAxis[1]), HTuple(RotAxis[2]),
      RotAngle, &(*QuatRotation));
  return;
}

// Chapter: Graphics / Output
// Short Description: Get string extends of several lines.
void max_line_width (HTuple WindowHandle, HTuple Lines, HTuple *MaxWidth)
{

  // Local iconic variables

  // Local control variables
  HTuple  Index, Ascent, Descent, LineWidth;
  HTuple  LineHeight;

  (*MaxWidth) = 0;
  {
  HTuple end_val1 = (Lines.TupleLength())-1;
  HTuple step_val1 = 1;
  for (Index=0; Index.Continue(end_val1, step_val1); Index += step_val1)
  {
    GetStringExtents(WindowHandle, HTuple(Lines[Index]), &Ascent, &Descent,
        &LineWidth, &LineHeight);
    (*MaxWidth) = (LineWidth.TupleConcat((*MaxWidth))).TupleMax();
  }
  }
  return;
}

// Chapter: Graphics / Output
// Short Description: Compute the center of all given 3D object models.
void get_object_models_center (HTuple ObjectModel3DID, HTuple *Center)
{

  // Local iconic variables

  // Local control variables
  HTuple  Diameter, MD, Weight, SumW;
  HTuple  Index, ObjectModel3DIDSelected, C, InvSum;

  //Compute the mean of all model centers (weighted by the diameter of the object models)
  if (0 != ((ObjectModel3DID.TupleLength())>0))
  {
    GetObjectModel3dParams(ObjectModel3DID, "diameter_axis_aligned_bounding_box",
        &Diameter);
    //Normalize Diameter to use it as weights for a weighted mean of the individual centers
    MD = Diameter.TupleMean();
    if (0 != (MD>1e-10))
    {
      Weight = Diameter/MD;
    }
    else
    {
      Weight = Diameter;
    }
    SumW = Weight.TupleSum();
    if (0 != (SumW<1e-10))
    {
      Weight = HTuple(Weight.TupleLength(),1.0);
      SumW = Weight.TupleSum();
    }
    (*Center).Clear();
    (*Center)[0] = 0;
    (*Center)[1] = 0;
    (*Center)[2] = 0;
    {
    HTuple end_val16 = (ObjectModel3DID.TupleLength())-1;
    HTuple step_val16 = 1;
    for (Index=0; Index.Continue(end_val16, step_val16); Index += step_val16)
    {
      ObjectModel3DIDSelected = ((const HTuple&)ObjectModel3DID)[Index];
      GetObjectModel3dParams(ObjectModel3DIDSelected, "center", &C);
      (*Center)[0] = HTuple((*Center)[0])+(HTuple(C[0])*HTuple(Weight[Index]));
      (*Center)[1] = HTuple((*Center)[1])+(HTuple(C[1])*HTuple(Weight[Index]));
      (*Center)[2] = HTuple((*Center)[2])+(HTuple(C[2])*HTuple(Weight[Index]));
    }
    }
    InvSum = 1.0/SumW;
    (*Center)[0] = HTuple((*Center)[0])*InvSum;
    (*Center)[1] = HTuple((*Center)[1])*InvSum;
    (*Center)[2] = HTuple((*Center)[2])*InvSum;
  }
  else
  {
    (*Center) = HTuple();
  }
  return;
}

// Chapter: Graphics / Output
// Short Description: Displays a continue button.
void disp_continue_button (HTuple WindowHandle)
{

  // Local iconic variables

  // Local control variables
  HTuple  ContinueMessage, Exception, Row;
  HTuple  Column, Width, Height, Ascent, Descent;
  HTuple  TextWidth, TextHeight;

  //This procedure displays a 'Continue' text button
  //in the lower right corner of the screen.
  //It uses the procedure disp_message.
  //
  //Input parameters:
  //WindowHandle: The window, where the text shall be displayed
  //
  //Use the continue message set in the global variable gTerminationButtonLabel.
  //If this variable is not defined, set a standard text instead.
  //global tuple gTerminationButtonLabel
  try
  {
    ContinueMessage = ExpGetGlobalVar_gTerminationButtonLabel();
  }
  // catch (Exception)
  catch (HalconCpp::HException &HDevExpDefaultException)
  {
    HDevExpDefaultException.ToHTuple(&Exception);
    ContinueMessage = "Continue";
  }
  //Display the continue button
  GetWindowExtents(WindowHandle, &Row, &Column, &Width, &Height);
  GetStringExtents(WindowHandle, (" "+ContinueMessage)+" ", &Ascent, &Descent,
      &TextWidth, &TextHeight);
  disp_text_button(WindowHandle, ContinueMessage, "window", (Height-TextHeight)-12,
      (Width-TextWidth)-12, "black", "#f28f26");
  return;
}

// Chapter: Graphics / Parameters
void color_string_to_rgb (HTuple Color, HTuple *RGB)
{

  // Local iconic variables
  HObject  Rectangle, Image;

  // Local control variables
  HTuple  WindowHandleBuffer, Exception;

  OpenWindow(0, 0, 1, 1, 0, "buffer", "", &WindowHandleBuffer);
  SetPart(WindowHandleBuffer, 0, 0, -1, -1);
  GenRectangle1(&Rectangle, 0, 0, 0, 0);
  try
  {
    SetColor(WindowHandleBuffer, Color);
  }
  // catch (Exception)
  catch (HalconCpp::HException &HDevExpDefaultException)
  {
    HDevExpDefaultException.ToHTuple(&Exception);
    Exception = "Wrong value of control parameter Color (must be a valid color string)";
    throw HalconCpp::HException(Exception);
  }
  DispObj(Rectangle, WindowHandleBuffer);
  DumpWindowImage(&Image, WindowHandleBuffer);
  CloseWindow(WindowHandleBuffer);
  GetGrayval(Image, 0, 0, &(*RGB));
  (*RGB) += ((HTuple(0).Append(0)).Append(0));
  return;
}

// Chapter: Graphics / Output
// Short Description: Get the center of the virtual trackback that is used to move the camera (version for inspection_mode = 'surface').
void get_trackball_center_fixed (HTuple SelectedObject, HTuple TrackballCenterRow,
    HTuple TrackballCenterCol, HTuple TrackballRadiusPixel, HTuple Scene3D,
    HTuple ObjectModel3DID, HTuple Poses, HTuple WindowHandleBuffer, HTuple CamParam,
    HTuple GenParamName, HTuple GenParamValue, HTuple *TBCenter, HTuple *TBSize)
{

  // Local iconic variables
  HObject  RegionCenter, DistanceImage, Domain;

  // Local control variables
  HTuple  NumModels, Width, Height, SelectPose;
  HTuple  Index1, Rows, Columns, Grayval, IndicesG;
  HTuple  Value, Pos;

  //Determine the trackball center for the fixed trackball
  NumModels = ObjectModel3DID.TupleLength();
  Width = ((const HTuple&)CamParam)[(CamParam.TupleLength())-2];
  Height = ((const HTuple&)CamParam)[(CamParam.TupleLength())-1];
  //
  //Project the selected objects
  SelectPose = HTuple();
  {
  HTuple end_val7 = (SelectedObject.TupleLength())-1;
  HTuple step_val7 = 1;
  for (Index1=0; Index1.Continue(end_val7, step_val7); Index1 += step_val7)
  {
    SelectPose = SelectPose.TupleConcat(HTuple(7,HTuple(SelectedObject[Index1])));
    if (0 != (HTuple(SelectedObject[Index1])==0))
    {
      SetScene3dInstanceParam(Scene3D, Index1, "visible", "false");
    }
  }
  }
  SetScene3dParam(Scene3D, "depth_persistence", "true");
  DisplayScene3d(WindowHandleBuffer, Scene3D, 0);
  SetScene3dParam(Scene3D, "visible", "true");
  //
  //determine the depth of the object point that appears closest to the trackball
  //center
  GenRegionPoints(&RegionCenter, TrackballCenterRow, TrackballCenterCol);
  DistanceTransform(RegionCenter, &DistanceImage, "chamfer-3-4-unnormalized",
      "false", Width, Height);
  GetDomain(DistanceImage, &Domain);
  GetRegionPoints(Domain, &Rows, &Columns);
  GetGrayval(DistanceImage, Rows, Columns, &Grayval);
  TupleSortIndex(Grayval, &IndicesG);
  GetDisplayScene3dInfo(WindowHandleBuffer, Scene3D, Rows.TupleSelect(IndicesG),
      Columns.TupleSelect(IndicesG), "depth", &Value);
  TupleFind(Value.TupleSgn(), 1, &Pos);
  //
  SetScene3dParam(Scene3D, "depth_persistence", "false");
  //
  //
  //set TBCenter
  if (0 != (Pos!=-1))
  {
    //if the object is visible in the image
    (*TBCenter).Clear();
    (*TBCenter)[0] = 0;
    (*TBCenter)[1] = 0;
    (*TBCenter).Append(HTuple(Value[HTuple(Pos[0])]));
  }
  else
  {
    //if the object is not visible in the image, set the z coordinate to -1
    //to indicate, the the previous z value should be used instead
    (*TBCenter).Clear();
    (*TBCenter)[0] = 0;
    (*TBCenter)[1] = 0;
    (*TBCenter)[2] = -1;
  }
  //
  if (0 != ((SelectedObject.TupleMax())!=0))
  {
    (*TBSize) = (0.5+((0.5*(SelectedObject.TupleSum()))/NumModels))*TrackballRadiusPixel;
  }
  else
  {
    (*TBCenter) = HTuple();
    (*TBSize) = 0;
  }
  return;
}

void action(long win,int  width,int height,HTuple ObjectModel3D)
{

  // Local iconic variables
  HObject  EmptyObject, Image;

  // Local control variables
  HTuple ImagePath, WindowHandle;
  HTuple SurfaceModelID, PoseOut;
  HTuple fartherWid = win;



  dev_update_off();
  GenEmptyObj(&EmptyObject);
  ImagePath = "time_of_flight/";
  if (HDevWindowStack::IsOpen())
    CloseWindow(HDevWindowStack::Pop());
  ReadImage(&Image, ImagePath+"engine_cover_xyz_01");
 // dev_open_window_fit_image(Image, 0, 0, -1, -1,&WindowHandle, fartherWid);
 // OpenWindow(10,10, width-40, height-40, fartherWid, "visible", "",&WindowHandle);

  SetPart(WindowHandle, 10,10, width-40, height-40);
  set_display_font(WindowHandle, 14, "mono", "true", "false");
  qDebug()<<"33";

  CreateSurfaceModel(ObjectModel3D, 0.03, HTuple(), HTuple(), &SurfaceModelID);
  qDebug()<<"44";
  visualize_object_model_3d(WindowHandle, ObjectModel3D, HTuple(), HTuple(),
      HTuple(), HTuple(), HTuple(), HTuple(), HTuple(), &PoseOut);
  ClearObjectModel3d(ObjectModel3D);

}


void LoadGrabParameters(int nIndex,double &OffsetRow,double & OffsetColumn,double & TPhi,double &TLength1,
                        double & TLength2,int & Modelmode)
{

}

void autogetFileNameCalib(int CalibNumber,HTuple &FilenameCalib,QString &path)
{

}
void autogetFileNameModel(int ModelNumber,HTuple &FileNameModel)
{
}

void ReadSelf3DPose (HTuple &Pose1, HTuple &Pose2, HTuple &Pose3, HTuple &Pose4)
{

  // Local iconic variables

  // Local control variables
  HTuple  APose1, APose2, APose3, APose4;
  /*
  ReadPose("./data/PublicPose/Pose1.dat", &(*Pose1));
  ReadPose("./data/PublicPose/Pose2.dat", &(*Pose2));
  ReadPose("./data/PublicPose/Pose3.dat", &(*Pose3));
  ReadPose("./data/PublicPose/Pose4.dat", &(*Pose4));
  */

  APose1.Clear();
  APose1[0] = 31.0;
  APose1[1] = 166.746;
  APose1[2] = 1.49122;
  APose1[3] = 225;
  APose1[4] = -45.0;
  APose1[5] = 0.0;
  APose1[6] = 0;
  APose2.Clear();
  APose2[0] = 51.0;
  APose2[1] = 166.381;
  APose2[2] = 1.66929;
  APose2[3] = 225.0;
  APose2[4] = 0.0;
  APose2[5] = 0.0;
  APose2[6] = 0;
  APose3.Clear();
  APose3[0] = 242.0;
  APose3[1] = 164.417;
  APose3[2] = -0.603401;
  APose3[3] = 225;
  APose3[4] = 0.0;
  APose3[5] = 0.0;
  APose3[6] = 0;
  APose4.Clear();
  APose4[0] = 261.0;
  APose4[1] = 164.271;
  APose4[2] = -0.722725;
  APose4[3] = 225;
  APose4[4] = 45.0;
  APose4[5] = 0.0;
  APose4[6] = 0;

  WritePose(APose1, "./data/AnglePose/Pose1.dat");
  WritePose(APose2, "./data/AnglePose/Pose2.dat");
  WritePose(APose3, "./data/AnglePose/Pose3.dat");
  WritePose(APose4, "./data/AnglePose/Pose4.dat");

  //设置姿态
  try
  {
      ReadPose("./data/AnglePose/Pose1.dat", &APose1);
      ReadPose("./data/AnglePose/Pose2.dat", &APose2);
      ReadPose("./data/AnglePose/Pose3.dat", &APose3);
      ReadPose("./data/AnglePose/Pose4.dat", &APose4);

      (Pose1)[3] = HTuple(APose1[3]);
      (Pose1)[4] = HTuple(APose1[4]);
      (Pose1)[5] = HTuple(APose1[5]);

      (Pose2)[3] = HTuple(APose2[3]);
      (Pose2)[4] = HTuple(APose2[4]);
      Pose2[5] = HTuple(APose2[5]);

      (Pose3)[3] = HTuple(APose3[3]);
      (Pose3)[4] = HTuple(APose3[4]);
      Pose3[5] = HTuple(APose3[5]);

      (Pose4)[3] = HTuple(APose4[3]);
      (Pose4)[4] = HTuple(APose4[4]);
      (Pose4)[5] = HTuple(APose4[5]);
  }
  catch(...)
  {
      qDebug()<<"failed 01";
  }



  return;
}

void gen_cam_par_area_scan_division (HTuple Focus, HTuple Kappa, HTuple Sx,
    HTuple Sy, HTuple Cx, HTuple Cy, HTuple ImageWidth, HTuple ImageHeight,
    HTuple *CameraParam);

void gen_cam_par_area_scan_division (HTuple Focus, HTuple Kappa, HTuple Sx,
    HTuple Sy, HTuple Cx, HTuple Cy, HTuple ImageWidth, HTuple ImageHeight,
    HTuple *CameraParam)
{

  // Local iconic variables

  //Generate a camera parameter tuple for an area scan camera
  //with distortions modeled by the division model.
  //
  (*CameraParam).Clear();
  (*CameraParam)[0] = "area_scan_division";
  (*CameraParam).Append(Focus);
  (*CameraParam).Append(Kappa);
  (*CameraParam).Append(Sx);
  (*CameraParam).Append(Sy);
  (*CameraParam).Append(Cx);
  (*CameraParam).Append(Cy);
  (*CameraParam).Append(ImageWidth);
  (*CameraParam).Append(ImageHeight);
  return;
}

void get_cam_par_data (HTuple CameraParam, HTuple ParamName, HTuple *ParamValue)
{

  // Local iconic variables

  // Local control variables
  HTuple  CameraType, CameraParamNames, Index;
  HTuple  ParamNameInd, I;

  //get_cam_par_data returns in ParamValue the value of the
  //parameter that is given in ParamName from the tuple of
  //camera parameters that is given in CameraParam.
  //
  //Get the parameter names that correspond to the
  //elements in the input camera parameter tuple.
  get_cam_par_names(CameraParam, &CameraType, &CameraParamNames);
  //
  //Find the index of the requested camera data and return
  //the corresponding value.
  (*ParamValue) = HTuple();
  {
  HTuple end_val11 = (ParamName.TupleLength())-1;
  HTuple step_val11 = 1;
  for (Index=0; Index.Continue(end_val11, step_val11); Index += step_val11)
  {
    ParamNameInd = HTuple(ParamName[Index]);
    if (0 != (int(ParamNameInd==HTuple("camera_type"))))
    {
      (*ParamValue) = (*ParamValue).TupleConcat(CameraType);
      continue;
    }
    I = CameraParamNames.TupleFind(ParamNameInd);
    if (0 != (int(I!=-1)))
    {
      (*ParamValue) = (*ParamValue).TupleConcat(HTuple(CameraParam[I]));
    }
    else
    {
      throw HException("Unknown camera parameter "+ParamNameInd);
    }
  }
  }
  return;
}
void set_cam_par_data (HTuple CameraParamIn, HTuple ParamName, HTuple ParamValue,
    HTuple *CameraParamOut)
{

  // Local iconic variables

  // Local control variables
  HTuple  Index, ParamNameInd, CameraParamNames;
  HTuple  I, CameraType, IsTelecentric;

  //set_cam_par_data sets the value of the parameter that
  //is given in ParamName in the tuple of camera parameters
  //given in CameraParamIn. The modified camera parameters
  //are returned in CameraParamOut.
  //
  //Check for consistent length of input parameters
  if (0 != (int((ParamName.TupleLength())!=(ParamValue.TupleLength()))))
  {
    throw HException("Different number of values in ParamName and ParamValue");
  }
  //First, get the parameter names that correspond to the
  //elements in the input camera parameter tuple.
  get_cam_par_names(CameraParamIn, &CameraType, &CameraParamNames);
  //
  //Find the index of the requested camera data and return
  //the corresponding value.
  (*CameraParamOut) = CameraParamIn;
  {
  HTuple end_val16 = (ParamName.TupleLength())-1;
  HTuple step_val16 = 1;
  for (Index=0; Index.Continue(end_val16, step_val16); Index += step_val16)
  {
    ParamNameInd = HTuple(ParamName[Index]);
    I = CameraParamNames.TupleFind(ParamNameInd);
    if (0 != (int(I!=-1)))
    {
      (*CameraParamOut)[I] = HTuple(ParamValue[Index]);
    }
    else
    {
      throw HException("Wrong ParamName "+ParamNameInd);
    }
    //Check the consistency of focus and telecentricity
    if (0 != (int(ParamNameInd==HTuple("focus"))))
    {
      IsTelecentric = HTuple(int((CameraType.TupleStrstr("telecentric"))!=-1)).TupleAnd(int((CameraType.TupleStrstr("image_side_telecentric"))==-1));
      if (0 != IsTelecentric)
      {
        throw HException(HTuple("Focus for telecentric lenses is always 0, and hence, cannot be changed."));
      }
      if (0 != (HTuple(IsTelecentric.TupleNot()).TupleAnd(int(HTuple(ParamValue[Index])==0.0))))
      {
        throw HException("Focus for non-telecentric lenses must not be 0.");
      }
    }
  }
  }
  return;
}
void get_cam_par_names (HTuple CameraParam, HTuple *CameraType, HTuple *ParamNames)
{

  // Local iconic variables

  // Local control variables
  HTuple  CameraParamAreaScanDivision, CameraParamAreaScanPolynomial;
  HTuple  CameraParamAreaScanTelecentricDivision, CameraParamAreaScanTelecentricPolynomial;
  HTuple  CameraParamAreaScanTiltDivision, CameraParamAreaScanTiltPolynomial;
  HTuple  CameraParamAreaScanImageSideTelecentricTiltDivision;
  HTuple  CameraParamAreaScanImageSideTelecentricTiltPolynomial;
  HTuple  CameraParamAreaScanBilateralTelecentricTiltDivision;
  HTuple  CameraParamAreaScanBilateralTelecentricTiltPolynomial;
  HTuple  CameraParamAreaScanObjectSideTelecentricTiltDivision;
  HTuple  CameraParamAreaScanObjectSideTelecentricTiltPolynomial;
  HTuple  CameraParamAreaScanHypercentricDivision, CameraParamAreaScanHypercentricPolynomial;
  HTuple  CameraParamLinesScanDivision, CameraParamLinesScanPolynomial;
  HTuple  CameraParamLinesScanTelecentricDivision, CameraParamLinesScanTelecentricPolynomial;
  HTuple  CameraParamAreaScanTiltDivisionLegacy, CameraParamAreaScanTiltPolynomialLegacy;
  HTuple  CameraParamAreaScanTelecentricDivisionLegacy;
  HTuple  CameraParamAreaScanTelecentricPolynomialLegacy;
  HTuple  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy;
  HTuple  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy;

  //get_cam_par_names returns for each element in the camera
  //parameter tuple that is passed in CameraParam the name
  //of the respective camera parameter. The parameter names
  //are returned in ParamNames. Additionally, the camera
  //type is returned in CameraType. Alternatively, instead of
  //the camera parameters, the camera type can be passed in
  //CameraParam in form of one of the following strings:
  //  - 'area_scan_division'
  //  - 'area_scan_polynomial'
  //  - 'area_scan_tilt_division'
  //  - 'area_scan_tilt_polynomial'
  //  - 'area_scan_telecentric_division'
  //  - 'area_scan_telecentric_polynomial'
  //  - 'area_scan_tilt_bilateral_telecentric_division'
  //  - 'area_scan_tilt_bilateral_telecentric_polynomial'
  //  - 'area_scan_tilt_object_side_telecentric_division'
  //  - 'area_scan_tilt_object_side_telecentric_polynomial'
  //  - 'area_scan_hypercentric_division'
  //  - 'area_scan_hypercentric_polynomial'
  //  - 'line_scan_division'
  //  - 'line_scan_polynomial'
  //  - 'line_scan_telecentric_division'
  //  - 'line_scan_telecentric_polynomial'
  //
  CameraParamAreaScanDivision.Clear();
  CameraParamAreaScanDivision[0] = "focus";
  CameraParamAreaScanDivision[1] = "kappa";
  CameraParamAreaScanDivision[2] = "sx";
  CameraParamAreaScanDivision[3] = "sy";
  CameraParamAreaScanDivision[4] = "cx";
  CameraParamAreaScanDivision[5] = "cy";
  CameraParamAreaScanDivision[6] = "image_width";
  CameraParamAreaScanDivision[7] = "image_height";
  CameraParamAreaScanPolynomial.Clear();
  CameraParamAreaScanPolynomial[0] = "focus";
  CameraParamAreaScanPolynomial[1] = "k1";
  CameraParamAreaScanPolynomial[2] = "k2";
  CameraParamAreaScanPolynomial[3] = "k3";
  CameraParamAreaScanPolynomial[4] = "p1";
  CameraParamAreaScanPolynomial[5] = "p2";
  CameraParamAreaScanPolynomial[6] = "sx";
  CameraParamAreaScanPolynomial[7] = "sy";
  CameraParamAreaScanPolynomial[8] = "cx";
  CameraParamAreaScanPolynomial[9] = "cy";
  CameraParamAreaScanPolynomial[10] = "image_width";
  CameraParamAreaScanPolynomial[11] = "image_height";
  CameraParamAreaScanTelecentricDivision.Clear();
  CameraParamAreaScanTelecentricDivision[0] = "magnification";
  CameraParamAreaScanTelecentricDivision[1] = "kappa";
  CameraParamAreaScanTelecentricDivision[2] = "sx";
  CameraParamAreaScanTelecentricDivision[3] = "sy";
  CameraParamAreaScanTelecentricDivision[4] = "cx";
  CameraParamAreaScanTelecentricDivision[5] = "cy";
  CameraParamAreaScanTelecentricDivision[6] = "image_width";
  CameraParamAreaScanTelecentricDivision[7] = "image_height";
  CameraParamAreaScanTelecentricPolynomial.Clear();
  CameraParamAreaScanTelecentricPolynomial[0] = "magnification";
  CameraParamAreaScanTelecentricPolynomial[1] = "k1";
  CameraParamAreaScanTelecentricPolynomial[2] = "k2";
  CameraParamAreaScanTelecentricPolynomial[3] = "k3";
  CameraParamAreaScanTelecentricPolynomial[4] = "p1";
  CameraParamAreaScanTelecentricPolynomial[5] = "p2";
  CameraParamAreaScanTelecentricPolynomial[6] = "sx";
  CameraParamAreaScanTelecentricPolynomial[7] = "sy";
  CameraParamAreaScanTelecentricPolynomial[8] = "cx";
  CameraParamAreaScanTelecentricPolynomial[9] = "cy";
  CameraParamAreaScanTelecentricPolynomial[10] = "image_width";
  CameraParamAreaScanTelecentricPolynomial[11] = "image_height";
  CameraParamAreaScanTiltDivision.Clear();
  CameraParamAreaScanTiltDivision[0] = "focus";
  CameraParamAreaScanTiltDivision[1] = "kappa";
  CameraParamAreaScanTiltDivision[2] = "image_plane_dist";
  CameraParamAreaScanTiltDivision[3] = "tilt";
  CameraParamAreaScanTiltDivision[4] = "rot";
  CameraParamAreaScanTiltDivision[5] = "sx";
  CameraParamAreaScanTiltDivision[6] = "sy";
  CameraParamAreaScanTiltDivision[7] = "cx";
  CameraParamAreaScanTiltDivision[8] = "cy";
  CameraParamAreaScanTiltDivision[9] = "image_width";
  CameraParamAreaScanTiltDivision[10] = "image_height";
  CameraParamAreaScanTiltPolynomial.Clear();
  CameraParamAreaScanTiltPolynomial[0] = "focus";
  CameraParamAreaScanTiltPolynomial[1] = "k1";
  CameraParamAreaScanTiltPolynomial[2] = "k2";
  CameraParamAreaScanTiltPolynomial[3] = "k3";
  CameraParamAreaScanTiltPolynomial[4] = "p1";
  CameraParamAreaScanTiltPolynomial[5] = "p2";
  CameraParamAreaScanTiltPolynomial[6] = "image_plane_dist";
  CameraParamAreaScanTiltPolynomial[7] = "tilt";
  CameraParamAreaScanTiltPolynomial[8] = "rot";
  CameraParamAreaScanTiltPolynomial[9] = "sx";
  CameraParamAreaScanTiltPolynomial[10] = "sy";
  CameraParamAreaScanTiltPolynomial[11] = "cx";
  CameraParamAreaScanTiltPolynomial[12] = "cy";
  CameraParamAreaScanTiltPolynomial[13] = "image_width";
  CameraParamAreaScanTiltPolynomial[14] = "image_height";
  CameraParamAreaScanImageSideTelecentricTiltDivision.Clear();
  CameraParamAreaScanImageSideTelecentricTiltDivision[0] = "focus";
  CameraParamAreaScanImageSideTelecentricTiltDivision[1] = "kappa";
  CameraParamAreaScanImageSideTelecentricTiltDivision[2] = "tilt";
  CameraParamAreaScanImageSideTelecentricTiltDivision[3] = "rot";
  CameraParamAreaScanImageSideTelecentricTiltDivision[4] = "sx";
  CameraParamAreaScanImageSideTelecentricTiltDivision[5] = "sy";
  CameraParamAreaScanImageSideTelecentricTiltDivision[6] = "cx";
  CameraParamAreaScanImageSideTelecentricTiltDivision[7] = "cy";
  CameraParamAreaScanImageSideTelecentricTiltDivision[8] = "image_width";
  CameraParamAreaScanImageSideTelecentricTiltDivision[9] = "image_height";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial.Clear();
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[0] = "focus";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[1] = "k1";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[2] = "k2";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[3] = "k3";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[4] = "p1";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[5] = "p2";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[6] = "tilt";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[7] = "rot";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[8] = "sx";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[9] = "sy";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[10] = "cx";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[11] = "cy";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[12] = "image_width";
  CameraParamAreaScanImageSideTelecentricTiltPolynomial[13] = "image_height";
  CameraParamAreaScanBilateralTelecentricTiltDivision.Clear();
  CameraParamAreaScanBilateralTelecentricTiltDivision[0] = "magnification";
  CameraParamAreaScanBilateralTelecentricTiltDivision[1] = "kappa";
  CameraParamAreaScanBilateralTelecentricTiltDivision[2] = "tilt";
  CameraParamAreaScanBilateralTelecentricTiltDivision[3] = "rot";
  CameraParamAreaScanBilateralTelecentricTiltDivision[4] = "sx";
  CameraParamAreaScanBilateralTelecentricTiltDivision[5] = "sy";
  CameraParamAreaScanBilateralTelecentricTiltDivision[6] = "cx";
  CameraParamAreaScanBilateralTelecentricTiltDivision[7] = "cy";
  CameraParamAreaScanBilateralTelecentricTiltDivision[8] = "image_width";
  CameraParamAreaScanBilateralTelecentricTiltDivision[9] = "image_height";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial.Clear();
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[0] = "magnification";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[1] = "k1";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[2] = "k2";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[3] = "k3";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[4] = "p1";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[5] = "p2";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[6] = "tilt";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[7] = "rot";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[8] = "sx";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[9] = "sy";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[10] = "cx";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[11] = "cy";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[12] = "image_width";
  CameraParamAreaScanBilateralTelecentricTiltPolynomial[13] = "image_height";
  CameraParamAreaScanObjectSideTelecentricTiltDivision.Clear();
  CameraParamAreaScanObjectSideTelecentricTiltDivision[0] = "magnification";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[1] = "kappa";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[2] = "image_plane_dist";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[3] = "tilt";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[4] = "rot";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[5] = "sx";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[6] = "sy";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[7] = "cx";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[8] = "cy";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[9] = "image_width";
  CameraParamAreaScanObjectSideTelecentricTiltDivision[10] = "image_height";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial.Clear();
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[0] = "magnification";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[1] = "k1";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[2] = "k2";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[3] = "k3";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[4] = "p1";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[5] = "p2";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[6] = "image_plane_dist";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[7] = "tilt";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[8] = "rot";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[9] = "sx";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[10] = "sy";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[11] = "cx";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[12] = "cy";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[13] = "image_width";
  CameraParamAreaScanObjectSideTelecentricTiltPolynomial[14] = "image_height";
  CameraParamAreaScanHypercentricDivision.Clear();
  CameraParamAreaScanHypercentricDivision[0] = "focus";
  CameraParamAreaScanHypercentricDivision[1] = "kappa";
  CameraParamAreaScanHypercentricDivision[2] = "sx";
  CameraParamAreaScanHypercentricDivision[3] = "sy";
  CameraParamAreaScanHypercentricDivision[4] = "cx";
  CameraParamAreaScanHypercentricDivision[5] = "cy";
  CameraParamAreaScanHypercentricDivision[6] = "image_width";
  CameraParamAreaScanHypercentricDivision[7] = "image_height";
  CameraParamAreaScanHypercentricPolynomial.Clear();
  CameraParamAreaScanHypercentricPolynomial[0] = "focus";
  CameraParamAreaScanHypercentricPolynomial[1] = "k1";
  CameraParamAreaScanHypercentricPolynomial[2] = "k2";
  CameraParamAreaScanHypercentricPolynomial[3] = "k3";
  CameraParamAreaScanHypercentricPolynomial[4] = "p1";
  CameraParamAreaScanHypercentricPolynomial[5] = "p2";
  CameraParamAreaScanHypercentricPolynomial[6] = "sx";
  CameraParamAreaScanHypercentricPolynomial[7] = "sy";
  CameraParamAreaScanHypercentricPolynomial[8] = "cx";
  CameraParamAreaScanHypercentricPolynomial[9] = "cy";
  CameraParamAreaScanHypercentricPolynomial[10] = "image_width";
  CameraParamAreaScanHypercentricPolynomial[11] = "image_height";
  CameraParamLinesScanDivision.Clear();
  CameraParamLinesScanDivision[0] = "focus";
  CameraParamLinesScanDivision[1] = "kappa";
  CameraParamLinesScanDivision[2] = "sx";
  CameraParamLinesScanDivision[3] = "sy";
  CameraParamLinesScanDivision[4] = "cx";
  CameraParamLinesScanDivision[5] = "cy";
  CameraParamLinesScanDivision[6] = "image_width";
  CameraParamLinesScanDivision[7] = "image_height";
  CameraParamLinesScanDivision[8] = "vx";
  CameraParamLinesScanDivision[9] = "vy";
  CameraParamLinesScanDivision[10] = "vz";
  CameraParamLinesScanPolynomial.Clear();
  CameraParamLinesScanPolynomial[0] = "focus";
  CameraParamLinesScanPolynomial[1] = "k1";
  CameraParamLinesScanPolynomial[2] = "k2";
  CameraParamLinesScanPolynomial[3] = "k3";
  CameraParamLinesScanPolynomial[4] = "p1";
  CameraParamLinesScanPolynomial[5] = "p2";
  CameraParamLinesScanPolynomial[6] = "sx";
  CameraParamLinesScanPolynomial[7] = "sy";
  CameraParamLinesScanPolynomial[8] = "cx";
  CameraParamLinesScanPolynomial[9] = "cy";
  CameraParamLinesScanPolynomial[10] = "image_width";
  CameraParamLinesScanPolynomial[11] = "image_height";
  CameraParamLinesScanPolynomial[12] = "vx";
  CameraParamLinesScanPolynomial[13] = "vy";
  CameraParamLinesScanPolynomial[14] = "vz";
  CameraParamLinesScanTelecentricDivision.Clear();
  CameraParamLinesScanTelecentricDivision[0] = "magnification";
  CameraParamLinesScanTelecentricDivision[1] = "kappa";
  CameraParamLinesScanTelecentricDivision[2] = "sx";
  CameraParamLinesScanTelecentricDivision[3] = "sy";
  CameraParamLinesScanTelecentricDivision[4] = "cx";
  CameraParamLinesScanTelecentricDivision[5] = "cy";
  CameraParamLinesScanTelecentricDivision[6] = "image_width";
  CameraParamLinesScanTelecentricDivision[7] = "image_height";
  CameraParamLinesScanTelecentricDivision[8] = "vx";
  CameraParamLinesScanTelecentricDivision[9] = "vy";
  CameraParamLinesScanTelecentricDivision[10] = "vz";
  CameraParamLinesScanTelecentricPolynomial.Clear();
  CameraParamLinesScanTelecentricPolynomial[0] = "magnification";
  CameraParamLinesScanTelecentricPolynomial[1] = "k1";
  CameraParamLinesScanTelecentricPolynomial[2] = "k2";
  CameraParamLinesScanTelecentricPolynomial[3] = "k3";
  CameraParamLinesScanTelecentricPolynomial[4] = "p1";
  CameraParamLinesScanTelecentricPolynomial[5] = "p2";
  CameraParamLinesScanTelecentricPolynomial[6] = "sx";
  CameraParamLinesScanTelecentricPolynomial[7] = "sy";
  CameraParamLinesScanTelecentricPolynomial[8] = "cx";
  CameraParamLinesScanTelecentricPolynomial[9] = "cy";
  CameraParamLinesScanTelecentricPolynomial[10] = "image_width";
  CameraParamLinesScanTelecentricPolynomial[11] = "image_height";
  CameraParamLinesScanTelecentricPolynomial[12] = "vx";
  CameraParamLinesScanTelecentricPolynomial[13] = "vy";
  CameraParamLinesScanTelecentricPolynomial[14] = "vz";
  //Legacy parameter names
  CameraParamAreaScanTiltDivisionLegacy.Clear();
  CameraParamAreaScanTiltDivisionLegacy[0] = "focus";
  CameraParamAreaScanTiltDivisionLegacy[1] = "kappa";
  CameraParamAreaScanTiltDivisionLegacy[2] = "tilt";
  CameraParamAreaScanTiltDivisionLegacy[3] = "rot";
  CameraParamAreaScanTiltDivisionLegacy[4] = "sx";
  CameraParamAreaScanTiltDivisionLegacy[5] = "sy";
  CameraParamAreaScanTiltDivisionLegacy[6] = "cx";
  CameraParamAreaScanTiltDivisionLegacy[7] = "cy";
  CameraParamAreaScanTiltDivisionLegacy[8] = "image_width";
  CameraParamAreaScanTiltDivisionLegacy[9] = "image_height";
  CameraParamAreaScanTiltPolynomialLegacy.Clear();
  CameraParamAreaScanTiltPolynomialLegacy[0] = "focus";
  CameraParamAreaScanTiltPolynomialLegacy[1] = "k1";
  CameraParamAreaScanTiltPolynomialLegacy[2] = "k2";
  CameraParamAreaScanTiltPolynomialLegacy[3] = "k3";
  CameraParamAreaScanTiltPolynomialLegacy[4] = "p1";
  CameraParamAreaScanTiltPolynomialLegacy[5] = "p2";
  CameraParamAreaScanTiltPolynomialLegacy[6] = "tilt";
  CameraParamAreaScanTiltPolynomialLegacy[7] = "rot";
  CameraParamAreaScanTiltPolynomialLegacy[8] = "sx";
  CameraParamAreaScanTiltPolynomialLegacy[9] = "sy";
  CameraParamAreaScanTiltPolynomialLegacy[10] = "cx";
  CameraParamAreaScanTiltPolynomialLegacy[11] = "cy";
  CameraParamAreaScanTiltPolynomialLegacy[12] = "image_width";
  CameraParamAreaScanTiltPolynomialLegacy[13] = "image_height";
  CameraParamAreaScanTelecentricDivisionLegacy.Clear();
  CameraParamAreaScanTelecentricDivisionLegacy[0] = "focus";
  CameraParamAreaScanTelecentricDivisionLegacy[1] = "kappa";
  CameraParamAreaScanTelecentricDivisionLegacy[2] = "sx";
  CameraParamAreaScanTelecentricDivisionLegacy[3] = "sy";
  CameraParamAreaScanTelecentricDivisionLegacy[4] = "cx";
  CameraParamAreaScanTelecentricDivisionLegacy[5] = "cy";
  CameraParamAreaScanTelecentricDivisionLegacy[6] = "image_width";
  CameraParamAreaScanTelecentricDivisionLegacy[7] = "image_height";
  CameraParamAreaScanTelecentricPolynomialLegacy.Clear();
  CameraParamAreaScanTelecentricPolynomialLegacy[0] = "focus";
  CameraParamAreaScanTelecentricPolynomialLegacy[1] = "k1";
  CameraParamAreaScanTelecentricPolynomialLegacy[2] = "k2";
  CameraParamAreaScanTelecentricPolynomialLegacy[3] = "k3";
  CameraParamAreaScanTelecentricPolynomialLegacy[4] = "p1";
  CameraParamAreaScanTelecentricPolynomialLegacy[5] = "p2";
  CameraParamAreaScanTelecentricPolynomialLegacy[6] = "sx";
  CameraParamAreaScanTelecentricPolynomialLegacy[7] = "sy";
  CameraParamAreaScanTelecentricPolynomialLegacy[8] = "cx";
  CameraParamAreaScanTelecentricPolynomialLegacy[9] = "cy";
  CameraParamAreaScanTelecentricPolynomialLegacy[10] = "image_width";
  CameraParamAreaScanTelecentricPolynomialLegacy[11] = "image_height";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy.Clear();
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[0] = "focus";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[1] = "kappa";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[2] = "tilt";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[3] = "rot";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[4] = "sx";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[5] = "sy";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[6] = "cx";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[7] = "cy";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[8] = "image_width";
  CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy[9] = "image_height";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy.Clear();
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[0] = "focus";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[1] = "k1";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[2] = "k2";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[3] = "k3";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[4] = "p1";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[5] = "p2";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[6] = "tilt";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[7] = "rot";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[8] = "sx";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[9] = "sy";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[10] = "cx";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[11] = "cy";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[12] = "image_width";
  CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy[13] = "image_height";
  //
  //If the camera type is passed in CameraParam
  if (0 != (HTuple(int((CameraParam.TupleLength())==1)).TupleAnd(HTuple(CameraParam[0]).TupleIsString())))
  {
    (*CameraType) = ((const HTuple&)CameraParam)[0];
    if (0 != (int((*CameraType)==HTuple("area_scan_division"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_telecentric_division"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanTelecentricDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_telecentric_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanTelecentricPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_division"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanTiltDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanTiltPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_image_side_telecentric_division"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanImageSideTelecentricTiltDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_image_side_telecentric_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanImageSideTelecentricTiltPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_bilateral_telecentric_division"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanBilateralTelecentricTiltDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_bilateral_telecentric_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanBilateralTelecentricTiltPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_object_side_telecentric_division"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanObjectSideTelecentricTiltDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_object_side_telecentric_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanObjectSideTelecentricTiltPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_hypercentric_division"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanHypercentricDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_hypercentric_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanHypercentricPolynomial);
    }
    else if (0 != (HTuple(int((*CameraType)==HTuple("line_scan_division"))).TupleOr(int((*CameraType)==HTuple("line_scan")))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamLinesScanDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("line_scan_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamLinesScanPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("line_scan_telecentric_division"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamLinesScanTelecentricDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("line_scan_telecentric_polynomial"))))
    {
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamLinesScanTelecentricPolynomial);
    }
    else
    {
      throw HException(("Unknown camera type '"+(*CameraType))+"' passed in CameraParam.");
    }
    return;
  }
  //
  //If the camera parameters are passed in CameraParam
  if (0 != ((HTuple(CameraParam[0]).TupleIsString()).TupleNot()))
  {
    //Format of camera parameters for HALCON 12 and earlier
    switch ((CameraParam.TupleLength()).I())
    {
      //
      //Area Scan
    case 8:
      //CameraType: 'area_scan_division' or 'area_scan_telecentric_division'
      if (0 != (int(HTuple(CameraParam[0])!=0.0)))
      {
        (*ParamNames) = CameraParamAreaScanDivision;
        (*CameraType) = "area_scan_division";
      }
      else
      {
        (*ParamNames) = CameraParamAreaScanTelecentricDivisionLegacy;
        (*CameraType) = "area_scan_telecentric_division";
      }
      break;
    case 10:
      //CameraType: 'area_scan_tilt_division' or 'area_scan_telecentric_tilt_division'
      if (0 != (int(HTuple(CameraParam[0])!=0.0)))
      {
        (*ParamNames) = CameraParamAreaScanTiltDivisionLegacy;
        (*CameraType) = "area_scan_tilt_division";
      }
      else
      {
        (*ParamNames) = CameraParamAreaScanBilateralTelecentricTiltDivisionLegacy;
        (*CameraType) = "area_scan_tilt_bilateral_telecentric_division";
      }
      break;
    case 12:
      //CameraType: 'area_scan_polynomial' or 'area_scan_telecentric_polynomial'
      if (0 != (int(HTuple(CameraParam[0])!=0.0)))
      {
        (*ParamNames) = CameraParamAreaScanPolynomial;
        (*CameraType) = "area_scan_polynomial";
      }
      else
      {
        (*ParamNames) = CameraParamAreaScanTelecentricPolynomialLegacy;
        (*CameraType) = "area_scan_telecentric_polynomial";
      }
      break;
    case 14:
      //CameraType: 'area_scan_tilt_polynomial' or 'area_scan_telecentric_tilt_polynomial'
      if (0 != (int(HTuple(CameraParam[0])!=0.0)))
      {
        (*ParamNames) = CameraParamAreaScanTiltPolynomialLegacy;
        (*CameraType) = "area_scan_tilt_polynomial";
      }
      else
      {
        (*ParamNames) = CameraParamAreaScanBilateralTelecentricTiltPolynomialLegacy;
        (*CameraType) = "area_scan_tilt_bilateral_telecentric_polynomial";
      }
      break;
      //
      //Line Scan
    case 11:
      //CameraType: 'line_scan' or 'line_scan_telecentric'
      if (0 != (int(HTuple(CameraParam[0])!=0.0)))
      {
        (*ParamNames) = CameraParamLinesScanDivision;
        (*CameraType) = "line_scan_division";
      }
      else
      {
        (*ParamNames) = CameraParamLinesScanTelecentricDivision;
        (*CameraType) = "line_scan_telecentric_division";
      }
      break;
    default:
      throw HException("Wrong number of values in CameraParam.");
    }
  }
  else
  {
    //Format of camera parameters since HALCON 13
    (*CameraType) = ((const HTuple&)CameraParam)[0];
    if (0 != (int((*CameraType)==HTuple("area_scan_division"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=9)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=13)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_telecentric_division"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=9)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanTelecentricDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_telecentric_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=13)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanTelecentricPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_division"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=12)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanTiltDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=16)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanTiltPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_image_side_telecentric_division"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=11)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanImageSideTelecentricTiltDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_image_side_telecentric_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=15)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanImageSideTelecentricTiltPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_bilateral_telecentric_division"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=11)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanBilateralTelecentricTiltDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_bilateral_telecentric_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=15)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanBilateralTelecentricTiltPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_object_side_telecentric_division"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=12)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanObjectSideTelecentricTiltDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_tilt_object_side_telecentric_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=16)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanObjectSideTelecentricTiltPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_hypercentric_division"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=9)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanHypercentricDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("area_scan_hypercentric_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=13)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamAreaScanHypercentricPolynomial);
    }
    else if (0 != (HTuple(int((*CameraType)==HTuple("line_scan_division"))).TupleOr(int((*CameraType)==HTuple("line_scan")))))
    {
      if (0 != (int((CameraParam.TupleLength())!=12)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamLinesScanDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("line_scan_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=16)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamLinesScanPolynomial);
    }
    else if (0 != (int((*CameraType)==HTuple("line_scan_telecentric_division"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=12)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamLinesScanTelecentricDivision);
    }
    else if (0 != (int((*CameraType)==HTuple("line_scan_telecentric_polynomial"))))
    {
      if (0 != (int((CameraParam.TupleLength())!=16)))
      {
        throw HException("Wrong number of values in CameraParam.");
      }
      (*ParamNames).Clear();
      (*ParamNames)[0] = "camera_type";
      (*ParamNames).Append(CameraParamLinesScanTelecentricPolynomial);
    }
    else
    {
      throw HException("Unknown camera type in CameraParam.");
    }
  }
  return;
}
void visualize_object_model_3d (HTuple WindowHandle, HTuple ObjectModel3D,
    HTuple CamParam, HTuple PoseIn, HTuple GenParamName, HTuple GenParamValue,
    HTuple Title, HTuple Label, HTuple Information, HTuple *PoseOut)
{

  // Local iconic variables
  HObject  Image, ImageDump;

  // Local control variables
  HTuple  ExpTmpLocalVar_gDispObjOffset, ExpTmpLocalVar_gLabelsDecor;
  HTuple  ExpTmpLocalVar_gInfoDecor, ExpTmpLocalVar_gInfoPos;
  HTuple  ExpTmpLocalVar_gTitlePos, ExpTmpLocalVar_gTitleDecor;
  HTuple  ExpTmpLocalVar_gTerminationButtonLabel, ExpTmpLocalVar_gAlphaDeselected;
  HTuple  ExpTmpLocalVar_gIsSinglePose, ExpTmpLocalVar_gUsesOpenGL;
  HTuple  TrackballSize, VirtualTrackball, MouseMapping;
  HTuple  WaitForButtonRelease, MaxNumModels, WindowCenteredRotation;
  HTuple  NumModels, SelectedObject, ClipRegion;
  HTuple  CPLength, RowNotUsed, ColumnNotUsed, Width;
  HTuple  Height, WPRow1, WPColumn1, WPRow2, WPColumn2;
  HTuple  CamWidth, CamHeight, Scale, Indices;
  HTuple  DispBackground, Mask, Center, PoseEstimated;
  HTuple  Poses, HomMat3Ds, Sequence, WindowHandleBuffer;
  HTuple  Font, Exception, OpenGLInfo, DummyObjectModel3D;
  HTuple  Scene3DTest, CameraIndexTest, PoseTest;
  HTuple  InstanceIndexTest, MinImageSize, TrackballRadiusPixel;
  HTuple  Ascent, Descent, TextWidth, TextHeight;
  HTuple  NumChannels, ColorImage, Scene3D, CameraIndex;
  HTuple  AllInstances, SetLight, LightParam, LightPosition;
  HTuple  LightKind, LightIndex, PersistenceParamName;
  HTuple  PersistenceParamValue, ValueListSS3P, ValueListSS3IP;
  HTuple  AlphaOrig, UsedParamMask, I, ParamName;
  HTuple  ParamValue, UseParam, ParamNameTrunk, Instance;
  HTuple  GenParamNameRemaining, GenParamValueRemaining;
  HTuple  HomMat3D, Qx, Qy, Qz, TBCenter, TBSize;
  HTuple  ButtonHold, VisualizeTB, MaxIndex, TrackballCenterRow;
  HTuple  TrackballCenterCol, GraphEvent, Exit, GraphButtonRow;
  HTuple  GraphButtonColumn, GraphButton, ButtonReleased;

  //The procedure visualize_object_model_3d can be used to display
  //one or more 3d object models and to interactively modify
  //the object poses by using the mouse.
  //
  //The pose can be modified by moving the mouse while
  //pressing a mouse button. The default settings are:
  //
  // Left mouse button:   Modify the object orientation
  // Shift+ left mouse button  or
  // center mouse button: Modify the object distance
  // Right mouse button:  Modify the object position
  // Ctrl + Left mouse button: (De-)select object(s)
  // Alt + Mouse button: Low mouse sensitiviy
  // (Default may be changed with the variable MouseMapping below)
  //
  //In GenParamName and GenParamValue all generic Paramters
  //of disp_object_model_3d are supported.
  //
  //**********************************************************
  //Define global variables
  //**********************************************************
  //
  //global def tuple gDispObjOffset
  //global def tuple gLabelsDecor
  //global def tuple gInfoDecor
  //global def tuple gInfoPos
  //global def tuple gTitlePos
  //global def tuple gTitleDecor
  //global def tuple gTerminationButtonLabel
  //global def tuple gAlphaDeselected
  //global def tuple gIsSinglePose
  //global def tuple gUsesOpenGL
  //
  //**********************************************************
  //First some user defines that may be adapted if desired
  //**********************************************************
  //
  //TrackballSize defines the diameter of the trackball in
  //the image with respect to the smaller image dimension.
  TrackballSize = 0.8;
  //
  //VirtualTrackball defines the type of virtual trackball that
  //shall be used ('shoemake' or 'bell').
  VirtualTrackball = "shoemake";
  //VirtualTrackball := 'bell'
  //
  //Functionality of mouse buttons
  //    1: Left Button
  //    2: Middle Button
  //    4: Right Button
  //    5: Left+Right Mousebutton
  //  8+x: Shift + Mousebutton
  // 16+x: Ctrl + Mousebutton
  // 48+x: Ctrl + Alt + Mousebutton
  //in the order [Translate, Rotate, Scale, ScaleAlternative1, ScaleAlternative2, SelectObjects, ToggleSelectionMode]
  MouseMapping.Clear();
  MouseMapping[0] = 17;
  MouseMapping[1] = 1;
  MouseMapping[2] = 2;
  MouseMapping[3] = 5;
  MouseMapping[4] = 9;
  MouseMapping[5] = 4;
  MouseMapping[6] = 49;
  //
  //The labels of the objects appear next to their projected
  //center. With gDispObjOffset a fixed offset is added
  //                  R,  C
  ExpTmpLocalVar_gDispObjOffset.Clear();
  ExpTmpLocalVar_gDispObjOffset[0] = -30;
  ExpTmpLocalVar_gDispObjOffset[1] = 0;
  ExpSetGlobalVar_gDispObjOffset(ExpTmpLocalVar_gDispObjOffset);
  //
  //Customize the decoration of the different text elements
  //              Color,   Box
  ExpTmpLocalVar_gInfoDecor.Clear();
  ExpTmpLocalVar_gInfoDecor[0] = "white";
  ExpTmpLocalVar_gInfoDecor[1] = "false";
  ExpSetGlobalVar_gInfoDecor(ExpTmpLocalVar_gInfoDecor);
  ExpTmpLocalVar_gLabelsDecor.Clear();
  ExpTmpLocalVar_gLabelsDecor[0] = "white";
  ExpTmpLocalVar_gLabelsDecor[1] = "false";
  ExpSetGlobalVar_gLabelsDecor(ExpTmpLocalVar_gLabelsDecor);
  ExpTmpLocalVar_gTitleDecor.Clear();
  ExpTmpLocalVar_gTitleDecor[0] = "black";
  ExpTmpLocalVar_gTitleDecor[1] = "true";
  ExpSetGlobalVar_gTitleDecor(ExpTmpLocalVar_gTitleDecor);
  //
  //Customize the position of some text elements
  //  gInfoPos has one of the values
  //  {'UpperLeft', 'LowerLeft', 'UpperRight'}
  ExpTmpLocalVar_gInfoPos = "LowerLeft";
  ExpSetGlobalVar_gInfoPos(ExpTmpLocalVar_gInfoPos);
  //  gTitlePos has one of the values
  //  {'UpperLeft', 'UpperCenter', 'UpperRight'}
  ExpTmpLocalVar_gTitlePos = "UpperLeft";
  ExpSetGlobalVar_gTitlePos(ExpTmpLocalVar_gTitlePos);
  //Alpha value (=1-transparency) that is used for visualizing
  //the objects that are not selected
  ExpTmpLocalVar_gAlphaDeselected = 0.3;
  ExpSetGlobalVar_gAlphaDeselected(ExpTmpLocalVar_gAlphaDeselected);
  //Customize the label of the continue button
  ExpTmpLocalVar_gTerminationButtonLabel = " Continue ";
  ExpSetGlobalVar_gTerminationButtonLabel(ExpTmpLocalVar_gTerminationButtonLabel);
  //Define if the continue button responds to a single click event or
  //if it responds only if the mouse button is released while being placed
  //over the continue button.
  //'true':  Wait until the continue button has been released.
  //         This should be used to avoid unwanted continuations of
  //         subsequent calls of visualize_object_model_3d, which can
  //         otherwise occur if the mouse button remains pressed while the
  //         next visualization is active.
  //'false': Continue the execution already if the continue button is
  //         pressed. This option allows a fast forwarding through
  //         subsequent calls of visualize_object_model_3d.
  WaitForButtonRelease = "true";
  //Number of 3D Object models that can be handled individually
  //if there are more models passed then this number, some calculations
  //are performed differently. And the individual handling of models is not
  //supported anymore
  MaxNumModels = 5;
  //Defines the default for the initial state of the rotation center:
  //(1) The rotation center is fixed in the center of the image and lies
  //    on the surface of the object.
  //(2) The rotation center lies in the center of the object.
  WindowCenteredRotation = 2;
  //
  //**********************************************************
  //
  //Initialize some values
  NumModels = ObjectModel3D.TupleLength();
  SelectedObject = HTuple(NumModels,1);
  //
  //Apply some system settings
  // dev_set_preferences(...); only in hdevelop
  // dev_get_preferences(...); only in hdevelop
  // dev_set_preferences(...); only in hdevelop
  // dev_get_preferences(...); only in hdevelop
  // dev_set_preferences(...); only in hdevelop
  GetSystem("clip_region", &ClipRegion);
  SetSystem("clip_region", "false");
  dev_update_off();
  //
  //Refactor camera parameters to fit to window size
  //
  CPLength = CamParam.TupleLength();
  GetWindowExtents(WindowHandle, &RowNotUsed, &ColumnNotUsed, &Width,
      &Height);
  GetPart(WindowHandle, &WPRow1, &WPColumn1, &WPRow2, &WPColumn2);
  SetPart(WindowHandle, 0, 0, Height-1, Width-1);
  if (0 != (CPLength==0))
  {
    CamParam.Clear();
    CamParam[0] = 0.06;
    CamParam[1] = 0;
    CamParam[2] = 8.5e-6;
    CamParam[3] = 8.5e-6;
    CamParam.Append(Width/2);
    CamParam.Append(Height/2);
    CamParam.Append(Width);
    CamParam.Append(Height);
    CPLength = CamParam.TupleLength();
  }
  else
  {
    CamWidth = HTuple(CamParam[CPLength-2]).TupleReal();
    CamHeight = HTuple(CamParam[CPLength-1]).TupleReal();
    Scale = ((Width/CamWidth).TupleConcat(Height/CamHeight)).TupleMin();
    CamParam[CPLength-6] = HTuple(CamParam[CPLength-6])/Scale;
    CamParam[CPLength-5] = HTuple(CamParam[CPLength-5])/Scale;
    CamParam[CPLength-4] = HTuple(CamParam[CPLength-4])*Scale;
    CamParam[CPLength-3] = HTuple(CamParam[CPLength-3])*Scale;
    CamParam[CPLength-2] = (HTuple(CamParam[CPLength-2])*Scale).TupleInt();
    CamParam[CPLength-1] = (HTuple(CamParam[CPLength-1])*Scale).TupleInt();
  }
  //
  //Check the generic parameters for window_centered_rotation
  //(Note that the default is set above to WindowCenteredRotation := 2)
  Indices = GenParamName.TupleFind("inspection_mode");
  if (0 != (HTuple(Indices!=-1).TupleAnd(Indices!=HTuple())))
  {
    if (0 != (HTuple(GenParamValue[HTuple(Indices[0])])==HTuple("surface")))
    {
      WindowCenteredRotation = 1;
    }
    else if (0 != (HTuple(GenParamValue[HTuple(Indices[0])])==HTuple("standard")))
    {
      WindowCenteredRotation = 2;
    }
    else
    {
      //Wrong parameter value, use default value
    }
    GenParamName = GenParamName.TupleRemove(Indices);
    GenParamValue = GenParamValue.TupleRemove(Indices);
  }
  //
  //Check the generic parameters for disp_background
  //(The former parameter name 'use_background' is still supported
  // for compatibility reasons)
  DispBackground = "false";
  if (0 != ((GenParamName.TupleLength())>0))
  {
    Mask = (GenParamName.TupleEqualElem("disp_background")).TupleOr(GenParamName.TupleEqualElem("use_background"));
    Indices = Mask.TupleFind(1);
  }
  else
  {
    Indices = -1;
  }
  if (0 != (HTuple(Indices!=-1).TupleAnd(Indices!=HTuple())))
  {
    DispBackground = ((const HTuple&)GenParamValue)[HTuple(Indices[0])];
    if (0 != (HTuple(DispBackground!=HTuple("true")).TupleAnd(DispBackground!=HTuple("false"))))
    {
      //Wrong parameter value: Only 'true' and 'false' are allowed
      throw HalconCpp::HException("Wrong value for parameter 'disp_background' (must be either 'true' or 'false')");
    }
    //Note the the background is handled explicitely in this procedure
    //and therefore, the parameter is removed from the list of
    //parameters and disp_background is always set to true (see below)
    GenParamName = GenParamName.TupleRemove(Indices);
    GenParamValue = GenParamValue.TupleRemove(Indices);
  }
  //
  //Read and check the parameter Label for each object
  if (0 != ((Label.TupleLength())==0))
  {
    Label = 0;
  }
  else if (0 != ((Label.TupleLength())==1))
  {
    Label = HTuple(NumModels,Label);
  }
  else
  {
    if (0 != ((Label.TupleLength())!=NumModels))
    {
      //Error: Number of elements in Label does not match the
      //number of object models
      // stop(); only in hdevelop
    }
  }
  //
  //Read and check the parameter PoseIn for each object
  get_object_models_center(ObjectModel3D, &Center);
  if (0 != ((PoseIn.TupleLength())==0))
  {
    //If no pose was specified by the caller, automatically calculate
    //a pose that is appropriate for the visualization.
    //Set the initial model reference pose. The orientation is parallel
    //to the object coordinate system, the position is at the center
    //of gravity of all models.
    CreatePose(-HTuple(Center[0]), -HTuple(Center[1]), -HTuple(Center[2]),
        0, 0, 0, "Rp+T", "gba", "point", &PoseIn);
    determine_optimum_pose_distance(ObjectModel3D, CamParam, 0.9, PoseIn,
        &PoseEstimated);
    Poses = HTuple();
    HomMat3Ds = HTuple();
    Sequence = HTuple::TupleGenSequence(0,(NumModels*7)-1,1);
    Poses = ((const HTuple&)PoseEstimated)[Sequence%7];
    ExpTmpLocalVar_gIsSinglePose = 1;
    ExpSetGlobalVar_gIsSinglePose(ExpTmpLocalVar_gIsSinglePose);
  }
  else if (0 != ((PoseIn.TupleLength())==7))
  {
    Poses = HTuple();
    HomMat3Ds = HTuple();
    Sequence = HTuple::TupleGenSequence(0,(NumModels*7)-1,1);
    Poses = ((const HTuple&)PoseIn)[Sequence%7];
    ExpTmpLocalVar_gIsSinglePose = 1;
    ExpSetGlobalVar_gIsSinglePose(ExpTmpLocalVar_gIsSinglePose);
  }
  else
  {
    if (0 != ((PoseIn.TupleLength())!=((ObjectModel3D.TupleLength())*7)))
    {
      //Error: Wrong number of values of input control parameter 'PoseIn'
      // stop(); only in hdevelop
    }
    else
    {
      Poses = PoseIn;
    }
    ExpTmpLocalVar_gIsSinglePose = 0;
    ExpSetGlobalVar_gIsSinglePose(ExpTmpLocalVar_gIsSinglePose);
  }
  //
  //Open (invisible) buffer window to avoid flickering
  OpenWindow(0, 0, Width, Height, 0, "buffer", "", &WindowHandleBuffer);
  SetPart(WindowHandleBuffer, 0, 0, Height-1, Width-1);
  GetFont(WindowHandle, &Font);
  try
  {
    SetFont(WindowHandleBuffer, Font);
  }
  // catch (Exception)
  catch (HalconCpp::HException &HDevExpDefaultException)
  {
    HDevExpDefaultException.ToHTuple(&Exception);
  }
  //
  // Is OpenGL available and should it be used?
  ExpTmpLocalVar_gUsesOpenGL = "true";
  ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
  Indices = GenParamName.TupleFind("opengl");
  if (0 != (HTuple(Indices!=-1).TupleAnd(Indices!=HTuple())))
  {
    ExpTmpLocalVar_gUsesOpenGL = ((const HTuple&)GenParamValue)[HTuple(Indices[0])];
    ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
    GenParamName = GenParamName.TupleRemove(Indices);
    GenParamValue = GenParamValue.TupleRemove(Indices);
    if (0 != (HTuple(ExpGetGlobalVar_gUsesOpenGL()!=HTuple("true")).TupleAnd(ExpGetGlobalVar_gUsesOpenGL()!=HTuple("false"))))
    {
      //Wrong parameter value: Only 'true' and 'false' are allowed
      throw HalconCpp::HException("Wrong value for parameter 'opengl' (must be either 'true' or 'false')");
    }
  }
  if (0 != (ExpGetGlobalVar_gUsesOpenGL()==HTuple("true")))
  {
    GetSystem("opengl_info", &OpenGLInfo);
    if (0 != (OpenGLInfo==HTuple("No OpenGL support included.")))
    {
      ExpTmpLocalVar_gUsesOpenGL = "false";
      ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
    }
    else
    {
      GenObjectModel3dFromPoints(0, 0, 0, &DummyObjectModel3D);
      CreateScene3d(&Scene3DTest);
      AddScene3dCamera(Scene3DTest, CamParam, &CameraIndexTest);
      determine_optimum_pose_distance(DummyObjectModel3D, CamParam, 0.9, ((((((HTuple(0).Append(0)).Append(0)).Append(0)).Append(0)).Append(0)).Append(0)),
          &PoseTest);
      AddScene3dInstance(Scene3DTest, DummyObjectModel3D, PoseTest, &InstanceIndexTest);
      try
      {
        DisplayScene3d(WindowHandleBuffer, Scene3DTest, InstanceIndexTest);
      }
      // catch (Exception)
      catch (HalconCpp::HException &HDevExpDefaultException)
      {
        HDevExpDefaultException.ToHTuple(&Exception);
        ExpTmpLocalVar_gUsesOpenGL = "false";
        ExpSetGlobalVar_gUsesOpenGL(ExpTmpLocalVar_gUsesOpenGL);
      }
      ClearScene3d(Scene3DTest);
      ClearObjectModel3d(DummyObjectModel3D);
    }
  }
  //
  //Compute the trackball
  MinImageSize = (Width.TupleConcat(Height)).TupleMin();
  TrackballRadiusPixel = (TrackballSize*MinImageSize)/2.0;
  //
  //Measure the text extents for the continue button in the
  //graphics window
  GetStringExtents(WindowHandleBuffer, ExpGetGlobalVar_gTerminationButtonLabel()+"  ",
      &Ascent, &Descent, &TextWidth, &TextHeight);
  //
  //Store background image
  if (0 != (DispBackground==HTuple("false")))
  {
    ClearWindow(WindowHandle);
  }
  DumpWindowImage(&Image, WindowHandle);
  //Special treatment for color background images necessary
  CountChannels(Image, &NumChannels);
  ColorImage = NumChannels==3;
  //
  CreateScene3d(&Scene3D);
  AddScene3dCamera(Scene3D, CamParam, &CameraIndex);
  AddScene3dInstance(Scene3D, ObjectModel3D, Poses, &AllInstances);
  //Always set 'disp_background' to true,  because it is handled explicitely
  //in this procedure (see above)
  SetScene3dParam(Scene3D, "disp_background", "true");
  //Check if we have to set light specific parameters
  SetLight = GenParamName.TupleRegexpTest("light_");
  if (0 != SetLight)
  {
    //set position of light source
    Indices = GenParamName.TupleFind("light_position");
    if (0 != (HTuple(Indices!=-1).TupleAnd(Indices!=HTuple())))
    {
      //If multiple light positions are given, use the last one
      LightParam = (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])]).TupleSplit(", ")).TupleNumber();
      if (0 != ((LightParam.TupleLength())!=4))
      {
        throw HalconCpp::HException("light_position must be given as a string that contains four space separated floating point numbers");
      }
      LightPosition = LightParam.TupleSelectRange(0,2);
      LightKind = "point_light";
      if (0 != (HTuple(LightParam[3])==0))
      {
        LightKind = "directional_light";
      }
      //Currently, only one light source is supported
      RemoveScene3dLight(Scene3D, 0);
      AddScene3dLight(Scene3D, LightPosition, LightKind, &LightIndex);
      TupleRemove(GenParamName, Indices, &GenParamName);
      TupleRemove(GenParamValue, Indices, &GenParamValue);
    }
    //set ambient part of light source
    Indices = GenParamName.TupleFind("light_ambient");
    if (0 != (HTuple(Indices!=-1).TupleAnd(Indices!=HTuple())))
    {
      //If the ambient part is set multiple times, use the last setting
      LightParam = (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])]).TupleSplit(", ")).TupleNumber();
      if (0 != ((LightParam.TupleLength())<3))
      {
        throw HalconCpp::HException("light_ambient must be given as a string that contains three space separated floating point numbers");
      }
      SetScene3dLightParam(Scene3D, 0, "ambient", LightParam.TupleSelectRange(0,2));
      TupleRemove(GenParamName, Indices, &GenParamName);
      TupleRemove(GenParamValue, Indices, &GenParamValue);
    }
    //set diffuse part of light source
    Indices = GenParamName.TupleFind("light_diffuse");
    if (0 != (HTuple(Indices!=-1).TupleAnd(Indices!=HTuple())))
    {
      //If the diffuse part is set multiple times, use the last setting
      LightParam = (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])]).TupleSplit(", ")).TupleNumber();
      if (0 != ((LightParam.TupleLength())<3))
      {
        throw HalconCpp::HException("light_diffuse must be given as a string that contains three space separated floating point numbers");
      }
      SetScene3dLightParam(Scene3D, 0, "diffuse", LightParam.TupleSelectRange(0,2));
      TupleRemove(GenParamName, Indices, &GenParamName);
      TupleRemove(GenParamValue, Indices, &GenParamValue);
    }
  }
  //
  //Handle persistence parameters separately because persistence will
  //only be activated immediately before leaving the visualization
  //procedure
  PersistenceParamName = HTuple();
  PersistenceParamValue = HTuple();
  //set position of light source
  Indices = GenParamName.TupleFind("object_index_persistence");
  if (0 != (HTuple(Indices!=-1).TupleAnd(Indices!=HTuple())))
  {
    if (0 != (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])])==HTuple("true")))
    {
      PersistenceParamName = PersistenceParamName.TupleConcat("object_index_persistence");
      PersistenceParamValue = PersistenceParamValue.TupleConcat("true");
    }
    else if (0 != (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])])==HTuple("false")))
    {
    }
    else
    {
      throw HalconCpp::HException("Wrong value for parameter 'object_index_persistence' (must be either 'true' or 'false')");
    }
    TupleRemove(GenParamName, Indices, &GenParamName);
    TupleRemove(GenParamValue, Indices, &GenParamValue);
  }
  Indices = GenParamName.TupleFind("depth_persistence");
  if (0 != (HTuple(Indices!=-1).TupleAnd(Indices!=HTuple())))
  {
    if (0 != (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])])==HTuple("true")))
    {
      PersistenceParamName = PersistenceParamName.TupleConcat("depth_persistence");
      PersistenceParamValue = PersistenceParamValue.TupleConcat("true");
    }
    else if (0 != (HTuple(GenParamValue[HTuple(Indices[(Indices.TupleLength())-1])])==HTuple("false")))
    {
    }
    else
    {
      throw HalconCpp::HException("Wrong value for parameter 'depth_persistence' (must be either 'true' or 'false')");
    }
    TupleRemove(GenParamName, Indices, &GenParamName);
    TupleRemove(GenParamValue, Indices, &GenParamValue);
  }
  //
  //Parse the generic parameters
  //- First, all parameters that are understood by set_scene_3d_instance_param
  GetParamInfo("set_scene_3d_param", "GenParamName", "value_list", &ValueListSS3P);
  GetParamInfo("set_scene_3d_instance_param", "GenParamName", "value_list", &ValueListSS3IP);
  AlphaOrig = HTuple(NumModels,1);
  UsedParamMask = HTuple(GenParamName.TupleLength(),0);
  {
  HTuple end_val371 = (GenParamName.TupleLength())-1;
  HTuple step_val371 = 1;
  for (I=0; I.Continue(end_val371, step_val371); I += step_val371)
  {
    ParamName = ((const HTuple&)GenParamName)[I];
    ParamValue = ((const HTuple&)GenParamValue)[I];
    //Check if this parameter is understood by set_scene_3d_param
    UseParam = ValueListSS3P.TupleRegexpTest(("^"+ParamName)+"$");
    if (0 != UseParam)
    {
      try
      {
        SetScene3dParam(Scene3D, ParamName, ParamValue);
      }
      // catch (Exception)
      catch (HalconCpp::HException &HDevExpDefaultException)
      {
        HDevExpDefaultException.ToHTuple(&Exception);
        if (0 != (HTuple(HTuple(Exception[0])==1204).TupleOr(HTuple(Exception[0])==1304)))
        {
          throw HalconCpp::HException((("Wrong type or value for parameter "+ParamName)+": ")+ParamValue);
        }
        else
        {
          throw HalconCpp::HException(Exception);
        }
      }
      UsedParamMask[I] = 1;
      if (0 != (ParamName==HTuple("alpha")))
      {
        AlphaOrig = HTuple(NumModels,ParamValue);
      }
      continue;
    }
    //Check if it is a parameter that is valid for only one instance
    //and therefore can be set only with set_scene_3d_instance_param
    ParamNameTrunk = ParamName.TupleRegexpReplace("_\\d+$","");
    UseParam = ValueListSS3IP.TupleRegexpTest(("^"+ParamNameTrunk)+"$");
    if (0 != UseParam)
    {
      Instance = (ParamName.TupleRegexpReplace(("^"+ParamNameTrunk)+"_(\\d+)$","$1")).TupleNumber();
      if (0 != (HTuple(Instance<0).TupleOr(Instance>(NumModels-1))))
      {
        throw HalconCpp::HException(("Parameter "+ParamName)+" refers to a non existing 3D object model");
      }
      try
      {
        SetScene3dInstanceParam(Scene3D, Instance, ParamNameTrunk, ParamValue);
      }
      // catch (Exception)
      catch (HalconCpp::HException &HDevExpDefaultException)
      {
        HDevExpDefaultException.ToHTuple(&Exception);
        if (0 != (HTuple(HTuple(Exception[0])==1204).TupleOr(HTuple(Exception[0])==1304)))
        {
          throw HalconCpp::HException((("Wrong type or value for parameter "+ParamName)+": ")+ParamValue);
        }
        else
        {
          throw HalconCpp::HException(Exception);
        }
      }
      UsedParamMask[I] = 1;
      if (0 != (ParamNameTrunk==HTuple("alpha")))
      {
        AlphaOrig[Instance] = ParamValue;
      }
      continue;
    }
  }
  }
  //
  //Check if there are remaining parameters
  if (0 != ((GenParamName.TupleLength())>0))
  {
    GenParamNameRemaining = GenParamName.TupleSelectMask(UsedParamMask.TupleNot());
    GenParamValueRemaining = GenParamValue.TupleSelectMask(UsedParamMask.TupleNot());
    if (0 != (GenParamNameRemaining!=HTuple()))
    {
      throw HalconCpp::HException("Parameters that cannot be handled: "+((((GenParamNameRemaining+" := ")+GenParamValueRemaining)+", ").TupleSum()));
    }
  }
  //
  //Start the visualization loop
  PoseToHomMat3d(Poses.TupleSelectRange(0,6), &HomMat3D);
  AffineTransPoint3d(HomMat3D, HTuple(Center[0]), HTuple(Center[1]), HTuple(Center[2]),
      &Qx, &Qy, &Qz);
  TBCenter.Clear();
  TBCenter.Append(Qx);
  TBCenter.Append(Qy);
  TBCenter.Append(Qz);
  TBSize = (0.5+((0.5*(SelectedObject.TupleSum()))/NumModels))*TrackballRadiusPixel;
  ButtonHold = 0;
  while (0 != 1)
  {
    VisualizeTB = (SelectedObject.TupleMax())!=0;
    MaxIndex = ((HTuple(ObjectModel3D.TupleLength()).TupleConcat(MaxNumModels)).TupleMin())-1;
    //Set trackball fixed in the center of the window
    TrackballCenterRow = Height/2;
    TrackballCenterCol = Width/2;
    if (0 != (WindowCenteredRotation==1))
    {
      try
      {
        get_trackball_center_fixed(SelectedObject.TupleSelectRange(0,MaxIndex),
            TrackballCenterRow, TrackballCenterCol, TrackballRadiusPixel,
            Scene3D, ObjectModel3D.TupleSelectRange(0,MaxIndex), Poses.TupleSelectRange(0,((MaxIndex+1)*7)-1),
            WindowHandleBuffer, CamParam, GenParamName, GenParamValue,
            &TBCenter, &TBSize);
      }
      // catch (Exception)
      catch (HalconCpp::HException &HDevExpDefaultException)
      {
        HDevExpDefaultException.ToHTuple(&Exception);
        disp_message(WindowHandle, "Surface inspection mode is not available.",
            "image", 5, 20, "red", "true");
        WindowCenteredRotation = 2;
        get_trackball_center(SelectedObject.TupleSelectRange(0,MaxIndex), TrackballRadiusPixel,
            ObjectModel3D.TupleSelectRange(0,MaxIndex), Poses.TupleSelectRange(0,((MaxIndex+1)*7)-1),
            &TBCenter, &TBSize);
        WaitSeconds(1);
      }
    }
    else
    {
      get_trackball_center(SelectedObject.TupleSelectRange(0,MaxIndex), TrackballRadiusPixel,
          ObjectModel3D.TupleSelectRange(0,MaxIndex), Poses.TupleSelectRange(0,((MaxIndex+1)*7)-1),
          &TBCenter, &TBSize);
    }
    dump_image_output(Image, WindowHandleBuffer, Scene3D, AlphaOrig,
        ObjectModel3D, GenParamName, GenParamValue, CamParam, Poses,
        ColorImage, Title, Information, Label, VisualizeTB, "true",
        TrackballCenterRow, TrackballCenterCol, TBSize, SelectedObject,
        WindowCenteredRotation, TBCenter);
    DumpWindowImage(&ImageDump, WindowHandleBuffer);
    HDevWindowStack::SetActive(WindowHandle);
    if (HDevWindowStack::IsOpen())
      DispObj(ImageDump, HDevWindowStack::GetActive());
    //
    //Check for mouse events
    GraphEvent = 0;
    Exit = 0;
    while (0 != 1)
    {
      //
      //Check graphic event
      try
      {
        GetMpositionSubPix(WindowHandle, &GraphButtonRow, &GraphButtonColumn,
            &GraphButton);
        if (0 != (GraphButton!=0))
        {
          if (0 != (HTuple(HTuple(HTuple(GraphButtonRow>((Height-TextHeight)-13)).TupleAnd(GraphButtonRow((Width-TextWidth)-13))).TupleAnd(GraphButtonColumn((Height-TextHeight)-13)).TupleAnd(GraphButtonRow((Width-TextWidth)-13))).TupleAnd(GraphButtonColumn0))
  {
    try
    {
      DispObjectModel3d(WindowHandle, ObjectModel3D, CamParam, Poses,
          (HTuple("disp_background").Append("alpha")).TupleConcat(PersistenceParamName),
          (HTuple("true").Append(0.0)).TupleConcat(PersistenceParamValue));
    }
    // catch (Exception)
    catch (HalconCpp::HException &HDevExpDefaultException)
    {
      HDevExpDefaultException.ToHTuple(&Exception);
      // stop(); only in hdevelop
    }
  }
  //
  //Compute the output pose
  if (0 != ExpGetGlobalVar_gIsSinglePose())
  {
    (*PoseOut) = Poses.TupleSelectRange(0,6);
  }
  else
  {
    (*PoseOut) = Poses;
  }
  //
  //Clean up
  SetSystem("clip_region", ClipRegion);
  // dev_set_preferences(...); only in hdevelop
  // dev_set_preferences(...); only in hdevelop
  // dev_set_preferences(...); only in hdevelop
  dump_image_output(Image, WindowHandleBuffer, Scene3D, AlphaOrig, ObjectModel3D,
      GenParamName, GenParamValue, CamParam, Poses, ColorImage, Title,
      HTuple(), Label, 0, "false", TrackballCenterRow, TrackballCenterCol,
      TBSize, SelectedObject, WindowCenteredRotation, TBCenter);
  DumpWindowImage(&ImageDump, WindowHandleBuffer);
  HDevWindowStack::SetActive(WindowHandle);
  if (HDevWindowStack::IsOpen())
    DispObj(ImageDump, HDevWindowStack::GetActive());
  CloseWindow(WindowHandleBuffer);
  SetPart(WindowHandle, WPRow1, WPColumn1, WPRow2, WPColumn2);
  ClearScene3d(Scene3D);
  return;
}


void fit_3d_plane_xyz1 (HTuple X, HTuple Y, HTuple Z, HTuple *Ox, HTuple *Oy,
    HTuple *Oz, HTuple *Nx, HTuple *Ny, HTuple *Nz, HTuple *MeanResidual)
{

  HTuple  Size, MatrixID_Mt, MatrixID_M;
  HTuple  MatrixID_U, MatrixID_S, MatrixID_V, x;
  HTuple  i, j, x1, SingularvaluesOfM, Indices;
  HTuple  N, MatrixID_N, MatrixID_MN, Distances;

  (*Ox) = HTuple();
  (*Oy) = HTuple();
  (*Oz) = HTuple();
  (*Nx) = HTuple();
  (*Ny) = HTuple();
  (*Nz) = HTuple();
  (*MeanResidual) = HTuple();

  //Test the size of X, Y and Z, and return if necessary
  Size = X.TupleLength();
  if (0 != (HTuple(HTuple(int(Size<3)).TupleOr(int(Size!=(Y.TupleLength())))).TupleOr(int(Size!=(Z.TupleLength())))))
  {
    return;
  }

  //Compute the coordinates of the centroid point.
  //计算质心点的坐标.求均值
  TupleMean(X, &(*Ox));
  TupleMean(Y, &(*Oy));
  TupleMean(Z, &(*Oz));

  //Setup the equation system as a matrix M and compute
  //its singular value decomposition. The singular vector
  //of M corresponding to its smallest singular value provides
  //the coordinates of the normal vector of the fitted plane.
  //将方程式系统设定为矩阵 m 并计算其奇异值分解。
  //对应于最小奇异值的 m 的奇异矢量提供了拟合平面法向量的坐标。
  //stop ()
  //之前281* 2  562 *3  1686
  //column := |X|
  CreateMatrix(3, X.TupleLength(), ((X-(*Ox)).TupleConcat(Y-(*Oy))).TupleConcat(Z-(*Oz)),
      &MatrixID_Mt);
  //get_full_matrix (MatrixID_Mt, MatrixID_Mt_value)
  //矩阵转置
  TransposeMatrix(MatrixID_Mt, &MatrixID_M);
  //矩阵SVD求解
  SvdMatrix(MatrixID_M, "reduced", "right", &MatrixID_U, &MatrixID_S, &MatrixID_V);

  //从矩阵内部找到对应的数值
  x = HTuple();

  for (i=0; i<=2; i+=1)
  {
    for (j=0; j<=2; j+=1)
    {
      GetValueMatrix(MatrixID_S, i, j, &x1);
      x = x.TupleConcat(x1);
    }
  }
  //stop ()
  //SingularvaluesOfM  奇异值
  GetValueMatrix(MatrixID_S, ((HTuple(0).Append(1)).Append(2)), ((HTuple(0).Append(1)).Append(2)),
      &SingularvaluesOfM);

  //对s 进行排序
  TupleSortIndex(SingularvaluesOfM, &Indices);

  //Test if more than one singular value of M is (nearly) equal
  //to zero. This indicates that the provided 3d points are
  //inappropriate to fit the plane (e.g. they are nearly
  //collinear or reduce to a single point).
  if (0 != (HTuple(int(HTuple(SingularvaluesOfM[HTuple(Indices[0])])<1e-9)).TupleAnd(int(HTuple(SingularvaluesOfM[HTuple(Indices[1])])<1e-9))))
  {
    return;
  }

  //Get coordinates of the normal vector to the fitted plane

  x = ((const HTuple&)Indices)[0];
  //*从矩阵内部找到对应的数值
  GetValueMatrix(MatrixID_V, ((HTuple(0).Append(1)).Append(2)), (HTuple(Indices[0]).TupleConcat(HTuple(Indices[0]))).TupleConcat(HTuple(Indices[0])),
      &N);
  //创建3 行  ,一列的矩阵
  CreateMatrix(3, 1, N, &MatrixID_N);
  (*Nx) = ((const HTuple&)N)[0];
  (*Ny) = ((const HTuple&)N)[1];
  (*Nz) = ((const HTuple&)N)[2];

  //Compute the mean residual distance between the 3d points
  //and the fitted plane, in order to guess the quality of
  //the fitted plane:
  //计算三维点与拟合平面之间的平均剩余距离,以估计拟合平面的质量
  //multiplication 乘法
  MultMatrix(MatrixID_M, MatrixID_N, "AB", &MatrixID_MN);

  //获取矩阵的所有值
  GetFullMatrix(MatrixID_MN, &Distances);
  Distances = Distances.TupleAbs();
  (*MeanResidual) = (Distances.TupleSum())/Size;

  //Clear the matrices used in the procedure
  ClearMatrix((((((MatrixID_MN.TupleConcat(MatrixID_N)).TupleConcat(MatrixID_V)).TupleConcat(MatrixID_S)).TupleConcat(MatrixID_U)).TupleConcat(MatrixID_M)).TupleConcat(MatrixID_Mt));
  return;
}

void gen_LightPlanePose (HTuple X, HTuple Y, HTuple Z, HTuple WindowHandle,
    HTuple *LightPlanePose)
{

  // Local iconic variables

  // Local control variables
  HTuple  Ox, Oy, Oz, Nx, Ny, Nz;
  HTuple  MeanResidual, String;

  //Fit the light plane in the 3D coordinates of the line
  //points computed previously. Note that this requires
  //nearly coplanar points. We must provide line points
  //recorded at -at least- two different heights, in order
  //to get an unambiguous solution. To obtain stable and
  //accurate results, acquire the light line points at the
  //bottom and at the top of the measurement volume.
  //在先前计算的线点的三维坐标中拟合光平面。 注意这几乎是共面的。
  //为了得到一个明确的解决方案,我们必须提供至少两个不同高度的线点记录。
  //为了获得稳定、准确的测量结果,需要获得测量体积顶部和底部的光线点。

  //把一个平面的点 所有全部丢进去, 返回的就是 质心坐标和法向量,拟合的质量(其实均值)。
  //MeanResidual  作为平面度 测量。0.0954
  fit_3d_plane_xyz1(X, Y, Z, &Ox, &Oy, &Oz, &Nx, &Ny, &Nz,
      &MeanResidual);
  if (0 != (HTuple(HTuple(int((Nx.TupleLength())==0)).TupleOr(int((Ny.TupleLength())==0))).TupleOr(int((Nz.TupleLength())==0))))
  {
    disp_message(WindowHandle, HTuple("Too few 3d points have been provided to fit the light plane,\nor the points are (nearly) collinear!\nThe program will exit."),
        "window", 12, 12, "black", "true");
    return;
  }
  //if (MeanResidual > 8e-5)
    //disp_message (WindowHandle, 'The light plane could not be fitted accurately!\nThe mean residual distance between the 3d-points and the\nfitted plane is too high (' + (MeanResidual * 1000)$'.3' + 'mm). Please check the\nquality and the correctness of those points.\nThe program will exit!', 'window', 12, 21, 'black', 'true')
    //return ()

  //endif

  //Compute the light plane pose: this pose must be oriented
  //such that the plane defined by z=0 coincides with the
  //light plane.
  //计算 线的点 来拟合光平面。
  get_light_plane_pose(Ox, Oy, Oz, Nx, Ny, Nz, &(*LightPlanePose));
  if (0 != (int(((*LightPlanePose).TupleLength())!=7)))
  {
    disp_message(WindowHandle, "The pose of the light plane could not be\ndetermined. Please verify that the vector\npassed at input of the procedure\nget_light_plane_pose() is not null.\nThe program will exit!",
        "window", -1, -2, "black", "true");
    return;
  }
  String.Clear();
  String[0] = "LightPlanePose: ";
  String.Append(("  Tx    = "+(HTuple((*LightPlanePose)[0]).TupleString(".3")))+" m");
  String.Append(("  Ty    = "+(HTuple((*LightPlanePose)[1]).TupleString(".3")))+" m");
  String.Append(("  Tz    = "+(HTuple((*LightPlanePose)[2]).TupleString(".3")))+" m");
  String.Append(("  alpha = "+(HTuple((*LightPlanePose)[3]).TupleString(".4")))+//'°'
      "\241\343");
  String.Append(("  beta  = "+(HTuple((*LightPlanePose)[4]).TupleString(".4")))+//'°'
      "\241\343");
  String.Append(("  gamma = "+(HTuple((*LightPlanePose)[5]).TupleString(".4")))+//'°'
      "\241\343");
  String.Append("  type  = "+HTuple((*LightPlanePose)[6]));
  disp_message(WindowHandle, String, "window", 12, 12, "black", "true");
  //disp_continue_message(WindowHandle, "black", "true");
  return;
}


void get_light_plane_pose (HTuple OriginX, HTuple OriginY, HTuple OriginZ,
    HTuple NormalVectorX, HTuple NormalVectorY, HTuple NormalVectorZ, HTuple *LightPlanePose)
{

  // Local iconic variables

  // Local control variables
  HTuple  Norm, HomMat3DIdentity, Alpha;
  HTuple  HomMat3DRotateAlpha, N1x, N1y, N1z;
  HTuple  Beta, HomMat3DRotateBeta, HomMat3DTranslate;
  HTuple  HomMat3DTmp, HomMat3DWorldToLightplane;

  //This procedure determines a lightplane pose,
  //e.g. a pose whose plane defined by z=0 coincides
  //with the physical light plane.


  //这个过程决定了一个光平面的姿势,
  //例如一个由 z 0定义的平面与物理光平面一致的姿势。
  //stop ()
  //Test that the vector passed at input is not null
  //测试在输入处传递的向量是否为空
  (*LightPlanePose) = HTuple();
  Norm = ((NormalVectorX*NormalVectorX)+(NormalVectorY*NormalVectorY))+(NormalVectorZ*NormalVectorZ);
  if (0 != (int((Norm.TupleAbs())<1e-8)))
  {
    return;
  }

  //In order to compute a light-plane pose, we determine
  //two rotations which align the unit vector of the z-axis
  //to the normal vector of the light plane, when applied
  //successively. For example, we can compute the angles
  //Alpha (rotation around the x-axis) and Beta (subsequent
  //rotation around the y-axis) in this successive order.
  //(The rotation around the z-axis is arbitrarily set
  //to zero).

  //Determine the value of the angle Alpha and rotate the
  //normal vector to the plane y=0. This provides the
  //vector N1.
  //为了计算一个光平面的姿态,我们确定了两个旋转,使 z 轴的单位向量与光平面的法向量相一致,当连续施加时。
  //例如,我们可以计算角度 α (围绕 x 轴旋转)和 β (随后围绕 y 轴旋转)在这个连续的顺序。 (围绕 z 轴的旋转被任意设置为零)。
  //确定角 α 的值,并将正常向量旋转到平面 y 0。 它提供了向量 n1。

  HomMat3dIdentity(&HomMat3DIdentity);
  //NY NZ  反正切
  TupleAtan2(NormalVectorY, NormalVectorZ, &Alpha);
  HomMat3dRotate(HomMat3DIdentity, Alpha, "x", 0, 0, 0, &HomMat3DRotateAlpha);

  //将NX NY NZ  变换为 N1x, N1y, N1z 。
  AffineTransPoint3d(HomMat3DRotateAlpha, NormalVectorX, NormalVectorY,
      NormalVectorZ, &N1x, &N1y, &N1z);

  //Determine the value of the angle Beta by using the
  //coordinates of N1. Note that the rotation around the
  //y-axis with angle Beta is carried out in the counter
  //trigonometric direction, therefore we apply -Beta.
  //通过使用 n1的坐标来确定角 β 的值。 注意绕 y 轴的转动是沿着反三角方向进行的,因此我们应用-β。

  TupleAtan2(N1x, N1z, &Beta);
  HomMat3dRotate(HomMat3DIdentity, -Beta, "y", 0, 0, 0, &HomMat3DRotateBeta);

  //Create the LightPlanePose
  //1. HomMat3DIdentity  平移  ----》omMat3DTranslate
  HomMat3dTranslate(HomMat3DIdentity, -OriginX, -OriginY, -OriginZ, &HomMat3DTranslate);

  //2  omMat3DTranslate +  沿着 α 角 相乘----》HomMat3DTmp
  HomMat3dCompose(HomMat3DRotateAlpha, HomMat3DTranslate, &HomMat3DTmp);

  //3 HomMat3DTmp +沿着 β 角 相乘----》HomMat3DWorldToLightplane
  HomMat3dCompose(HomMat3DRotateBeta, HomMat3DTmp, &HomMat3DWorldToLightplane);

  //将齐次变换矩阵 转换为pose
  HomMat3dToPose(HomMat3DWorldToLightplane, &(*LightPlanePose));
  return;

}


void project_object_model_3d_lines_to_contour_xld (HObject *ho_IntersectionX, HTuple ObjectModel3DIntersection,
    HTuple CutPlanePose)
{

  // Local iconic variables

  // Local control variables
  HTuple  PoseInvert2, Diameter, Scale;
  HTuple  CamParam;

  //获取相交线的点的个数
  //get_object_model_3d_params (ObjectModel3DIntersection, 'num_points', Intersection_Value)

  if (HDevWindowStack::IsOpen())
    SetLineWidth(HDevWindowStack::GetActive(),1);
  if (HDevWindowStack::IsOpen())
    SetColor(HDevWindowStack::GetActive(),"yellow");
  if (HDevWindowStack::IsOpen())
    SetDraw(HDevWindowStack::GetActive(),"margin");
  //The inverted intersection plane pose is our projection pose
  PoseInvert(CutPlanePose, &PoseInvert2);
  //Make sure, the projection plane lies in front of the camera
  GetObjectModel3dParams(ObjectModel3DIntersection, "diameter_axis_aligned_bounding_box",
      &Diameter);
  //+Diameter
  PoseInvert2[2] = HTuple(PoseInvert2[2])+Diameter;
  //Use a parallel projection to achieve the desired scaling (default 1:1)
  Scale = 1;
  CamParam.Clear();
  CamParam[0] = 0;
  CamParam[1] = 0;
  CamParam.Append(1.0/Scale);
  CamParam.Append(1.0/Scale);
  CamParam.Append(0);
  CamParam.Append(0);
  CamParam.Append(440);
  CamParam.Append(440);
  //将3维相交线 ObjectModel3DIntersection  与 CamParam  ,PoseInvert2获取2维的xld轮廓线
  ProjectObjectModel3d(&(*ho_IntersectionX), ObjectModel3DIntersection, CamParam,
      PoseInvert2, "data", "lines");

  return;
}

//判断文件是否存在,如果不存在保存到日志,或者打印到窗口
bool isFileExist(QString fullFileName)
{
    QFileInfo fileInfo(fullFileName);
    if(fileInfo.isFile())
    {
        QString LogType="file = exsit";
        //WriteLog(LogType, fullFileName);
        return true;
    }
    else
    {
       //保存日志
        QString LogType="file not exsit";
        //WriteLog(LogType, fullFileName);
    }
    return false;
}

void GenSelfPointCloud (HTuple ObjectModel3DScene1, HTuple *ObjectModel3DScene)
{

  // Local control variables
  HTuple  ObjectConnected, GenParamValue;
  HTuple  Max, ObjectSelected;

  ConnectionObjectModel3d(ObjectModel3DScene1, "distance_3d", 1, &ObjectConnected);
  //获取点云个数的参数
  GetObjectModel3dParams(ObjectConnected, "num_points", &GenParamValue);
  //求取点云个数的最大值
  TupleMax(GenParamValue, &Max);
  //根据点云的个数完成筛选
  SelectObjectModel3d(ObjectConnected, "num_points", "and", 20000, Max+1,
      &ObjectSelected);
  //再联合  如果选取点云个数大于1
  UnionObjectModel3d(ObjectSelected, "points_surface", &(*ObjectModel3DScene));
  return;
}

void GenSelfKindsOfParameters (HTuple *DispPose, HTuple *GenParNames, HTuple *GenParValues,
    HTuple *Instructions, HTuple *CamParam)
{
  (*DispPose).Clear();
  (*DispPose)[0] = 249.253;
  (*DispPose)[1] = 57.6831;
  (*DispPose)[2] = 238.687;
  (*DispPose)[3] = 12.2041;
  (*DispPose)[4] = 332.36;
  (*DispPose)[5] = 111.077;
  (*DispPose)[6] = 0;
  (*GenParNames).Clear();
  (*GenParNames)[0] = "color_0";
  (*GenParNames)[1] = "alpha";
  (*GenParNames)[2] = "disp_pose";
  (*GenParValues).Clear();
  (*GenParValues)[0] = "cyan";
  (*GenParValues)[1] = 0.7;
  (*GenParValues)[2] = "false";
  (*Instructions)[0] = "Rotate: Left button";
  (*Instructions)[1] = "Zoom:   Shift + left button";
  (*Instructions)[2] = "Move:   Ctrl  + left button";
  (*CamParam).Clear();
  (*CamParam)[0] = 0.01;
  (*CamParam)[1] = 0;
  (*CamParam)[2] = 7e-6;
  (*CamParam)[3] = 7e-6;
  (*CamParam).Append(800/2);
  (*CamParam).Append(500/2);
  (*CamParam).Append(800);
  (*CamParam).Append(500);
  return;
}





你可能感兴趣的:(三维点云处理,c++,人工智能,计算机视觉,图像处理)