<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkChooserPainter.cxx

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

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

=========================================================================*/
#include "vtkChooserPainter.h"

#include "vtkCommand.h"
#include "vtkConfigure.h"
#include "vtkGarbageCollector.h"
#include "vtkInformation.h"
#include "vtkLinesPainter.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointsPainter.h"
#include "vtkPolyData.h"
#include "vtkPolygonsPainter.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkStandardPolyDataPainter.h"
#include "vtkTStripsPainter.h"

vtkStandardNewMacro(vtkChooserPainter);

vtkCxxSetObjectMacro(vtkChooserPainter, VertPainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, LinePainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, PolyPainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, StripPainter, vtkPolyDataPainter);

//-----------------------------------------------------------------------------
vtkChooserPainter::vtkChooserPainter()
{
  this->VertPainter = NULL;
  this->LinePainter = NULL;
  this->PolyPainter = NULL;
  this->StripPainter = NULL;
  this->LastRenderer = NULL;
  this->UseLinesPainterForWireframes = 0;
#if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA))
  /*
   * On some Macs, glPolygonMode(*,GL_LINE) does not render anything
   * for polys. To fix this, we use the GL_LINE_LOOP to render the polygons.
   */
  this->UseLinesPainterForWireframes = 1;
#endif
}

//-----------------------------------------------------------------------------
vtkChooserPainter::~vtkChooserPainter()
{

  if (this->VertPainter) this->VertPainter->Delete();
  if (this->LinePainter) this->LinePainter->Delete();
  if (this->PolyPainter) this->PolyPainter->Delete();
  if (this->StripPainter) this->StripPainter->Delete();
}

