//=========================================================================
//#
//#  pfCAVEhead-sproc.cxx                              #####     
//#                                                   ##   ##
//#  Author(s): Paul Rajlich                          ##
//#  Email: prajlich@ncsa.uiuc.ed                     ##   ##
//#  Date created:                                     #####
//#
//#  Description: parallel vtk pipelines pfCAVE example
//#    based on medical1.cxx from vtk 2.x distribution
//#
//=========================================================================

#include <stdio.h>
#include <stdlib.h>
#include <Performer/pf/pfChannel.h>
#include <Performer/pf/pfLightSource.h>
#include <Performer/pf/pfDCS.h>
#include <Performer/pf/pfSwitch.h>
#include <X11/X.h>
#include <X11/keysym.h>

#include "vtkMarchingCubes.h"
#include "vtkVolume16Reader.h"
#include "vtkExtractVOI.h"
#include "vtkOutlineFilter.h"

#include "vtkActorToPFTranslatorParallel.h"

void readData();
void doThreads();
void initPF();
void pfMainLoop();
void vtkInit();
void vtkMainLoop();
void m_print(char *);
void initWindow();
void updateUser();

vtkStructuredPoints *vol;
vtkMarchingCubes *shellExtractor[64];
vtkActorToPFTranslatorParallel *translator[64];
pfChannel *chan;
Display *dsp;
pfDCS *centerDcs, *transDcs;
pfGroup *isoGroup;
pfSwitch *outlineSwitch;
float center[3], bounds[3];

int NPROCS = 1;
float ISOVAL = 500.0f;
float ROT_H = 0.0f;


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

  // user can specify number of vtk threads or use default
  if (argc > 1)
    NPROCS = atoi(argv[1]);
  else
    NPROCS = m_get_numprocs()-1;

  if (NPROCS > 64) NPROCS = 64;
  if (NPROCS < 1) NPROCS = 1;

  m_set_procs(NPROCS+1);

  // initialize pfCAVE app
  pfInit();
  pfMultiprocess(0);
  pfConfig();

  initWindow();

  // geodes will be added to this
  centerDcs = new pfDCS();
  isoGroup = new pfGroup();
  outlineSwitch = new pfSwitch();
  outlineSwitch->setVal(PFSWITCH_ON);
  centerDcs->addChild(isoGroup);
  centerDcs->addChild(outlineSwitch);

  // read data - only do once (before threads start)
  readData();

  // note: m_fork uses sproc(). See man pages for m_fork()
  cout << "Number of vtk threads will be " << m_get_numprocs()-1 << endl;
  m_fork(doThreads);
 
  // clean up 
  pfExit();
}

// this is called before threads start
void readData() {
  cout << "loading data...";
  cout.flush();
  vtkVolume16Reader *volReader = vtkVolume16Reader::New();
  volReader->SetDataDimensions(64, 64);
  volReader->SwapBytesOn();
  volReader->SetFilePrefix("../../vtkdata/headsq/quarter");
  volReader->SetDataSpacing(3.2, 3.2, 1.5);
  volReader->SetImageRange(1, 93);
  volReader->Update(); // do it
  cout << "done." << endl;

  // set global pointer to data
  vol = volReader->GetOutput();
  vol->GetCenter(center);
  vol->GetBounds(bounds);
}


// only one thread can print a messge at one time
void m_print(char *str) {
  m_lock();
  cout << str << endl;
  m_unlock();
}

// m_fork called sproc() to generate threads with ids 0..n-1
void doThreads() {
  if (m_get_myid() == 0) {  // Performer thread
    m_print("pf loop thread started.");
    initPF();
    m_sync(); // barrier - wait for all vtk threads to finish initializing
    pfMainLoop();
  }
  else {                  // VTK threads
    char str[8];
    sprintf(str, "vtk thread %d started.", m_get_myid()-1);
    m_print(str);
    vtkInit(); 
    m_sync(); // barrier
    vtkMainLoop();
  }
}

// each vtk thread runs this loop
void vtkMainLoop() {
  int i = m_get_myid()-1;
  char str[8];
  sprintf(str, "vtk main loop %d started.", i);
  m_print(str);
  while (1) {
    // will only "modify" shellExtractor if different than previous value
    shellExtractor[i]->SetValue(0, ISOVAL);
    // idea here is that the translator is continually looking to re-execute
    translator[i]->Update();
    sginap(5);
  }
}

// main performer application loop
void pfMainLoop() {
  int i = m_get_myid()-1;
  m_print("pf main loop started.");
  while (1) {
    updateUser();
    pfSync();
    pfFrame();
  }
}

