/*****************************************************************************
*
* Copyright (c) 2000 - 2018, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

// ************************************************************************* //
//                              avtPLYWriter.C                             //
// ************************************************************************* //

#include <avtPLYWriter.h>

#include <vector>
#include <vtkAppendPolyData.h>
#include <vtkCharArray.h>
#include <vtkTriangleFilter.h>
#include <vtkGeometryFilter.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkPointData.h>

#include <vtkScalarsToColors.h>
#include <vtkColorTransferFunction.h>
#include <avtColorTables.h>
#include <ColorTableAttributes.h>
#include <ColorControlPointList.h>
#include <ColorControlPoint.h>

#include <vtkPolyData.h>
#include <vtkPLYWriter.h>
#include <avtDatabaseMetaData.h>
#include <DBOptionsAttributes.h>
#include <DebugStream.h>
#include <avtParallel.h>
#ifdef PARALLEL
  #include <mpi.h>
#endif

using     std::string;
using     std::vector;


// ****************************************************************************
//  Method: avtPLYWriter constructor
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
// ****************************************************************************

avtPLYWriter::avtPLYWriter(DBOptionsAttributes *atts)
{
    doBinary = atts->GetBool("Binary format");
    doColor = atts->GetBool("Output colors");
    colorTable = atts->GetString("Color table");
    colorTableMin = atts->GetDouble("Color table min");
    colorTableMax = atts->GetDouble("Color table max");
}

// ****************************************************************************
//  Method: avtPLYWriter::OpenFile
//
//  Purpose:
//      Does no actual work.  Just records the stem name for the files.
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
// ****************************************************************************

void
avtPLYWriter::OpenFile(const string &stemname, int numblocks)
{
    stem = stemname;
}


// ****************************************************************************
//  Method: avtPLYWriter::WriteHeaders
//
//  Purpose:
//      Writes out a VisIt file to tie the PLY files together.
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
// ****************************************************************************

void
avtPLYWriter::WriteHeaders(const avtDatabaseMetaData *md,
                           const vector<string> &scalars,
                           const vector<string> &vectors,
                           const vector<string> &materials)
{
    // WRITE OUT HEADER INFO
}


// ****************************************************************************
//  Method: avtPLYWriter::WriteChunk
//
//  Purpose:
//      This writes out one chunk of an avtDataset.
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
//  Modifications:
//    Brad Whitlock, Tue Sep  8 17:28:35 PDT 2015
//    Rely on base class to combine data.
//
// ****************************************************************************

void
avtPLYWriter::WriteChunk(vtkDataSet *ds, int chunk)
{
    if (ds->GetNumberOfCells() == 0)
    {
        debug4 << "avtPLYWriter::WriteChunk: No data to write" << endl;
        return;
    }

    std::string filename;
    if(writeContext.GroupSize() > 1)
    {
        char ext[20];
        SNPRINTF(ext, 20, ".%d.ply", writeContext.GroupRank());
        filename = stem + ext;
    }
    else
        filename = stem + ".ply";


    vtkPLYWriter *writer = vtkPLYWriter::New();
    writer->SetFileName(filename.c_str());
    if(doBinary)
        writer->SetFileTypeToBinary();
    else
        writer->SetFileTypeToASCII();

    writer->SetInputData(ds);

    if (doColor && ds->GetPointData()->GetScalars())
    {
        vtkScalarsToColors *lut = GetColorTable();
        if (lut)
        {
            writer->SetArrayName(ds->GetPointData()->GetScalars()->GetName());
            writer->SetLookupTable(lut);
        }
    }
    
    writer->Update();
//    writer->Write();
    writer->Delete();
}

// ****************************************************************************
//  Method: avtPLYWriter::CloseFile
//
//  Purpose:
//      Closes the file.  This does nothing in this case.
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
//  Modifications:
//
// ****************************************************************************

void
avtPLYWriter::CloseFile(void)
{
}

// ****************************************************************************
// Method: avtPLYWriter::CreateTrianglePolyData
//
// Purpose:
//   Tell VisIt's export that we'll want triangles.
//
// Returns:    True
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep  8 17:00:23 PDT 2015
//
// Modifications:
//
// ****************************************************************************

bool
avtPLYWriter::CreateTrianglePolyData() const
{
    return true;
}

// ****************************************************************************
//  Method: avtTecplotWriter::GetCombineMode
//
//  Purpose:
//     Provides a hint to the export mechanism to tell it how to combine data.
//
//  Note: We combine geometry because PLY tools will want 1 file.
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Sep  8 15:36:45 PDT 2015
//
// ****************************************************************************

avtDatabaseWriter::CombineMode
avtPLYWriter::GetCombineMode(const std::string &) const
{
    return CombineAll;
}

//****************************************************************************
// Method:  avtPLYWriter::GetColorTable()
//
// Purpose:
//   Create color table
//
//
// Programmer:  Dave Pugmire
// Creation:    April 26, 2013
//
// Modifications:
//
//****************************************************************************

vtkScalarsToColors *
avtPLYWriter::GetColorTable()
{
    const ColorTableAttributes *colorTables = avtColorTables::Instance()->GetColorTables();
    int nCT = colorTables->GetNumColorTables();
    for (int i=0; i<nCT; i++)
    {
        if (colorTables->GetNames()[i] == colorTable)
        {
            const ColorControlPointList &table = colorTables->GetColorTables(i);
            vtkColorTransferFunction *lut = vtkColorTransferFunction::New();

            double *vals = new double[3*table.GetNumControlPoints()];
            for (int j=0; j<table.GetNumControlPoints(); j++)
            {
                const ColorControlPoint &pt = table.GetControlPoints(j);
                vals[j*3 + 0] = pt.GetColors()[0]/255.0;
                vals[j*3 + 1] = pt.GetColors()[1]/255.0;
                vals[j*3 + 2] = pt.GetColors()[2]/255.0;
            }
            
            lut->BuildFunctionFromTable(colorTableMin, colorTableMax, table.GetNumControlPoints(), vals);
            delete [] vals;

            return lut;
        }
    }
    return NULL;
}