/*
//-----------------------------------------------------------------------------
void vtkChooserPainter::ReleaseGraphicsResources(vtkWindow* w)
{
  if (this->VertPainter)
    {
    this->VertPainter->ReleaseGraphicsResources(w);
    }
  if (this->LinePainter)
    {
    this->LinePainter->ReleaseGraphicsResources(w);
    }
  if (this->PolyPainter)
    {
    this->PolyPainter->ReleaseGraphicsResources(w);
    }
  if (this->StripPainter)
    {
    this->StripPainter->ReleaseGraphicsResources(w);
    }
  this->Superclass::ReleaseGraphicsResources(w);
}
*/
//-----------------------------------------------------------------------------
void vtkChooserPainter::ReportReferences(vtkGarbageCollector *collector)
{
  this->Superclass::ReportReferences(collector);

  vtkGarbageCollectorReport(collector, this->VertPainter, "Vert Painter");
  vtkGarbageCollectorReport(collector, this->LinePainter, "Line Painter");
  vtkGarbageCollectorReport(collector, this->PolyPainter, "Poly Painter");
  vtkGarbageCollectorReport(collector, this->StripPainter, "Strip Painter");
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::PrepareForRendering(vtkRenderer* ren, vtkActor* actor)
{
  // Ensure that the renderer chain is up-to-date.
  if (this->PaintersChoiceTime < this->MTime ||
    this->PaintersChoiceTime < this->Information->GetMTime() ||
    this->LastRenderer != ren ||
    this->PaintersChoiceTime < this->GetInput()->GetMTime())
    {
    this->LastRenderer = ren;
    // Choose the painters.
    this->ChoosePainters(ren, actor);
    // Pass them the information and poly data we have.
    this->UpdateChoosenPainters();
    this->PaintersChoiceTime.Modified();
    }
  this->Superclass::PrepareForRendering(ren, actor);
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::UpdateChoosenPainters()
{
  if (this->VertPainter)
    {
    this->PassInformation(this->VertPainter);
    }
  if (this->LinePainter)
    {
    this->PassInformation(this->LinePainter);
    }
  if (this->PolyPainter)
    {
    this->PassInformation(this->PolyPainter);
    }
  if (this->StripPainter)
    {
    this->PassInformation(this->StripPainter);
    }
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::ChoosePainters(vtkRenderer *renderer, vtkActor* actor)
{
  const char *vertpaintertype;
  const char *linepaintertype;
  const char *polypaintertype;
  const char *strippaintertype;

  vtkPolyDataPainter* painter;

  this->SelectPainters(renderer, actor, vertpaintertype, linepaintertype,
                       polypaintertype, strippaintertype);
  vtkDebugMacro(<< "Selected " << vertpaintertype << ", "
                << linepaintertype << ", " << polypaintertype << ", "
                << strippaintertype);

  if (!this->VertPainter || !this->VertPainter->IsA(vertpaintertype))
    {
    painter = this->CreatePainter(vertpaintertype);
    if (painter)
      {
      this->SetVertPainter(painter);
      painter->Delete();
      vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
      painter->SetDelegatePainter(sp);
      sp->Delete();
      }
    }

  if (!this->LinePainter || !this->LinePainter->IsA(linepaintertype))
    {
    if (strcmp(vertpaintertype, linepaintertype) == 0)
      {
      this->SetLinePainter(this->VertPainter);
      }
    else
      {
      painter = this->CreatePainter(linepaintertype);
      if (painter)
        {
        this->SetLinePainter(painter);
        painter->Delete();
        vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
        painter->SetDelegatePainter(sp);
        sp->Delete();
        }
      }
    }

  if (!this->PolyPainter || !this->PolyPainter->IsA(polypaintertype))
    {
    if (strcmp(vertpaintertype, polypaintertype) == 0)
      {
      this->SetPolyPainter(this->VertPainter);
      }
    else if (strcmp(linepaintertype, polypaintertype) == 0)
      {
      this->SetPolyPainter(this->LinePainter);
      }
    else
      {
      painter = this->CreatePainter(polypaintertype);
      if (painter)
        {
        this->SetPolyPainter(painter);
        painter->Delete();
        vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
        painter->SetDelegatePainter(sp);
        sp->Delete();
        }
      }
    }

  if (!this->StripPainter || !this->StripPainter->IsA(strippaintertype))
    {
    if (strcmp(vertpaintertype, strippaintertype) == 0)
      {
      this->SetStripPainter(this->VertPainter);
      }
    else if (strcmp(linepaintertype, strippaintertype) == 0)
      {
      this->SetStripPainter(this->LinePainter);
      }
    else if (strcmp(polypaintertype, strippaintertype) == 0)
      {
      this->SetStripPainter(this->PolyPainter);
      }
    else
      {
      painter = this->CreatePainter(strippaintertype);
      if (painter)
        {
        this->SetStripPainter(painter);
        painter->Delete();
        vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
        painter->SetDelegatePainter(sp);
        sp->Delete();
        }
      }
    }
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::SelectPainters(vtkRenderer *vtkNotUsed(renderer),
    vtkActor* vtkNotUsed(actor), const char *&vertptype, const char *&lineptype,
    const char *&polyptype, const char *&stripptype)
{
  vertptype = "vtkPointsPainter";
  lineptype = "vtkLinesPainter";
  polyptype = "vtkPolygonsPainter";
  stripptype = "vtkTStripsPainter";
}

//-----------------------------------------------------------------------------
vtkPolyDataPainter* vtkChooserPainter::CreatePainter(const char *paintertype)
{
  vtkPolyDataPainter* p = 0;
  if (strcmp(paintertype, "vtkPointsPainter") == 0)
    {
    p = vtkPointsPainter::New();
    }
  else if (strcmp(paintertype, "vtkLinesPainter") == 0)
    {
    p = vtkLinesPainter::New();
    }
  else if (strcmp(paintertype, "vtkPolygonsPainter") == 0)
    {
    p = vtkPolygonsPainter::New();
    }
  else if (strcmp(paintertype, "vtkTStripsPainter") == 0)
    {
    p = vtkTStripsPainter::New();
    }
  else
    {
    vtkErrorMacro("Cannot create painter " << paintertype);
    return 0;
    }
  this->ObserverPainterProgress(p);
  return p;
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::RenderInternal(vtkRenderer* renderer, vtkActor* actor,
                                       unsigned long typeflags,
                                       bool forceCompileOnly)
{
  vtkPolyData* pdInput = this->GetInputAsPolyData();
  vtkIdType numVerts = pdInput->GetNumberOfVerts();
  vtkIdType numLines = pdInput->GetNumberOfLines();
  vtkIdType numPolys = pdInput->GetNumberOfPolys();
  vtkIdType numStrips = pdInput->GetNumberOfStrips();

  vtkIdType total_cells = (typeflags & vtkPainter::VERTS)?
    pdInput->GetNumberOfVerts() : 0;
  total_cells += (typeflags & vtkPainter::LINES)?
    pdInput->GetNumberOfLines() : 0;
  total_cells += (typeflags & vtkPainter::POLYS)?
    pdInput->GetNumberOfPolys() : 0;
  total_cells += (typeflags & vtkPainter::STRIPS)?
    pdInput->GetNumberOfStrips() : 0;

  if (total_cells == 0)
    {
    // nothing to render.
    return;
    }

  this->ProgressOffset = 0.0;
  this->TimeToDraw = 0.0;
  if ((typeflags & vtkPainter::VERTS) && numVerts>0 )
    {
    //cout << this << "Verts" << endl;
    this->ProgressScaleFactor = static_cast<double>(numVerts)/total_cells;
    this->VertPainter->Render(renderer, actor, vtkPainter::VERTS,
                              forceCompileOnly);
    this->TimeToDraw += this->VertPainter->GetTimeToDraw();
    this->ProgressOffset += this->ProgressScaleFactor;
    }

  if ((typeflags & vtkPainter::LINES) && numLines>0 )
    {
    //cout << this << "Lines" << endl;
    this->ProgressScaleFactor = static_cast<double>(numLines)/total_cells;
    this->LinePainter->Render(renderer, actor, vtkPainter::LINES,
                              forceCompileOnly);
    this->TimeToDraw += this->LinePainter->GetTimeToDraw();
    this->ProgressOffset += this->ProgressScaleFactor;
    }

  if ((typeflags & vtkPainter::POLYS) && numPolys>0 )
    {
    //cout << this << "Polys" << endl;
    this->ProgressScaleFactor = static_cast<double>(numPolys)/total_cells;
    if (   this->UseLinesPainterForWireframes
        && (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)
        && !actor->GetProperty()->GetBackfaceCulling()
        && !actor->GetProperty()->GetFrontfaceCulling()
        && !this->GetInputAsPolyData()->GetPointData()->GetAttribute(
                                               vtkDataSetAttributes::EDGEFLAG) )
      {
      this->LinePainter->Render(renderer, actor, vtkPainter::POLYS,
        forceCompileOnly);
      this->TimeToDraw += this->LinePainter->GetTimeToDraw();
      }
    else
      {
      this->PolyPainter->Render(renderer, actor, vtkPainter::POLYS,
        forceCompileOnly);
      this->TimeToDraw += this->PolyPainter->GetTimeToDraw();
      }
    this->ProgressOffset += this->ProgressScaleFactor;
    }

  if ((typeflags & vtkPainter::STRIPS) && numStrips>0 )
    {
    //cout << this << "Strips" << endl;
    this->ProgressScaleFactor = static_cast<double>(numStrips)/total_cells;
    this->StripPainter->Render(renderer, actor, vtkPainter::STRIPS,
                               forceCompileOnly);
    this->TimeToDraw += this->StripPainter->GetTimeToDraw();
    }
  this->Superclass::RenderInternal(renderer, actor, typeflags,forceCompileOnly);
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "VertPainter: " << this->VertPainter << endl;
  os << indent << "LinePainter: " << this->LinePainter << endl;
  os << indent << "PolyPainter: " << this->PolyPainter << endl;
  os << indent << "StripPainter: " << this->StripPainter << endl;
  os << indent << "UseLinesPainterForWireframes: "
    << this->UseLinesPainterForWireframes << endl;
}
<commit_msg>fix for failing mac dashbaords<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkChooserPainter.cxx

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

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

=========================================================================*/
#include "vtkChooserPainter.h"

#include "vtkCommand.h"
#include "vtkConfigure.h"
#include "vtkGarbageCollector.h"
#include "vtkInformation.h"
#include "vtkLinesPainter.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointsPainter.h"
#include "vtkPolyData.h"
#include "vtkPolygonsPainter.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkStandardPolyDataPainter.h"
#include "vtkTStripsPainter.h"

vtkStandardNewMacro(vtkChooserPainter);

vtkCxxSetObjectMacro(vtkChooserPainter, VertPainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, LinePainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, PolyPainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, StripPainter, vtkPolyDataPainter);

//-----------------------------------------------------------------------------
vtkChooserPainter::vtkChooserPainter()
{
  this->VertPainter = NULL;
  this->LinePainter = NULL;
  this->PolyPainter = NULL;
  this->StripPainter = NULL;
  this->LastRenderer = NULL;
  this->UseLinesPainterForWireframes = 0;
#if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA))
  /*
   * On some Macs, glPolygonMode(*,GL_LINE) does not render anything
   * for polys. To fix this, we use the GL_LINE_LOOP to render the polygons.
   */
//  this->UseLinesPainterForWireframes = 1;
#endif
}

//-----------------------------------------------------------------------------
vtkChooserPainter::~vtkChooserPainter()
{

  if (this->VertPainter) this->VertPainter->Delete();
  if (this->LinePainter) this->LinePainter->Delete();
  if (this->PolyPainter) this->PolyPainter->Delete();
  if (this->StripPainter) this->StripPainter->Delete();
}

/*
//-----------------------------------------------------------------------------
void vtkChooserPainter::ReleaseGraphicsResources(vtkWindow* w)
{
  if (this->VertPainter)
    {
    this->VertPainter->ReleaseGraphicsResources(w);
    }
  if (this->LinePainter)
    {
    this->LinePainter->ReleaseGraphicsResources(w);
    }
  if (this->PolyPainter)
    {
    this->PolyPainter->ReleaseGraphicsResources(w);
    }
  if (this->StripPainter)
    {
    this->StripPainter->ReleaseGraphicsResources(w);
    }
  this->Superclass::ReleaseGraphicsResources(w);
}
*/
//-----------------------------------------------------------------------------
void vtkChooserPainter::ReportReferences(vtkGarbageCollector *collector)
{
  this->Superclass::ReportReferences(collector);

  vtkGarbageCollectorReport(collector, this->VertPainter, "Vert Painter");
  vtkGarbageCollectorReport(collector, this->LinePainter, "Line Painter");
  vtkGarbageCollectorReport(collector, this->PolyPainter, "Poly Painter");
  vtkGarbageCollectorReport(collector, this->StripPainter, "Strip Painter");
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::PrepareForRendering(vtkRenderer* ren, vtkActor* actor)
{
  // Ensure that the renderer chain is up-to-date.
  if (this->PaintersChoiceTime < this->MTime ||
    this->PaintersChoiceTime < this->Information->GetMTime() ||
    this->LastRenderer != ren ||
    this->PaintersChoiceTime < this->GetInput()->GetMTime())
    {
    this->LastRenderer = ren;
    // Choose the painters.
    this->ChoosePainters(ren, actor);
    // Pass them the information and poly data we have.
    this->UpdateChoosenPainters();
    this->PaintersChoiceTime.Modified();
    }
  this->Superclass::PrepareForRendering(ren, actor);
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::UpdateChoosenPainters()
{
  if (this->VertPainter)
    {
    this->PassInformation(this->VertPainter);
    }
  if (this->LinePainter)
    {
    this->PassInformation(this->LinePainter);
    }
  if (this->PolyPainter)
    {
    this->PassInformation(this->PolyPainter);
    }
  if (this->StripPainter)
    {
    this->PassInformation(this->StripPainter);
    }
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::ChoosePainters(vtkRenderer *renderer, vtkActor* actor)
{
  const char *vertpaintertype;
  const char *linepaintertype;
  const char *polypaintertype;
  const char *strippaintertype;

  vtkPolyDataPainter* painter;

  this->SelectPainters(renderer, actor, vertpaintertype, linepaintertype,
                       polypaintertype, strippaintertype);
  vtkDebugMacro(<< "Selected " << vertpaintertype << ", "
                << linepaintertype << ", " << polypaintertype << ", "
                << strippaintertype);

  if (!this->VertPainter || !this->VertPainter->IsA(vertpaintertype))
    {
    painter = this->CreatePainter(vertpaintertype);
    if (painter)
      {
      this->SetVertPainter(painter);
      painter->Delete();
      vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
      painter->SetDelegatePainter(sp);
      sp->Delete();
      }
    }

  if (!this->LinePainter || !this->LinePainter->IsA(linepaintertype))
    {
    if (strcmp(vertpaintertype, linepaintertype) == 0)
      {
      this->SetLinePainter(this->VertPainter);
      }
    else
      {
      painter = this->CreatePainter(linepaintertype);
      if (painter)
        {
        this->SetLinePainter(painter);
        painter->Delete();
        vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
        painter->SetDelegatePainter(sp);
        sp->Delete();
        }
      }
    }

  if (!this->PolyPainter || !this->PolyPainter->IsA(polypaintertype))
    {
    if (strcmp(vertpaintertype, polypaintertype) == 0)
      {
      this->SetPolyPainter(this->VertPainter);
      }
    else if (strcmp(linepaintertype, polypaintertype) == 0)
      {
      this->SetPolyPainter(this->LinePainter);
      }
    else
      {
      painter = this->CreatePainter(polypaintertype);
      if (painter)
        {
        this->SetPolyPainter(painter);
        painter->Delete();
        vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
        painter->SetDelegatePainter(sp);
        sp->Delete();
        }
      }
    }

  if (!this->StripPainter || !this->StripPainter->IsA(strippaintertype))
    {
    if (strcmp(vertpaintertype, strippaintertype) == 0)
      {
      this->SetStripPainter(this->VertPainter);
      }
    else if (strcmp(linepaintertype, strippaintertype) == 0)
      {
      this->SetStripPainter(this->LinePainter);
      }
    else if (strcmp(polypaintertype, strippaintertype) == 0)
      {
      this->SetStripPainter(this->PolyPainter);
      }
    else
      {
      painter = this->CreatePainter(strippaintertype);
      if (painter)
        {
        this->SetStripPainter(painter);
        painter->Delete();
        vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
        painter->SetDelegatePainter(sp);
        sp->Delete();
        }
      }
    }
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::SelectPainters(vtkRenderer *vtkNotUsed(renderer),
    vtkActor* vtkNotUsed(actor), const char *&vertptype, const char *&lineptype,
    const char *&polyptype, const char *&stripptype)
{
  vertptype = "vtkPointsPainter";
  lineptype = "vtkLinesPainter";
  polyptype = "vtkPolygonsPainter";
  stripptype = "vtkTStripsPainter";
}

//-----------------------------------------------------------------------------
vtkPolyDataPainter* vtkChooserPainter::CreatePainter(const char *paintertype)
{
  vtkPolyDataPainter* p = 0;
  if (strcmp(paintertype, "vtkPointsPainter") == 0)
    {
    p = vtkPointsPainter::New();
    }
  else if (strcmp(paintertype, "vtkLinesPainter") == 0)
    {
    p = vtkLinesPainter::New();
    }
  else if (strcmp(paintertype, "vtkPolygonsPainter") == 0)
    {
    p = vtkPolygonsPainter::New();
    }
  else if (strcmp(paintertype, "vtkTStripsPainter") == 0)
    {
    p = vtkTStripsPainter::New();
    }
  else
    {
    vtkErrorMacro("Cannot create painter " << paintertype);
    return 0;
    }
  this->ObserverPainterProgress(p);
  return p;
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::RenderInternal(vtkRenderer* renderer, vtkActor* actor,
                                       unsigned long typeflags,
                                       bool forceCompileOnly)
{
  vtkPolyData* pdInput = this->GetInputAsPolyData();
  vtkIdType numVerts = pdInput->GetNumberOfVerts();
  vtkIdType numLines = pdInput->GetNumberOfLines();
  vtkIdType numPolys = pdInput->GetNumberOfPolys();
  vtkIdType numStrips = pdInput->GetNumberOfStrips();

  vtkIdType total_cells = (typeflags & vtkPainter::VERTS)?
    pdInput->GetNumberOfVerts() : 0;
  total_cells += (typeflags & vtkPainter::LINES)?
    pdInput->GetNumberOfLines() : 0;
  total_cells += (typeflags & vtkPainter::POLYS)?
    pdInput->GetNumberOfPolys() : 0;
  total_cells += (typeflags & vtkPainter::STRIPS)?
    pdInput->GetNumberOfStrips() : 0;

  if (total_cells == 0)
    {
    // nothing to render.
    return;
    }

  this->ProgressOffset = 0.0;
  this->TimeToDraw = 0.0;
  if ((typeflags & vtkPainter::VERTS) && numVerts>0 )
    {
    //cout << this << "Verts" << endl;
    this->ProgressScaleFactor = static_cast<double>(numVerts)/total_cells;
    this->VertPainter->Render(renderer, actor, vtkPainter::VERTS,
                              forceCompileOnly);
    this->TimeToDraw += this->VertPainter->GetTimeToDraw();
    this->ProgressOffset += this->ProgressScaleFactor;
    }

  if ((typeflags & vtkPainter::LINES) && numLines>0 )
    {
    //cout << this << "Lines" << endl;
    this->ProgressScaleFactor = static_cast<double>(numLines)/total_cells;
    this->LinePainter->Render(renderer, actor, vtkPainter::LINES,
                              forceCompileOnly);
    this->TimeToDraw += this->LinePainter->GetTimeToDraw();
    this->ProgressOffset += this->ProgressScaleFactor;
    }

  if ((typeflags & vtkPainter::POLYS) && numPolys>0 )
    {
    //cout << this << "Polys" << endl;
    this->ProgressScaleFactor = static_cast<double>(numPolys)/total_cells;
    if (   this->UseLinesPainterForWireframes
        && (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)
        && !actor->GetProperty()->GetBackfaceCulling()
        && !actor->GetProperty()->GetFrontfaceCulling()
        && !this->GetInputAsPolyData()->GetPointData()->GetAttribute(
                                               vtkDataSetAttributes::EDGEFLAG) )
      {
      this->LinePainter->Render(renderer, actor, vtkPainter::POLYS,
        forceCompileOnly);
      this->TimeToDraw += this->LinePainter->GetTimeToDraw();
      }
    else
      {
      this->PolyPainter->Render(renderer, actor, vtkPainter::POLYS,
        forceCompileOnly);
      this->TimeToDraw += this->PolyPainter->GetTimeToDraw();
      }
    this->ProgressOffset += this->ProgressScaleFactor;
    }

  if ((typeflags & vtkPainter::STRIPS) && numStrips>0 )
    {
    //cout << this << "Strips" << endl;
    this->ProgressScaleFactor = static_cast<double>(numStrips)/total_cells;
    this->StripPainter->Render(renderer, actor, vtkPainter::STRIPS,
                               forceCompileOnly);
    this->TimeToDraw += this->StripPainter->GetTimeToDraw();
    }
  this->Superclass::RenderInternal(renderer, actor, typeflags,forceCompileOnly);
}

//-----------------------------------------------------------------------------
void vtkChooserPainter::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "VertPainter: " << this->VertPainter << endl;
  os << indent << "LinePainter: " << this->LinePainter << endl;
  os << indent << "PolyPainter: " << this->PolyPainter << endl;
  os << indent << "StripPainter: " << this->StripPainter << endl;
  os << indent << "UseLinesPainterForWireframes: "
    << this->UseLinesPainterForWireframes << endl;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLHardwareSupport.cxx

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

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

=========================================================================*/

#include "vtkOpenGLHardwareSupport.h"

#include "vtkObjectFactory.h"
#include "vtkOpenGL.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkgl.h"

vtkCxxRevisionMacro(vtkOpenGLHardwareSupport, "1.4");
vtkStandardNewMacro(vtkOpenGLHardwareSupport);

vtkCxxSetObjectMacro(vtkOpenGLHardwareSupport, ExtensionManager, vtkOpenGLExtensionManager);

// ----------------------------------------------------------------------------
vtkOpenGLHardwareSupport::vtkOpenGLHardwareSupport()
{
  this->ExtensionManager = NULL;
}

// ----------------------------------------------------------------------------
vtkOpenGLHardwareSupport::~vtkOpenGLHardwareSupport()
{
  this->SetExtensionManager(NULL);
}

// ----------------------------------------------------------------------------
int vtkOpenGLHardwareSupport::GetNumberOfFixedTextureUnits()
{
  if ( ! vtkgl::MultiTexCoord2d || ! vtkgl::ActiveTexture )
    {
    if(!this->ExtensionManagerSet())
      {
      vtkWarningMacro(<<"extension manager not set. Return 1.");
      return 1;
      }

    // multitexture is a core feature of OpenGL 1.3.
    // multitexture is an ARB extension of OpenGL 1.2.1
    int supports_GL_1_3 = this->ExtensionManager->ExtensionSupported( "GL_VERSION_1_3" );
    int supports_GL_1_2_1 = this->ExtensionManager->ExtensionSupported("GL_VERSION_1_2");
    int supports_ARB_mutlitexture =
      this->ExtensionManager->ExtensionSupported("GL_ARB_multitexture");

    if(supports_GL_1_3)
      {
      this->ExtensionManager->LoadExtension("GL_VERSION_1_3");
      }
    else if(supports_GL_1_2_1 && supports_ARB_mutlitexture)
      {
      this->ExtensionManager->LoadExtension("GL_VERSION_1_2");
      this->ExtensionManager->LoadCorePromotedExtension("GL_ARB_multitexture");
      }
    else
      {
      return 1;
      }
    }

  GLint numSupportedTextures = 1;
  glGetIntegerv(vtkgl::MAX_TEXTURE_UNITS, &numSupportedTextures);

  return numSupportedTextures;
}

// ----------------------------------------------------------------------------
// Description:
// Return the total number of texture image units accessible by a shader
// program.
int vtkOpenGLHardwareSupport::GetNumberOfTextureUnits()
{
  int result=1;
  // vtkgl::MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB is defined in
  // GL_ARB_vertex_shader
  // vtkgl::MAX_COMBINED_TEXTURE_IMAGE_UNITS is defined in OpenGL 2.0

  // test for a function defined both by GL_ARB_vertex_shader and OpenGL 2.0
  if(vtkgl::GetActiveAttrib==0)
    {
    if(!this->ExtensionManagerSet())
      {
      vtkWarningMacro(<<"extension manager not set. Return 1.");
      }
    else
      {
      bool supports_shaders=false;
      if(this->ExtensionManager->ExtensionSupported("GL_VERSION_2_0"))
        {
        this->ExtensionManager->LoadExtension("GL_VERSION_2_0");
        supports_shaders=true;
        }
      else
        {
        supports_shaders=
          this->ExtensionManager->ExtensionSupported("GL_ARB_vertex_shader");
        if(supports_shaders)
          {
          this->ExtensionManager->LoadCorePromotedExtension(
            "GL_ARB_vertex_shader");
          }
        }
      if(supports_shaders)
        {
        GLint value;
        glGetIntegerv(vtkgl::MAX_COMBINED_TEXTURE_IMAGE_UNITS,&value);
        result=static_cast<int>(value);
        }
      }
    }
  return result;
}

// ----------------------------------------------------------------------------
bool vtkOpenGLHardwareSupport::GetSupportsMultiTexturing()
{
  if ( ! vtkgl::MultiTexCoord2d || ! vtkgl::ActiveTexture )
    {
    if(!ExtensionManagerSet())
      {
      return false;
      }

    // multitexture is a core feature of OpenGL 1.3.
    // multitexture is an ARB extension of OpenGL 1.2.1
    int supports_GL_1_3 = this->ExtensionManager->ExtensionSupported( "GL_VERSION_1_3" );
    int supports_GL_1_2_1 = this->ExtensionManager->ExtensionSupported("GL_VERSION_1_2");
    int supports_ARB_mutlitexture =
      this->ExtensionManager->ExtensionSupported("GL_ARB_multitexture");

    if(supports_GL_1_3 || supports_GL_1_2_1 || supports_ARB_mutlitexture)
      {
      return true;
      }

    return false;
    }
  else
    {
    return true;
    }
}

//-----------------------------------------------------------------------------
void vtkOpenGLHardwareSupport::PrintSelf(ostream& os, vtkIndent indent)
{
  os << indent << this->ExtensionManager << endl;
  this->Superclass::PrintSelf(os,indent);
}

bool vtkOpenGLHardwareSupport::ExtensionManagerSet()
{
  if(!this->ExtensionManager)
    {
    vtkErrorMacro("" << this->GetClassName() << ": requires an ExtensionManager set.");
    return false;
    }
  if(!this->ExtensionManager->GetRenderWindow())
    {
    vtkErrorMacro("" << this->GetClassName() << ": requires an ExtensionManager with Render Window set.");
    return false;
    }
  return true;
}
<commit_msg>COMP:Fixed VS warning C4800.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLHardwareSupport.cxx

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

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

=========================================================================*/

#include "vtkOpenGLHardwareSupport.h"

#include "vtkObjectFactory.h"
#include "vtkOpenGL.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkgl.h"

vtkCxxRevisionMacro(vtkOpenGLHardwareSupport, "1.5");
vtkStandardNewMacro(vtkOpenGLHardwareSupport);

vtkCxxSetObjectMacro(vtkOpenGLHardwareSupport, ExtensionManager, vtkOpenGLExtensionManager);

// ----------------------------------------------------------------------------
vtkOpenGLHardwareSupport::vtkOpenGLHardwareSupport()
{
  this->ExtensionManager = NULL;
}

// ----------------------------------------------------------------------------
vtkOpenGLHardwareSupport::~vtkOpenGLHardwareSupport()
{
  this->SetExtensionManager(NULL);
}

// ----------------------------------------------------------------------------
int vtkOpenGLHardwareSupport::GetNumberOfFixedTextureUnits()
{
  if ( ! vtkgl::MultiTexCoord2d || ! vtkgl::ActiveTexture )
    {
    if(!this->ExtensionManagerSet())
      {
      vtkWarningMacro(<<"extension manager not set. Return 1.");
      return 1;
      }

    // multitexture is a core feature of OpenGL 1.3.
    // multitexture is an ARB extension of OpenGL 1.2.1
    int supports_GL_1_3 = this->ExtensionManager->ExtensionSupported( "GL_VERSION_1_3" );
    int supports_GL_1_2_1 = this->ExtensionManager->ExtensionSupported("GL_VERSION_1_2");
    int supports_ARB_mutlitexture =
      this->ExtensionManager->ExtensionSupported("GL_ARB_multitexture");

    if(supports_GL_1_3)
      {
      this->ExtensionManager->LoadExtension("GL_VERSION_1_3");
      }
    else if(supports_GL_1_2_1 && supports_ARB_mutlitexture)
      {
      this->ExtensionManager->LoadExtension("GL_VERSION_1_2");
      this->ExtensionManager->LoadCorePromotedExtension("GL_ARB_multitexture");
      }
    else
      {
      return 1;
      }
    }

  GLint numSupportedTextures = 1;
  glGetIntegerv(vtkgl::MAX_TEXTURE_UNITS, &numSupportedTextures);

  return numSupportedTextures;
}

// ----------------------------------------------------------------------------
// Description:
// Return the total number of texture image units accessible by a shader
// program.
int vtkOpenGLHardwareSupport::GetNumberOfTextureUnits()
{
  int result=1;
  // vtkgl::MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB is defined in
  // GL_ARB_vertex_shader
  // vtkgl::MAX_COMBINED_TEXTURE_IMAGE_UNITS is defined in OpenGL 2.0

  // test for a function defined both by GL_ARB_vertex_shader and OpenGL 2.0
  if(vtkgl::GetActiveAttrib==0)
    {
    if(!this->ExtensionManagerSet())
      {
      vtkWarningMacro(<<"extension manager not set. Return 1.");
      }
    else
      {
      bool supports_shaders=false;
      if(this->ExtensionManager->ExtensionSupported("GL_VERSION_2_0"))
        {
        this->ExtensionManager->LoadExtension("GL_VERSION_2_0");
        supports_shaders=true;
        }
      else
        {
        supports_shaders=
          this->ExtensionManager->ExtensionSupported("GL_ARB_vertex_shader")==1;
        if(supports_shaders)
          {
          this->ExtensionManager->LoadCorePromotedExtension(
            "GL_ARB_vertex_shader");
          }
        }
      if(supports_shaders)
        {
        GLint value;
        glGetIntegerv(vtkgl::MAX_COMBINED_TEXTURE_IMAGE_UNITS,&value);
        result=static_cast<int>(value);
        }
      }
    }
  return result;
}

// ----------------------------------------------------------------------------
bool vtkOpenGLHardwareSupport::GetSupportsMultiTexturing()
{
  if ( ! vtkgl::MultiTexCoord2d || ! vtkgl::ActiveTexture )
    {
    if(!ExtensionManagerSet())
      {
      return false;
      }

    // multitexture is a core feature of OpenGL 1.3.
    // multitexture is an ARB extension of OpenGL 1.2.1
    int supports_GL_1_3 = this->ExtensionManager->ExtensionSupported( "GL_VERSION_1_3" );
    int supports_GL_1_2_1 = this->ExtensionManager->ExtensionSupported("GL_VERSION_1_2");
    int supports_ARB_mutlitexture =
      this->ExtensionManager->ExtensionSupported("GL_ARB_multitexture");

    if(supports_GL_1_3 || supports_GL_1_2_1 || supports_ARB_mutlitexture)
      {
      return true;
      }

    return false;
    }
  else
    {
    return true;
    }
}

//-----------------------------------------------------------------------------
void vtkOpenGLHardwareSupport::PrintSelf(ostream& os, vtkIndent indent)
{
  os << indent << this->ExtensionManager << endl;
  this->Superclass::PrintSelf(os,indent);
}

bool vtkOpenGLHardwareSupport::ExtensionManagerSet()
{
  if(!this->ExtensionManager)
    {
    vtkErrorMacro("" << this->GetClassName() << ": requires an ExtensionManager set.");
    return false;
    }
  if(!this->ExtensionManager->GetRenderWindow())
    {
    vtkErrorMacro("" << this->GetClassName() << ": requires an ExtensionManager with Render Window set.");
    return false;
    }
  return true;
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCLuaScriptModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2013-01-02
//    @Module           :    NFCLuaScriptModule
//    @Desc             :
// -------------------------------------------------------------------------

#include "NFCLuaScriptModule.h"
#include "NFLuaScriptPlugin.h"
#include <assert.h>

bool NFCLuaScriptModule::Init()
{
	m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>("NFCKernelModule");
	m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>("NFCLogicClassModule");
	m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>("NFCElementInfoModule");

	assert(NULL != m_pKernelModule);
	assert(NULL != m_pLogicClassModule);
	assert(NULL != m_pElementInfoModule);

	Regisger();

	try
	{
		lw.dofile("script_init.lua");
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		assert(0);
	}

	//std::shared_ptr<NFILogicClass> pClass = m_pLogicClassModule->First();
	//while (pClass.get())
	//{
	//	std::shared_ptr<NFIComponent> pComponent = pClass->GetComponentManager()->First();
	//	while (pComponent.get())
	//	{
	//		if (!CheckCompomentStatus(pComponent->GetComponentName()))
	//		{
	//			assert(0);
	//		}

	//		pComponent = pClass->GetComponentManager()->Next();
	//	}

	//	pClass = m_pLogicClassModule->Next();
	//}
	if (!CheckCompomentStatus("Test"))
	{
		assert(0);
	}

	luacpp::call<void>(lw, "Init", (NFINT64)m_pKernelModule);

	return true;
}

bool NFCLuaScriptModule::AfterInit()
{
	luacpp::call<void>(lw, "AfterInit", (NFINT64)m_pKernelModule);

	//add all callback
	m_pKernelModule->ResgisterCommonPropertyEvent(this, &NFCLuaScriptModule::OnPropertyCommEvent);
	m_pKernelModule->ResgisterCommonRecordEvent(this, &NFCLuaScriptModule::OnRecordCommonEvent);
	m_pKernelModule->ResgisterCommonClassEvent(this, &NFCLuaScriptModule::OnClassCommonEvent);

	return true;
}

bool NFCLuaScriptModule::Shut()
{

	return true;
}

bool NFCLuaScriptModule::Execute()
{
	return true;
}

bool NFCLuaScriptModule::BeforeShut()
{
	//fflua.~fflua_t();
	return true;
}

int NFCLuaScriptModule::OnPropertyCommEvent(const NFGUID& self, const std::string& strPropertyName, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	DoPropertyCommEvent(self, strPropertyName, oldVar, newVar);

	return 0;
}

int NFCLuaScriptModule::OnRecordCommonEvent(const NFGUID& self, const RECORD_EVENT_DATA& xEventData, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	DoRecordCommonEvent(self, xEventData, oldVar, newVar);

	return 0;
}

int NFCLuaScriptModule::OnClassCommonEvent(const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
	DoClassCommonEvent(m_pLogicClassModule, self, strClassName, eClassEvent, var);

	return 0;
}

bool NFCLuaScriptModule::CheckCompomentStatus(const std::string& strComponentName, const std::string& strFuncName)
{
	return true;
}

bool NFCLuaScriptModule::CheckCompomentStatus(const std::string& strComponentName)
{
	try
	{
		luacpp::call<void>(lw, "load_script_file", strComponentName);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return false;
	}

	return true;
}

int NFCLuaScriptModule::DoScript(const NFGUID& self, const std::string& strComponentName, const std::string& strFunction, const NFCDataList& arg)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, &arg);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, arg);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}

	return 1;
}

int NFCLuaScriptModule::DoEventScript(const NFGUID& self, const int nEventID, const std::string& strComponentName, const std::string& strFunction, const NFCDataList& arg)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, nEventID, &arg);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, nEventID, arg);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoHeartBeatScript(const NFGUID& self, const std::string& strHeartBeat, const float fTime, const int nCount, std::string& strComponentName, const std::string& strFunction)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strHeartBeat.c_str(), fTime, nCount);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strHeartBeat.c_str(), fTime, nCount);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoScriptPropertyCallBack(const NFGUID& self, const std::string& strPropertyName, const std::string& strComponentName, const std::string& strFunction, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strPropertyName.c_str(), &oldVar, &newVar);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strPropertyName.c_str(), oldVar, newVar);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoScriptRecordCallBack(const NFGUID& self, const std::string& strRecordName, const std::string& strComponentName, const std::string& strFunction, const int nOpType, const int nRow, const int nCol, const NFCDataList::TData& oldVar, const NFCDataList::TData& newVar)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strRecordName.c_str(), nOpType, nRow, nCol, &oldVar, &newVar);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strRecordName.c_str(), nOpType, nRow, nCol, oldVar, newVar);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