// setup vtk pipeline and translators
void vtkInit() {
  int i = m_get_myid()-1;
  m_print("entering initVTK()...");

  // Volume of interest... will be used to do data decomposition.
  // NOTE: only one thread can extract its VOI at a time.
  m_lock();
  vtkExtractVOI *extractVOI = vtkExtractVOI::New();
  extractVOI->SetInput(vol);
  int *dims = vol->GetDimensions();
  float zslab = ((float) dims[2])/NPROCS;
  extractVOI->SetVOI(0, dims[0], 0, dims[1], i*zslab, (i+1)*zslab);
  extractVOI->Update(); // do it!
  m_unlock();

  vtkOutlineFilter *outlineF = vtkOutlineFilter::New();
  outlineF->SetInput(extractVOI->GetOutput());

  vtkPolyDataMapper *outlineMapper = vtkPolyDataMapper::New();
  outlineMapper->SetInput(outlineF->GetOutput());
  outlineMapper->ScalarVisibilityOff();

  vtkActor *outlineActor = vtkActor::New();
  outlineActor->SetMapper(outlineMapper);
  outlineActor->GetProperty()->SetColor(0.7, 0.7, 0.7);

  shellExtractor[i] = vtkMarchingCubes::New();
  shellExtractor[i]->SetInput(extractVOI->GetOutput());
  shellExtractor[i]->SetValue(0, ISOVAL);

  vtkPolyDataMapper *shellMapper = vtkPolyDataMapper::New();
  shellMapper->SetInput(shellExtractor[i]->GetOutput());
  shellMapper->ScalarVisibilityOff(); // use overall color

  vtkActor *shellActor = vtkActor::New();
  shellActor->SetMapper(shellMapper);
  shellActor->GetProperty()->SetColor(1.0, 1.0, 1.0);

  // translators
  translator[i] = vtkActorToPFTranslatorParallel::New(shellActor);
  translator[i]->Update();

  vtkActorToPFTranslatorParallel *outlineT;
  outlineT = vtkActorToPFTranslatorParallel::New(outlineActor);
  outlineT->Update();

  // only one thread can add nodes to the scenegraph at a time
  m_lock();
  isoGroup->addChild(translator[i]->GetGeode());
  outlineSwitch->addChild(outlineT->GetGeode());
  m_unlock();

  m_print("exiting initVTK().");
}

// initialize performer scene
void initPF() {
  m_print("entering initPF()...");

  pfScene *scene;
  pfGeoState *gstate;
  pfLightSource *light;
  scene = new pfScene;
  gstate = new pfGeoState;
  gstate->setMode(PFSTATE_ENLIGHTING, PF_ON);
  gstate->setMode(PFSTATE_CULLFACE, PFCF_OFF);
  scene->setGState(gstate);

  light = new pfLightSource;
  light->setColor(PFLT_DIFFUSE, 1.0, 1.0, 1.0);
  light->setAmbient(0.0, 0.0, 0.0);
  scene->addChild(light);

  // create pfDCS that will center/scale the geometry
  float scaleFactor = 5.0/(bounds[1] - bounds[0]);

  // order in DCS is S*R*T. Centered vtk geometry (see below) will be
  // scaled, rotated, then translated.
  transDcs = new pfDCS();
  transDcs->setScale(scaleFactor, scaleFactor, scaleFactor);
  transDcs->setRot(ROT_H, 180.0f, 0.0);
  transDcs->setTrans(0.0, 10.0, 0.0);

  // center vtk geometry
  centerDcs->setTrans(-center[0], -center[1], -center[2]);
  transDcs->addChild(centerDcs);
  scene->addChild(transDcs);

  chan->setScene(scene);

  m_print("exiting initPF().");
}

void initWindow() {
  // setup Performer window
  pfPipe *p = pfGetPipe(0);
  pfPipeWindow *pw = new pfPipeWindow(p);
  pw->setWinType(PFPWIN_TYPE_X);
  pw->setName("Parallel vtkActorToPF");
  pw->setOriginSize(100, 100, 500, 500);
  pw->open();

  // set up X input event handling
  dsp = pfGetCurWSConnection();

  // Thanks to Jan Ehrhardt for this fix!
  // wait until pw is open otherwise code below (xwin) will fail...
  while (!pw->isOpen())
    pfFrame(); // keep doing pfFrame to trigger draw

  Window xwin = pw->getWSWindow();
  XSelectInput(dsp, xwin,  KeyPressMask );
  XMapWindow(dsp, xwin);
  XSync(dsp,FALSE);

  chan = new pfChannel(p);
}
    
void updateUser() {
  // non-blocking... 
  while (XPending(dsp)) {
   XEvent event;
   XNextEvent(dsp, &event);
   switch(event.type) {
     case KeyPress: {
       char buf[100];
       //int rv;
       KeySym ks;
       XLookupString(&event.xkey, buf, sizeof(buf), &ks, 0);
       switch(ks) {
         case XK_Escape:
           exit(0);
           break;
         case XK_Up: // up arrow key
           ISOVAL += 100.0f;
           cout << "setting isoval to " << ISOVAL << endl;
           break;
         case XK_Down: // down arrow key
           ISOVAL -= 100.0f;
           cout << "setting isoval to " << ISOVAL << endl;
           break;
         case XK_Left:
           ROT_H -= 5.0;
           transDcs->setRot(ROT_H, 180.0, 0.0);
           break;
         case XK_Right:
           ROT_H += 5.0;
           transDcs->setRot(ROT_H, 180.0, 0.0);
           break;
         case XK_o:
           if (outlineSwitch->getVal() == PFSWITCH_ON)
             outlineSwitch->setVal(PFSWITCH_OFF);
           else
             outlineSwitch->setVal(PFSWITCH_ON);
           break;
         default:
           break;
       }
     } // keypress case
   } // event switch
 } // while event
}