bool NFCLuaScriptModule::Regisger()
{
	luacpp::reg_cclass<NFGUID>::_reg(lw, "NFGUID")
		.constructor<void>()//޲ι
		//.constructor<const test_class_A&>()//һ
		.method("GetData", &NFGUID::GetData)
		.method("SetData", &NFGUID::SetData)
		.method("GetHead", &NFGUID::GetHead)
		.method("SetHead", &NFGUID::SetHead);

	luacpp::reg_cclass<NFIDataList>::_reg(lw, "NFIDataList");

	luacpp::reg_cclass<NFCDataList>::_reg(lw, "NFCDataList")
		.constructor<void>()//޲ι
		//.constructor<const test_class_A&>()//һ
		.method("IsEmpty", &NFCDataList::IsEmpty)
		.method("GetCount", &NFCDataList::GetCount)
		.method("Type", &NFCDataList::Type)
		.method("AddInt", &NFCDataList::AddInt)
		.method("AddFloat", &NFCDataList::AddFloat)
		.method("AddString", &NFCDataList::AddStringFromChar)
		.method("AddObject", &NFCDataList::AddObject)
		.method("SetInt", &NFCDataList::SetInt)
		.method("SetFloat", &NFCDataList::SetFloat)
		.method("SetString", &NFCDataList::SetString)
		.method("SetObject", &NFCDataList::SetObject)
		.method("Int", &NFCDataList::Int)
		.method("Float", &NFCDataList::Float)
		.method("String", &NFCDataList::String)
		.method("Object", &NFCDataList::Object);

	luacpp::reg_cclass<NFCDataList::TData>::_reg(lw, "TData")
		.constructor<void>()//޲ι
		.method("GetFloat", &NFCDataList::TData::GetFloat)
		.method("GetInt", &NFCDataList::TData::GetInt)
		.method("GetObjectA", &NFCDataList::TData::GetObjectA)
		.method("GetString", &NFCDataList::TData::GetCharArr)
		.method("GetType", &NFCDataList::TData::GetType)
		.method("IsNullValue", &NFCDataList::TData::IsNullValue)
		.method("SetFloat", &NFCDataList::TData::SetFloat)
		.method("SetInt", &NFCDataList::TData::SetInt)
		.method("SetObject", &NFCDataList::TData::SetObject)
		.method("SetString", &NFCDataList::TData::SetString)
		.method("StringValEx", &NFCDataList::TData::StringValEx)
		.property("GetData", &NFCDataList::TData::variantData);

	luacpp::reg_cfun(lw, "DoEvent", &KernelModule_DoEvent);
	luacpp::reg_cfun(lw, "ExistElement", &KernelModule_ExistElement);
	luacpp::reg_cfun(lw, "GetElementPropertyInt", &KernelModule_GetElementPropertyInt);
	luacpp::reg_cfun(lw, "GetElementPropertyFloat", &KernelModule_GetElementPropertyFloat);
	luacpp::reg_cfun(lw, "GetElementPropertyString", &KernelModule_GetElementPropertyString);
	luacpp::reg_cfun(lw, "AddPropertyCallBack", &KernelModule_AddPropertyCallBack);
	luacpp::reg_cfun(lw, "AddRecordCallBack", &KernelModule_AddRecordCallBack);
	luacpp::reg_cfun(lw, "AddEventCallBack", &KernelModule_AddEventCallBack);
	luacpp::reg_cfun(lw, "AddHeartBeat", &KernelModule_AddHeartBeat);
	luacpp::reg_cfun(lw, "FindHeartBeat", &KernelModule_FindHeartBeat);
	luacpp::reg_cfun(lw, "RemoveHeartBeat", &KernelModule_RemoveHeartBeat);
	luacpp::reg_cfun(lw, "ExistContainer", &KernelModule_ExistContainer);
	luacpp::reg_cfun(lw, "SetPropertyInt", &KernelModule_SetPropertyInt);
	luacpp::reg_cfun(lw, "SetPropertyFloat", &KernelModule_SetPropertyFloat);
	luacpp::reg_cfun(lw, "SetPropertyString", &KernelModule_SetPropertyString);
	luacpp::reg_cfun(lw, "SetPropertyObject", &KernelModule_SetPropertyObject);
	luacpp::reg_cfun(lw, "GetPropertyInt", &KernelModule_GetPropertyInt);
	luacpp::reg_cfun(lw, "GetPropertyFloat", &KernelModule_GetPropertyFloat);
	luacpp::reg_cfun(lw, "GetPropertyString", &KernelModule_GetPropertyString);
	luacpp::reg_cfun(lw, "GetPropertyObject", &KernelModule_GetPropertyObject);
	luacpp::reg_cfun(lw, "SetRecordInt", &KernelModule_SetRecordInt);
	luacpp::reg_cfun(lw, "SetRecordFloat", &KernelModule_SetRecordFloat);
	luacpp::reg_cfun(lw, "SetRecordString", &KernelModule_SetRecordString);
	luacpp::reg_cfun(lw, "SetRecordObject", &KernelModule_SetRecordObject);
	luacpp::reg_cfun(lw, "GetRecordInt", &KernelModule_GetRecordInt);
	luacpp::reg_cfun(lw, "GetRecordFloat", &KernelModule_GetRecordFloat);
	luacpp::reg_cfun(lw, "GetRecordString", &KernelModule_GetRecordString);
	luacpp::reg_cfun(lw, "GetRecordObject", &KernelModule_GetRecordObject);
	luacpp::reg_cfun(lw, "AddRow", &KernelModule_AddRow);

	return true;
}

int NFCLuaScriptModule::DoClassCommonScript(const NFGUID& self, const std::string& strComponentName, const std::string& strFunction)
{
	if (!CheckCompomentStatus(strComponentName, strFunction))
	{
		return 0;
	}

	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 0;
}
<commit_msg>sue lua as module<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCLuaScriptModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2013-01-02
//    @Module           :    NFCLuaScriptModule
//    @Desc             :
// -------------------------------------------------------------------------

#include "NFCLuaScriptModule.h"
#include "NFLuaScriptPlugin.h"
#include <assert.h>

bool NFCLuaScriptModule::Init()
{
	m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>("NFCKernelModule");
	m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>("NFCLogicClassModule");
	m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>("NFCElementInfoModule");

	assert(NULL != m_pKernelModule);
	assert(NULL != m_pLogicClassModule);
	assert(NULL != m_pElementInfoModule);

	Regisger();

	try
	{
		lw.dofile("script_init.lua");
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		assert(0);
	}

	//std::shared_ptr<NFILogicClass> pClass = m_pLogicClassModule->First();
	//while (pClass.get())
	//{
	//	std::shared_ptr<NFIComponent> pComponent = pClass->GetComponentManager()->First();
	//	while (pComponent.get())
	//	{
	//		if (!CheckCompomentStatus(pComponent->GetComponentName()))
	//		{
	//			assert(0);
	//		}

	//		pComponent = pClass->GetComponentManager()->Next();
	//	}

	//	pClass = m_pLogicClassModule->Next();
	//}
	if (!CheckCompomentStatus("Test"))
	{
		assert(0);
	}

	//call Test:Init()
	luacpp::call<void>(lw, "Init");

	return true;
}

bool NFCLuaScriptModule::AfterInit()
{
	luacpp::call<void>(lw, "AfterInit");

	//add all callback
	m_pKernelModule->ResgisterCommonPropertyEvent(this, &NFCLuaScriptModule::OnPropertyCommEvent);
	m_pKernelModule->ResgisterCommonRecordEvent(this, &NFCLuaScriptModule::OnRecordCommonEvent);
	m_pKernelModule->ResgisterCommonClassEvent(this, &NFCLuaScriptModule::OnClassCommonEvent);

	return true;
}

bool NFCLuaScriptModule::Shut()
{

	return true;
}

bool NFCLuaScriptModule::Execute()
{
	return true;
}

bool NFCLuaScriptModule::BeforeShut()
{
	//fflua.~fflua_t();
	return true;
}

int NFCLuaScriptModule::OnPropertyCommEvent(const NFGUID& self, const std::string& strPropertyName, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	DoPropertyCommEvent(self, strPropertyName, oldVar, newVar);

	return 0;
}

int NFCLuaScriptModule::OnRecordCommonEvent(const NFGUID& self, const RECORD_EVENT_DATA& xEventData, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	DoRecordCommonEvent(self, xEventData, oldVar, newVar);

	return 0;
}

int NFCLuaScriptModule::OnClassCommonEvent(const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
	DoClassCommonEvent(m_pLogicClassModule, self, strClassName, eClassEvent, var);

	return 0;
}

bool NFCLuaScriptModule::CheckCompomentStatus(const std::string& strComponentName, const std::string& strFuncName)
{
	return true;
}

bool NFCLuaScriptModule::CheckCompomentStatus(const std::string& strComponentName)
{
	try
	{
		luacpp::call<void>(lw, "load_script_file", strComponentName);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return false;
	}

	return true;
}

int NFCLuaScriptModule::DoScript(const NFGUID& self, const std::string& strComponentName, const std::string& strFunction, const NFCDataList& arg)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, &arg);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, arg);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}

	return 1;
}

int NFCLuaScriptModule::DoEventScript(const NFGUID& self, const int nEventID, const std::string& strComponentName, const std::string& strFunction, const NFCDataList& arg)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, nEventID, &arg);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, nEventID, arg);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoHeartBeatScript(const NFGUID& self, const std::string& strHeartBeat, const float fTime, const int nCount, std::string& strComponentName, const std::string& strFunction)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strHeartBeat.c_str(), fTime, nCount);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strHeartBeat.c_str(), fTime, nCount);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoScriptPropertyCallBack(const NFGUID& self, const std::string& strPropertyName, const std::string& strComponentName, const std::string& strFunction, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strPropertyName.c_str(), &oldVar, &newVar);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strPropertyName.c_str(), oldVar, newVar);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoScriptRecordCallBack(const NFGUID& self, const std::string& strRecordName, const std::string& strComponentName, const std::string& strFunction, const int nOpType, const int nRow, const int nCol, const NFCDataList::TData& oldVar, const NFCDataList::TData& newVar)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strRecordName.c_str(), nOpType, nRow, nCol, &oldVar, &newVar);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strRecordName.c_str(), nOpType, nRow, nCol, oldVar, newVar);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

bool NFCLuaScriptModule::Regisger()
{
	luacpp::reg_cclass<NFGUID>::_reg(lw, "NFGUID")
		.constructor<void>()//޲ι
		//.constructor<const test_class_A&>()//һ
		.method("GetData", &NFGUID::GetData)
		.method("SetData", &NFGUID::SetData)
		.method("GetHead", &NFGUID::GetHead)
		.method("SetHead", &NFGUID::SetHead);

	luacpp::reg_cclass<NFIDataList>::_reg(lw, "NFIDataList");

	luacpp::reg_cclass<NFCDataList>::_reg(lw, "NFCDataList")
		.constructor<void>()//޲ι
		//.constructor<const test_class_A&>()//һ
		.method("IsEmpty", &NFCDataList::IsEmpty)
		.method("GetCount", &NFCDataList::GetCount)
		.method("Type", &NFCDataList::Type)
		.method("AddInt", &NFCDataList::AddInt)
		.method("AddFloat", &NFCDataList::AddFloat)
		.method("AddString", &NFCDataList::AddStringFromChar)
		.method("AddObject", &NFCDataList::AddObject)
		.method("SetInt", &NFCDataList::SetInt)
		.method("SetFloat", &NFCDataList::SetFloat)
		.method("SetString", &NFCDataList::SetString)
		.method("SetObject", &NFCDataList::SetObject)
		.method("Int", &NFCDataList::Int)
		.method("Float", &NFCDataList::Float)
		.method("String", &NFCDataList::String)
		.method("Object", &NFCDataList::Object);

	luacpp::reg_cclass<NFCDataList::TData>::_reg(lw, "TData")
		.constructor<void>()//޲ι
		.method("GetFloat", &NFCDataList::TData::GetFloat)
		.method("GetInt", &NFCDataList::TData::GetInt)
		.method("GetObjectA", &NFCDataList::TData::GetObjectA)
		.method("GetString", &NFCDataList::TData::GetCharArr)
		.method("GetType", &NFCDataList::TData::GetType)
		.method("IsNullValue", &NFCDataList::TData::IsNullValue)
		.method("SetFloat", &NFCDataList::TData::SetFloat)
		.method("SetInt", &NFCDataList::TData::SetInt)
		.method("SetObject", &NFCDataList::TData::SetObject)
		.method("SetString", &NFCDataList::TData::SetString)
		.method("StringValEx", &NFCDataList::TData::StringValEx)
		.property("GetData", &NFCDataList::TData::variantData);

	luacpp::reg_cfun(lw, "DoEvent", &KernelModule_DoEvent);
	luacpp::reg_cfun(lw, "ExistElement", &KernelModule_ExistElement);
	luacpp::reg_cfun(lw, "GetElementPropertyInt", &KernelModule_GetElementPropertyInt);
	luacpp::reg_cfun(lw, "GetElementPropertyFloat", &KernelModule_GetElementPropertyFloat);
	luacpp::reg_cfun(lw, "GetElementPropertyString", &KernelModule_GetElementPropertyString);
	luacpp::reg_cfun(lw, "AddPropertyCallBack", &KernelModule_AddPropertyCallBack);
	luacpp::reg_cfun(lw, "AddRecordCallBack", &KernelModule_AddRecordCallBack);
	luacpp::reg_cfun(lw, "AddEventCallBack", &KernelModule_AddEventCallBack);
	luacpp::reg_cfun(lw, "AddHeartBeat", &KernelModule_AddHeartBeat);
	luacpp::reg_cfun(lw, "FindHeartBeat", &KernelModule_FindHeartBeat);
	luacpp::reg_cfun(lw, "RemoveHeartBeat", &KernelModule_RemoveHeartBeat);
	luacpp::reg_cfun(lw, "ExistContainer", &KernelModule_ExistContainer);
	luacpp::reg_cfun(lw, "SetPropertyInt", &KernelModule_SetPropertyInt);
	luacpp::reg_cfun(lw, "SetPropertyFloat", &KernelModule_SetPropertyFloat);
	luacpp::reg_cfun(lw, "SetPropertyString", &KernelModule_SetPropertyString);
	luacpp::reg_cfun(lw, "SetPropertyObject", &KernelModule_SetPropertyObject);
	luacpp::reg_cfun(lw, "GetPropertyInt", &KernelModule_GetPropertyInt);
	luacpp::reg_cfun(lw, "GetPropertyFloat", &KernelModule_GetPropertyFloat);
	luacpp::reg_cfun(lw, "GetPropertyString", &KernelModule_GetPropertyString);
	luacpp::reg_cfun(lw, "GetPropertyObject", &KernelModule_GetPropertyObject);
	luacpp::reg_cfun(lw, "SetRecordInt", &KernelModule_SetRecordInt);
	luacpp::reg_cfun(lw, "SetRecordFloat", &KernelModule_SetRecordFloat);
	luacpp::reg_cfun(lw, "SetRecordString", &KernelModule_SetRecordString);
	luacpp::reg_cfun(lw, "SetRecordObject", &KernelModule_SetRecordObject);
	luacpp::reg_cfun(lw, "GetRecordInt", &KernelModule_GetRecordInt);
	luacpp::reg_cfun(lw, "GetRecordFloat", &KernelModule_GetRecordFloat);
	luacpp::reg_cfun(lw, "GetRecordString", &KernelModule_GetRecordString);
	luacpp::reg_cfun(lw, "GetRecordObject", &KernelModule_GetRecordObject);
	luacpp::reg_cfun(lw, "AddRow", &KernelModule_AddRow);

	return true;
}

int NFCLuaScriptModule::DoClassCommonScript(const NFGUID& self, const std::string& strComponentName, const std::string& strFunction)
{
	if (!CheckCompomentStatus(strComponentName, strFunction))
	{
		return 0;
	}

	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {XX.tif}
//    OUTPUTS: {XX.txt}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  This example shows the basic approch to perform object based analysis on a image.
//  The input image is firstly segmented using the \doxygen{otb}{MeanShiftImageFilter}
//  Then each segmented region is converted to a Map of labeled objects.
//  After the \doxygen{otb}{RadiometricAttributesLabelMapFilter}  computes
//  radiometric attributes for each object.
//  Images are supposed to be standard 4-bands image (B,G,R,NIR). The
//  index of each channel can be set via the Set***ChannelIndex()
//  accessors.
//
//  This filter internally applies the
//  StatisticsAttributesLabelMapFilter to the following features:
  //  \begin{itemize}
  //  \item GEMI
  //  \item NDVI
  //  \item IR
  //  \item IC
  //  \item IB
  //  \item NDWI2
  //  \item Intensity
  //  \item and original B, G, R and NIR channels
  //  \end{itemize},
//  Here we use the  \doxygen{otb}{AttributesMapOpeningLabelMapFilter} to extract vegetated areas.
//
//
//  Software Guide : EndLatex

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"

#include "otbMeanShiftImageFilter.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "otbAttributesMapLabelObject.h"
#include "itkLabelMap.h"
#include "otbShapeAttributesLabelMapFilter.h"
#include "otbStatisticsAttributesLabelMapFilter.h"
#include "otbRadiometricAttributesLabelMapFilter.h"
#include "otbAttributesMapOpeningLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"

int main(int argc, char * argv[])
{
  if(argc != 10)
    {
      std::cerr<<"Usage: "<<argv[0]<<" reffname outfname attribute_name lowerThan tresh spatialRadius rangeRadius minregionsize scale"<<std::endl;
      return EXIT_FAILURE;
    }

  const char * reffname = argv[1];
  const char * outfname = argv[2];
  const char * attr     = argv[3];
  bool  lowerThan       = atoi(argv[4]);
  double thresh         = atof(argv[5]);

  const unsigned int spatialRadius          = atoi(argv[6]);
  const double       rangeRadius            = atof(argv[7]);
  const unsigned int minRegionSize          = atoi(argv[8]);
  const double       scale                  = atoi(argv[9]);

  const unsigned int Dimension = 2;

  // Labeled image type
  typedef unsigned short                                                 LabelType;
  typedef double                                                         PixelType;
  typedef otb::Image<LabelType,Dimension>                                LabeledImageType;
  typedef otb::Image<PixelType,Dimension>                                ImageType;
  typedef otb::VectorImage<PixelType,Dimension>                          VectorImageType;
  typedef otb::ImageFileReader<LabeledImageType>                         LabeledReaderType;
  typedef otb::ImageFileReader<ImageType>                                ReaderType;
  typedef otb::ImageFileReader<VectorImageType>                          VectorReaderType;
  typedef otb::ImageFileWriter<LabeledImageType>                         WriterType;
  // Label map typedef
  typedef otb::AttributesMapLabelObject<LabelType,Dimension,double>      LabelObjectType;
  typedef itk::LabelMap<LabelObjectType>                                 LabelMapType;
  typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType;
  typedef otb::ShapeAttributesLabelMapFilter<LabelMapType>               ShapeLabelMapFilterType;
  typedef otb::StatisticsAttributesLabelMapFilter<LabelMapType,ImageType> StatisticsLabelMapFilterType;
  typedef otb::RadiometricAttributesLabelMapFilter<LabelMapType,VectorImageType> RadiometricLabelMapFilterType;
  typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType>          OpeningLabelMapFilterType;
  typedef itk::LabelMapToLabelImageFilter<LabelMapType,LabeledImageType> LabelMapToLabeledImageFilterType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(reffname);

  VectorReaderType::Pointer vreader = VectorReaderType::New();
  vreader->SetFileName(reffname);
    //  Software Guide : BeginLatex
  //
  // Firstly, segment input image using Mean Shift algorithm.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::MeanShiftImageFilter<ImageType,ImageType, LabeledImageType> FilterType;
  FilterType::Pointer filter = FilterType::New();
  filter->SetSpatialRadius(spatialRadius);
  filter->SetRangeRadius(rangeRadius);
  filter->SetMinimumRegionSize(minRegionSize);
  filter->SetScale(scale);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // The \doxygen{otb}{MeanShiftImageFilter} type is instantiated using the images
  // types.
  //
  //  Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
  filter->SetInput(reader->GetOutput());
// Software Guide : EndCodeSnippet
  LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New();
  labelMapFilter->SetInput(filter->GetLabeledClusteredOutput());
  labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::min());

  ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
  shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput());

  StatisticsLabelMapFilterType::Pointer statisticsLabelMapFilter = StatisticsLabelMapFilterType::New();
  statisticsLabelMapFilter->SetInput1(shapeLabelMapFilter->GetOutput());
  statisticsLabelMapFilter->SetInput2(reader->GetOutput());

  statisticsLabelMapFilter->Update();
  //  Software Guide : BeginLatex
  //
  // Instantiate the  \doxygen{otb}{RadiometricAttributesLabelMapFilter} to
  // compute radiometric value on each label object.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();
  radiometricLabelMapFilter->SetInput1(statisticsLabelMapFilter->GetOutput());
  radiometricLabelMapFilter->SetInput2(vreader->GetOutput());
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Then, we specify the red and the near infrared channels
  //
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  radiometricLabelMapFilter->SetRedChannelIndex(2);
  radiometricLabelMapFilter->SetNIRChannelIndex(3);
  radiometricLabelMapFilter->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The \doxygen{otb}{AttributesMapOpeningLabelMapFilter} will proceed the selection.
  // There are three parameters. \code{AttributeName} specifies the radiometric attribute, \code{Lambda}
  // controls the thresholding of the input and \code{ReverseOrdering} make this filter to remove the
  // object with an attribute value greater than \code{Lambda} instead.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New();
  opening->SetInput(radiometricLabelMapFilter->GetOutput());
  opening->SetAttributeName(attr);
  opening->SetLambda(thresh);
  opening->SetReverseOrdering(lowerThan);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Then, Label object selected are transform in a Label Image using the \doxygen{itk}{LabelMapToLabelImageFilter}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  LabelMapToLabeledImageFilterType::Pointer labelMap2LabeledImage = LabelMapToLabeledImageFilterType::New();
  labelMap2LabeledImage->SetInput(opening->GetOutput());
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // And finally, we declare the writer and call its \code{Update()} method to
  // trigger the full pipeline execution.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(outfname);
  writer->SetInput(labelMap2LabeledImage->GetOutput());
  writer->Update();
  // Software Guide : EndCodeSnippet

  return EXIT_SUCCESS;
}
<commit_msg>DOC:radiometriclabelmap<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {/home/grizonnetm/OTB/Dev/OTB-Data/Examples/qb_RoadExtract2.tif}
//    OUTPUTS: {OBIARadiometricAttribute1.tif}
//    STATS::Ndvi::Mean 0 0.3 16 16 200 1.0
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  This example shows the basic approach to perform object based analysis on a image.
//  The input image is firstly segmented using the \doxygen{otb}{MeanShiftImageFilter}
//  Then each segmented region is converted to a Map of labeled objects.
//  After the \doxygen{otb}{RadiometricAttributesLabelMapFilter}  computes
//  radiometric attributes for each object.
//  Images are supposed to be standard 4-bands image (B,G,R,NIR). The
//  index of each channel can be set via the Set***ChannelIndex()
//  accessors.
//
//  This filter internally applies the
//  StatisticsAttributesLabelMapFilter to the following features:
  //  \begin{itemize}
  //  \item GEMI
  //  \item NDVI
  //  \item IR
  //  \item IC
  //  \item IB
  //  \item NDWI2
  //  \item Intensity
  //  \item and original B, G, R and NIR channels
  //  \end{itemize},
//  Here we use the  \doxygen{otb}{AttributesMapOpeningLabelMapFilter} to extract vegetated areas.
//
//
//  Software Guide : EndLatex

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"

#include "otbMeanShiftImageFilter.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "otbAttributesMapLabelObject.h"
#include "itkLabelMap.h"
#include "otbShapeAttributesLabelMapFilter.h"
#include "otbStatisticsAttributesLabelMapFilter.h"
#include "otbRadiometricAttributesLabelMapFilter.h"
#include "otbAttributesMapOpeningLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"

int main(int argc, char * argv[])
{
  if(argc != 10)
    {
      std::cerr<<"Usage: "<<argv[0]<<" reffname outfname attribute_name lowerThan tresh spatialRadius rangeRadius minregionsize scale"<<std::endl;
      return EXIT_FAILURE;
    }

  const char * reffname = argv[1];
  const char * outfname = argv[2];
  const char * attr     = argv[3];
  bool  lowerThan       = atoi(argv[4]);
  double thresh         = atof(argv[5]);

  const unsigned int spatialRadius          = atoi(argv[6]);
  const double       rangeRadius            = atof(argv[7]);
  const unsigned int minRegionSize          = atoi(argv[8]);
  const double       scale                  = atoi(argv[9]);

  const unsigned int Dimension = 2;

  // Labeled image type
  typedef unsigned short                                                 LabelType;
  typedef double                                                         PixelType;
  typedef otb::Image<LabelType,Dimension>                                LabeledImageType;
  typedef otb::Image<PixelType,Dimension>                                ImageType;
  typedef otb::VectorImage<PixelType,Dimension>                          VectorImageType;
  typedef otb::ImageFileReader<LabeledImageType>                         LabeledReaderType;
  typedef otb::ImageFileReader<ImageType>                                ReaderType;
  typedef otb::ImageFileReader<VectorImageType>                          VectorReaderType;
  typedef otb::ImageFileWriter<LabeledImageType>                         WriterType;
  // Label map typedef
  typedef otb::AttributesMapLabelObject<LabelType,Dimension,double>      LabelObjectType;
  typedef itk::LabelMap<LabelObjectType>                                 LabelMapType;
  typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType;
  typedef otb::ShapeAttributesLabelMapFilter<LabelMapType>               ShapeLabelMapFilterType;
  typedef otb::StatisticsAttributesLabelMapFilter<LabelMapType,ImageType> StatisticsLabelMapFilterType;
  typedef otb::RadiometricAttributesLabelMapFilter<LabelMapType,VectorImageType> RadiometricLabelMapFilterType;
  typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType>          OpeningLabelMapFilterType;
  typedef itk::LabelMapToLabelImageFilter<LabelMapType,LabeledImageType> LabelMapToLabeledImageFilterType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(reffname);

  VectorReaderType::Pointer vreader = VectorReaderType::New();
  vreader->SetFileName(reffname);
    //  Software Guide : BeginLatex
  //
  // Firstly, segment input image using the Mean Shift algorithm.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::MeanShiftImageFilter<ImageType,ImageType, LabeledImageType> FilterType;
  FilterType::Pointer filter = FilterType::New();
  filter->SetSpatialRadius(spatialRadius);
  filter->SetRangeRadius(rangeRadius);
  filter->SetMinimumRegionSize(minRegionSize);
  filter->SetScale(scale);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // The \doxygen{otb}{MeanShiftImageFilter} type is instantiated using the images
  // types.
  //
  //  Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
  filter->SetInput(reader->GetOutput());
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
  //
  // The \doxygen{itk}{LabelImageToLabelMapFilter} type is instantiated using the output
  // of the \doxygen{otb}{MeanShiftImageFilter}. This filter produces a labeled image
  // where each segmented region have a unique label.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New();
  labelMapFilter->SetInput(filter->GetLabeledClusteredOutput());
  labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::min());
  // Software Guide : EndCodeSnippet

  ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
  shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput());

  StatisticsLabelMapFilterType::Pointer statisticsLabelMapFilter = StatisticsLabelMapFilterType::New();
  statisticsLabelMapFilter->SetInput1(shapeLabelMapFilter->GetOutput());
  statisticsLabelMapFilter->SetInput2(reader->GetOutput());

  statisticsLabelMapFilter->Update();
  //  Software Guide : BeginLatex
  //
  // Instantiate the  \doxygen{otb}{RadiometricAttributesLabelMapFilter} to
  // compute radiometric value on each label object.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();
  radiometricLabelMapFilter->SetInput1(statisticsLabelMapFilter->GetOutput());
  radiometricLabelMapFilter->SetInput2(vreader->GetOutput());
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // Then, we specify the red and the near infrared channels
  // By default, images are supposed to be standard 4-bands
  // image (B,G,R,NIR). The index of each channel can
  // be set via the Set***ChannelIndex() accessors.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  radiometricLabelMapFilter->SetRedChannelIndex(2);
  radiometricLabelMapFilter->SetNIRChannelIndex(3);
  radiometricLabelMapFilter->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // The \doxygen{otb}{AttributesMapOpeningLabelMapFilter} will proceed the selection.
  // There are three parameters. \code{AttributeName} specifies the radiometric attribute, \code{Lambda}
  // controls the thresholding of the input and \code{ReverseOrdering} make this filter to remove the
  // object with an attribute value greater than \code{Lambda} instead.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New();
  opening->SetInput(radiometricLabelMapFilter->GetOutput());
  opening->SetAttributeName(attr);
  opening->SetLambda(thresh);
  opening->SetReverseOrdering(lowerThan);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Then, Label object selected are transform in a Label Image using the \doxygen{itk}{LabelMapToLabelImageFilter}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  LabelMapToLabeledImageFilterType::Pointer labelMap2LabeledImage = LabelMapToLabeledImageFilterType::New();
  labelMap2LabeledImage->SetInput(opening->GetOutput());
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // And finally, we declare the writer and call its \code{Update()} method to
  // trigger the full pipeline execution.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(outfname);
  writer->SetInput(labelMap2LabeledImage->GetOutput());
  writer->Update();
  // Software Guide : EndCodeSnippet

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// DroneStroker.CLI.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DroneStriker.h"
extern "C" {
#include <math.h>
#include <stdlib.h>
}

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

#include <direct.h>
using namespace cv;

int main(int argc, char* argv[])
{
	if (argc != 4) {
		fprintf(stderr,
			"Usage %s <image filename> <wind orientation> <wind magnitude>\n",
			argv[0]);
		return -1;
	}
	double orientation = atof(argv[2]);
	int magnitude = atoi(argv[3]);

	// There is a bug with win32 and opencv2's imread preventing us from
	// reading the image directory into the Mat.
	IplImage* imageRead = cvLoadImage(argv[1], 1);
	Mat image(imageRead);

	if (image.data == NULL) {
		printf("Could not load image file.\n");
		printf("cwd = %s\n", _getcwd(NULL, 0));
		printf("f = %s\n", argv[1]);
		return - 1;
	}

	DroneStriker d;

	Mat resultantImage;

	d.Annihilate(image, resultantImage, orientation, magnitude);

	imwrite("output.jpg", resultantImage);
	return 0;
}

<commit_msg>Went back to opencv2 imread call<commit_after>// DroneStroker.CLI.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DroneStriker.h"
extern "C" {
#include <math.h>
#include <stdlib.h>
}

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

#include <direct.h>
using namespace cv;

int main(int argc, char* argv[])
{
	if (argc != 4) {
		fprintf(stderr,
			"Usage %s <image filename> <wind orientation> <wind magnitude>\n",
			argv[0]);
		return -1;
	}
	double orientation = atof(argv[2]);
	int magnitude = atoi(argv[3]);

	Mat image = imread(argv[1], 1);

	if (image.data == NULL) {
		printf("Could not load image file.\n");
		return - 1;
	}

	DroneStriker d;

	Mat resultantImage;

	d.Annihilate(image, resultantImage, orientation, magnitude);

	imwrite("output.jpg", resultantImage);
	return 0;
}

<|endoftext|>


<commit_before>
#include <rxcpp/rx-lite.hpp>
#include <rxcpp/operators/rx-reduce.hpp>
#include <rxcpp/operators/rx-filter.hpp>
#include <rxcpp/operators/rx-map.hpp>
#include <rxcpp/operators/rx-tap.hpp>
#include <rxcpp/operators/rx-concat_map.hpp>
#include <rxcpp/operators/rx-flat_map.hpp>
#include <rxcpp/operators/rx-concat.hpp>
#include <rxcpp/operators/rx-merge.hpp>
#include <rxcpp/operators/rx-repeat.hpp>
#include <rxcpp/operators/rx-publish.hpp>
#include <rxcpp/operators/rx-ref_count.hpp>
#include <rxcpp/operators/rx-window.hpp>
#include <rxcpp/operators/rx-window_toggle.hpp>
namespace Rx {
using namespace rxcpp;
using namespace rxcpp::sources;
using namespace rxcpp::operators;
using namespace rxcpp::util;
}
using namespace Rx;

#include <regex>
#include <random>
using namespace std;
using namespace std::chrono;

int main()
{
    random_device rd;   // non-deterministic generator
    mt19937 gen(rd());
    uniform_int_distribution<> dist(4, 18);

    // for testing purposes, produce byte stream that from lines of text
    auto bytes = range(0, 10) |
        flat_map([&](int i){
            auto body = from((uint8_t)('A' + i)) |
                repeat(dist(gen)) |
                as_dynamic();
            auto delim = from((uint8_t)'\r');
            return from(body, delim) | concat();
        }) |
        window(17) |
        flat_map([](observable<uint8_t> w){
            return w |
                reduce(
                    vector<uint8_t>(),
                    [](vector<uint8_t> v, uint8_t b){
                        v.push_back(b);
                        return v;
                    }) |
                as_dynamic();
        }) |
        tap([](vector<uint8_t>& v){
            // print input packet of bytes
            copy(v.begin(), v.end(), ostream_iterator<long>(cout, " "));
            cout << endl;
        });

    //
    // recover lines of text from byte stream
    //

    auto removespaces = [](string s){
        s.erase(remove_if(s.begin(), s.end(), ::isspace), s.end());
        return s;
    };

    // create strings split on \r
    auto strings = bytes |
        concat_map([](vector<uint8_t> v){
            string s(v.begin(), v.end());
            regex delim(R"/(\r)/");
            cregex_token_iterator cursor(&s[0], &s[0] + s.size(), delim, {-1, 0});
            cregex_token_iterator end;
            vector<string> splits(cursor, end);
            return iterate(move(splits));
        }) |
        filter([](const string& s){
            return !s.empty();
        }) |
        publish() |
        ref_count();

    // filter to last string in each line
    auto closes = strings |
        filter(
            [](const string& s){
                return s.back() == '\r';
            }) |
        Rx::map([](const string&){return 0;});

    // group strings by line
    auto linewindows = strings |
        window_toggle(closes | start_with(0), [=](int){return closes;});

    // reduce the strings for a line into one string
    auto lines = linewindows |
        flat_map([&](observable<string> w) {
            return w | start_with<string>("") | sum() | Rx::map(removespaces);
        });

    // print result
    lines |
        subscribe<string>(println(cout));

    return 0;
}
<commit_msg>decouple start_with from observable - fix example<commit_after>
#include <rxcpp/rx-lite.hpp>
#include <rxcpp/operators/rx-reduce.hpp>
#include <rxcpp/operators/rx-filter.hpp>
#include <rxcpp/operators/rx-map.hpp>
#include <rxcpp/operators/rx-tap.hpp>
#include <rxcpp/operators/rx-concat_map.hpp>
#include <rxcpp/operators/rx-flat_map.hpp>
#include <rxcpp/operators/rx-concat.hpp>
#include <rxcpp/operators/rx-merge.hpp>
#include <rxcpp/operators/rx-repeat.hpp>
#include <rxcpp/operators/rx-publish.hpp>
#include <rxcpp/operators/rx-ref_count.hpp>
#include <rxcpp/operators/rx-window.hpp>
#include <rxcpp/operators/rx-window_toggle.hpp>
#include <rxcpp/operators/rx-start_with.hpp>
namespace Rx {
using namespace rxcpp;
using namespace rxcpp::sources;
using namespace rxcpp::operators;
using namespace rxcpp::util;
}
using namespace Rx;

#include <regex>
#include <random>
using namespace std;
using namespace std::chrono;

int main()
{
    random_device rd;   // non-deterministic generator
    mt19937 gen(rd());
    uniform_int_distribution<> dist(4, 18);

    // for testing purposes, produce byte stream that from lines of text
    auto bytes = range(0, 10) |
        flat_map([&](int i){
            auto body = from((uint8_t)('A' + i)) |
                repeat(dist(gen)) |
                as_dynamic();
            auto delim = from((uint8_t)'\r');
            return from(body, delim) | concat();
        }) |
        window(17) |
        flat_map([](observable<uint8_t> w){
            return w |
                reduce(
                    vector<uint8_t>(),
                    [](vector<uint8_t> v, uint8_t b){
                        v.push_back(b);
                        return v;
                    }) |
                as_dynamic();
        }) |
        tap([](vector<uint8_t>& v){
            // print input packet of bytes
            copy(v.begin(), v.end(), ostream_iterator<long>(cout, " "));
            cout << endl;
        });

    //
    // recover lines of text from byte stream
    //

    auto removespaces = [](string s){
        s.erase(remove_if(s.begin(), s.end(), ::isspace), s.end());
        return s;
    };

    // create strings split on \r
    auto strings = bytes |
        concat_map([](vector<uint8_t> v){
            string s(v.begin(), v.end());
            regex delim(R"/(\r)/");
            cregex_token_iterator cursor(&s[0], &s[0] + s.size(), delim, {-1, 0});
            cregex_token_iterator end;
            vector<string> splits(cursor, end);
            return iterate(move(splits));
        }) |
        filter([](const string& s){
            return !s.empty();
        }) |
        publish() |
        ref_count();

    // filter to last string in each line
    auto closes = strings |
        filter(
            [](const string& s){
                return s.back() == '\r';
            }) |
        Rx::map([](const string&){return 0;});

    // group strings by line
    auto linewindows = strings |
        window_toggle(closes | start_with(0), [=](int){return closes;});

    // reduce the strings for a line into one string
    auto lines = linewindows |
        flat_map([&](observable<string> w) {
            return w | start_with<string>("") | sum() | Rx::map(removespaces);
        });

    // print result
    lines |
        subscribe<string>(println(cout));

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved
 */
#ifndef _Stroika_Foundation_DataExchange_OptionsFile_inl_
#define _Stroika_Foundation_DataExchange_OptionsFile_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    "../Characters/Format.h"
#include    "../Streams/BasicBinaryOutputStream.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   DataExchange {

            /*
             ********************************************************************************
             ************************** DataExchange::OptionsFile ***************************
             ********************************************************************************
             */
            template    <typename T>
            Optional<T>   OptionsFile::Read ()
            {
                Optional<VariantValue>  tmp = Read<VariantValue> ();
                if (tmp.IsMissing ()) {
                    return Optional<T> ();
                }
                try {
                    return fMapper_.ToObject<T> (*tmp);
                }
                catch (const BadFormatException& bf) {
                    fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file (bad format) '%s' - using defaults.", GetFilePath_ ().c_str ()));
                    return Optional<T> ();
                }
                catch (...) {
                    // if this fails, its probably because somehow the data in the config file was bad.
                    // So at least log that, and continue without reading anything (as if empty file)
                    fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", GetFilePath_ ().c_str ()));
                    return Optional<T> ();
                }
            }
            template    <typename T>
            T   OptionsFile::Read (const T& defaultObj, ReadFlags readFlags)
            {
                Optional<T> eltRead = Read<T> ();
                Optional<T> elt2Write;              // only if needed
                String      msgAugment;
                if (eltRead.IsMissing ()) {
                    if (readFlags == ReadFlags::eWriteIfChanged) {
                        elt2Write = defaultObj;
                        msgAugment = L"default";
                    }
                }
                else {
                    if (readFlags == ReadFlags::eWriteIfChanged) {
                        try {
                            // See if re-persisting the item would change it.
                            // This is useful if your data model adds or removes fields. It updates the file contents written to the
                            // upgraded/latest form
                            Memory::BLOB    oldData =   ReadRaw (); // @todo could have saved from previous Read<T>
                            Memory::BLOB    newData;
                            {
                                Streams::BasicBinaryOutputStream outStream;
                                fWriter_.Write (fMapper_.FromObject (*eltRead), outStream);
                                // not sure needed? outStream.Flush();
                                newData = outStream.As<Memory::BLOB> ();
                            }
                            if (oldData != newData) {
                                elt2Write = eltRead;
                                msgAugment = L"(because something changed)";
                            }
                        }
                        catch (...) {
                            fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to compare configuration file: %s", GetFilePath_ ().c_str ()));
                        }
                    }
                }
                if (elt2Write.IsPresent ()) {
                    fLogger_ (Execution::Logger::Priority::eInfo, Characters::Format (L"Writing %s '%s' configuration file.", msgAugment.c_str (), GetFilePath_ ().c_str ()));
                    try {
                        Write (*elt2Write);
                    }
                    catch (...) {
                        fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to write default values to file: %s", GetFilePath_ ().c_str ()));
                    }
                    return *elt2Write;
                }
                else if (eltRead.IsPresent ()) {
                    return *eltRead;
                }
                else {
                    return defaultObj;
                }
            }
            template    <typename T>
            void    OptionsFile::Write (const T& optionsObject)
            {
                Write<VariantValue> (fMapper_.FromObject<T> (optionsObject));
            }

        }

    }
}
#endif  /*_Stroika_Foundation_DataExchange_OptionsFile_inl_*/
<commit_msg>minor fixes to OptionsFile for last checkin<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved
 */
#ifndef _Stroika_Foundation_DataExchange_OptionsFile_inl_
#define _Stroika_Foundation_DataExchange_OptionsFile_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    "../Characters/Format.h"
#include    "../Streams/BasicBinaryOutputStream.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   DataExchange {

            /*
             ********************************************************************************
             ************************** DataExchange::OptionsFile ***************************
             ********************************************************************************
             */
            template    <typename T>
            Optional<T>   OptionsFile::Read ()
            {
                Optional<VariantValue>  tmp = Read<VariantValue> ();
                if (tmp.IsMissing ()) {
                    return Optional<T> ();
                }
                try {
                    return fMapper_.ToObject<T> (*tmp);
                }
                catch (const BadFormatException& bf) {
                    fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file (bad format) '%s' - using defaults.", GetReadFilePath_ ().c_str ()));
                    return Optional<T> ();
                }
                catch (...) {
                    // if this fails, its probably because somehow the data in the config file was bad.
                    // So at least log that, and continue without reading anything (as if empty file)
                    fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", GetReadFilePath_ ().c_str ()));
                    return Optional<T> ();
                }
            }
            template    <typename T>
            T   OptionsFile::Read (const T& defaultObj, ReadFlags readFlags)
            {
                Optional<T> eltRead = Read<T> ();
                Optional<T> elt2Write;              // only if needed
                String      msgAugment;
                if (eltRead.IsMissing ()) {
                    if (readFlags == ReadFlags::eWriteIfChanged) {
                        elt2Write = defaultObj;
                        msgAugment = L"default";
                    }
                }
                else {
                    if (readFlags == ReadFlags::eWriteIfChanged) {
                        try {
                            // See if re-persisting the item would change it.
                            // This is useful if your data model adds or removes fields. It updates the file contents written to the
                            // upgraded/latest form
                            Memory::BLOB    oldData =   ReadRaw (); // @todo could have saved from previous Read<T>
                            Memory::BLOB    newData;
                            {
                                Streams::BasicBinaryOutputStream outStream;
                                fWriter_.Write (fMapper_.FromObject (*eltRead), outStream);
                                // not sure needed? outStream.Flush();
                                newData = outStream.As<Memory::BLOB> ();
                            }
                            if (oldData != newData) {
                                elt2Write = eltRead;
                                msgAugment = L"(because something changed)";
                            }
                        }
                        catch (...) {
                            fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to compare configuration file: %s", GetReadFilePath_ ().c_str ()));
                        }
                    }
                }
                if (elt2Write.IsPresent ()) {
                    fLogger_ (Execution::Logger::Priority::eInfo, Characters::Format (L"Writing %s '%s' configuration file.", msgAugment.c_str (), GetWriteFilePath_ ().c_str ()));
                    try {
                        Write (*elt2Write);
                    }
                    catch (...) {
                        fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to write default values to file: %s", GetWriteFilePath_ ().c_str ()));
                    }
                    return *elt2Write;
                }
                else if (eltRead.IsPresent ()) {
                    return *eltRead;
                }
                else {
                    return defaultObj;
                }
            }
            template    <typename T>
            void    OptionsFile::Write (const T& optionsObject)
            {
                Write<VariantValue> (fMapper_.FromObject<T> (optionsObject));
            }

        }

    }
}
#endif  /*_Stroika_Foundation_DataExchange_OptionsFile_inl_*/
<|endoftext|>


<commit_before>#include "GBaseProjectile.h"
#include "GWorldForces.h"
#include "GEngine.h"
#include "GWorld.h"
#include "GLogicCamera.h"

#include <FrameworkUPC\GameFramework.h>
#include <math.h>

GBaseProjectile::GBaseProjectile(GEngine* engine) : GBaseActor::GBaseActor(engine),
	mTimeParameter(0.0f),
	mPower(30), // By default 30 radius explosion
	mPosition0(0, 0),
	mSpeed0(0, 0),
	mGravity(0, 0),
	mWind(0, 0) {

	mEngine = engine;
}

void GBaseProjectile::Initialize(float x, float y, float angle, float strength)
{
	GBaseActor::Initialize(x, y, "Sprites/bullet.png");

	mWorld = mEngine->GetWorld();
	mLogicCamera = mEngine->GetLogicCamera();

	//Position
	Vector2 pos = mSprite.GetPosition();
	mPosition0 = Vector2(pos.x - mSprite.GetWidth()*0.5f, pos.y - mSprite.GetHeight()*0.5f);
	mSprite.SetX(mPosition0.x);
	mSprite.SetY(mPosition0.y);

	//Speed
	mSpeed0 = Vector2(cosf(angle)*strength, sinf(angle)*strength);

	//World Forces
	GWorldForces* worldForces = GWorldForces::GET_WORLD_FORCES();
	mWind = worldForces->GetWind();
	mGravity = worldForces->GetGravity();
}

void GBaseProjectile::Update(float dt)
{
	if (!objectAlive) return;

	mTimeParameter += dt;

	float oldX = mX;
	float oldY = mY;

	mX = mPosition0.x + (mSpeed0.x + mWind.x*mTimeParameter)*mTimeParameter*0.5f;
	mY = mPosition0.y + (mSpeed0.y + (mWind.y + mGravity.y)*mTimeParameter)*mTimeParameter*0.5f;

	float dx = mX - oldX;
	float dy = mY - oldY;
	float angle = atan2f(dy, dx) + 1.57f;

	SetRotation(angle);

	Vector2 textureCoordinates = mWorld->ConvertToWorldTextureCoordinates(mX, mY);
	//textureCoordinates.x -= mLogicCamera->GetX();
	//textureCoordinates.y -= mLogicCamera->GetY();

	if (mWorld->ExistsTerrainIn(textureCoordinates.x, textureCoordinates.y))
	{
		mWorld->ExplodeTerrainIn(textureCoordinates.x, textureCoordinates.y, mPower);
		this->KillObject();
	}

	GBaseActor::Update(dt);
}

void GBaseProjectile::Draw(float dt)
{
	if (!objectAlive) return;

	GBaseActor::Draw(dt);
}

GBaseProjectile::~GBaseProjectile() {
	GBaseActor::~GBaseActor();
}<commit_msg>se agrego limites de eliminacion de memoria para la bala<commit_after>#include "GBaseProjectile.h"
#include "GWorldForces.h"
#include "GEngine.h"
#include "GWorld.h"
#include "GLogicCamera.h"

#include <FrameworkUPC\GameFramework.h>
#include <math.h>

GBaseProjectile::GBaseProjectile(GEngine* engine) : GBaseActor::GBaseActor(engine),
	mTimeParameter(0.0f),
	mPower(30), // By default 30 radius explosion
	mPosition0(0, 0),
	mSpeed0(0, 0),
	mGravity(0, 0),
	mWind(0, 0) {

	mEngine = engine;
}

void GBaseProjectile::Initialize(float x, float y, float angle, float strength)
{
	GBaseActor::Initialize(x, y, "Sprites/bullet.png");

	mWorld = mEngine->GetWorld();
	mLogicCamera = mEngine->GetLogicCamera();

	//Position
	Vector2 pos = mSprite.GetPosition();
	mPosition0 = Vector2(pos.x - mSprite.GetWidth()*0.5f, pos.y - mSprite.GetHeight()*0.5f);
	mSprite.SetX(mPosition0.x);
	mSprite.SetY(mPosition0.y);

	//Speed
	mSpeed0 = Vector2(cosf(angle)*strength, sinf(angle)*strength);

	//World Forces
	GWorldForces* worldForces = GWorldForces::GET_WORLD_FORCES();
	mWind = worldForces->GetWind();
	mGravity = worldForces->GetGravity();
}

void GBaseProjectile::Update(float dt)
{
	if (!objectAlive) return;

	mTimeParameter += dt;

	float oldX = mX;
	float oldY = mY;

	mX = mPosition0.x + (mSpeed0.x + mWind.x*mTimeParameter)*mTimeParameter*0.5f;
	mY = mPosition0.y + (mSpeed0.y + (mWind.y + mGravity.y)*mTimeParameter)*mTimeParameter*0.5f;

	float dx = mX - oldX;
	float dy = mY - oldY;
	float angle = atan2f(dy, dx) + 1.57f;

	SetRotation(angle);

	Vector2 textureCoordinates = mWorld->ConvertToWorldTextureCoordinates(mX, mY);
	//textureCoordinates.x -= mLogicCamera->GetX();
	//textureCoordinates.y -= mLogicCamera->GetY();

	if (mWorld->ExistsTerrainIn(textureCoordinates.x, textureCoordinates.y))
	{
		mWorld->ExplodeTerrainIn(textureCoordinates.x, textureCoordinates.y, mPower);
		this->KillObject();
	}

	// calculamos limites
	if ((mX < 0 || mX > mWorld->GetWidth()) || (mY > mWorld->GetHeight())) {
		this->KillObject();
	}

	GBaseActor::Update(dt);
}

void GBaseProjectile::Draw(float dt)
{
	if (!objectAlive) return;

	GBaseActor::Draw(dt);
}

GBaseProjectile::~GBaseProjectile() {
	GBaseActor::~GBaseActor();
}<|endoftext|>