# Writing a writer

Authors

  Bradley Chambers, Scott Lewis

Contact

  brad.chambers@gmail.com

Date

  10/26/2016

PDAL’s command-line application can be extended through the development of writer functions. In this tutorial, we will give a brief example.

## The header

First, we provide a full listing of the writer header.

     1// MyWriter.hpp
     2
     3#pragma once
     4
     5#include <pdal/Writer.hpp>
     6
     7#include <string>
     8
     9namespace pdal{
    10
    11  typedef std::shared_ptr<std::ostream> FileStreamPtr;
    12
    13  class MyWriter : public Writer
    14  {
    15  public:
    16    MyWriter()
    17    {}
    18
    19    std::string getName() const;
    20
    21  private:
    22    virtual void addArgs(ProgramArgs& args);
    23    virtual void initialize();
    24    virtual void ready(PointTableRef table);
    25    virtual void write(const PointViewPtr view);
    26    virtual void done(PointTableRef table);
    27
    28    std::string m_filename;
    29    std::string m_newline;
    30    std::string m_datafield;
    31    int m_precision;
    32
    33    FileStreamPtr m_stream;
    34    Dimension::Id m_dataDim;
    35  };
    36
    37} // namespace pdal

In your MyWriter class, you will declare the necessary methods and variables needed to make the writer work and meet the plugin specifications.

    1  typedef std::shared_ptr<std::ostream> FileStreamPtr;

FileStreamPtr is defined to make the declaration of the stream easier to manage later on.

        std::string getName() const;

Every stage must return a unique name.

        virtual void addArgs(ProgramArgs& args);
        virtual void initialize();
        virtual void ready(PointTableRef table);
        virtual void write(const PointViewPtr view);
        virtual void done(PointTableRef table);

These methods are used during various phases of the pipeline. There are also more methods, which will not be covered in this tutorial.

        std::string m_filename;
        std::string m_newline;
        std::string m_datafield;
        int m_precision;

        FileStreamPtr m_stream;
        Dimension::Id m_dataDim;

These are variables our Writer will use, such as the file to write to, the newline character to use, the name of the data field to use to write the MyData field, precision of the double outputs, the output stream, and the dimension that corresponds to the data field for easier lookup.

As mentioned, there cen be additional configurations done as needed.

## The source

We will start with a full listing of the writer source.

     1// MyWriter.cpp
     2
     3#include "MyWriter.hpp"
     4#include <pdal/util/FileUtils.hpp>
     5#include <pdal/util/ProgramArgs.hpp>
     6
     7namespace pdal
     8{
     9  static PluginInfo const s_info
    10  {
    11    "writers.mywriter",
    12    "My Awesome Writer",
    13    "http://path/to/documentation"
    14  };
    15
    16  CREATE_SHARED_STAGE(MyWriter, s_info);
    17
    18  std::string MyWriter::getName() const { return s_info.name; }
    19
    20  struct FileStreamDeleter
    21  {
    22    template <typename T>
    23    void operator()(T* ptr)
    24    {
    25      if (ptr)
    26      {
    27        ptr->flush();
    28        FileUtils::closeFile(ptr);
    29      }
    30    }
    31  };
    32
    33  void MyWriter::addArgs(ProgramArgs& args)
    34  {
    35    // setPositional() Makes the argument required.
    36    args.add("filename", "Output filename", m_filename).setPositional();
    37    args.add("newline", "Line terminator", m_newline, "\n");
    38    args.add("datafield", "Data field", m_datafield, "UserData");
    39    args.add("precision", "Precision", m_precision, 3);
    40  }
    41
    42  void MyWriter::initialize()
    43  {
    44    m_stream = FileStreamPtr(FileUtils::createFile(m_filename, true),
    45      FileStreamDeleter());
    46    if (!m_stream)
    47    {
    48      std::stringstream out;
    49      out << "writers.mywriter couldn't open '" << m_filename <<
    50        "' for output.";
    51      throw pdal_error(out.str());
    52    }
    53  }
    54
    55
    56  void MyWriter::ready(PointTableRef table)
    57  {
    58    m_stream->precision(m_precision);
    59    *m_stream << std::fixed;
    60
    61    Dimension::Id d = table.layout()->findDim(m_datafield);
    62    if (d == Dimension::Id::Unknown)
    63    {
    64      std::ostringstream oss;
    65      oss << "Dimension not found with name '" << m_datafield << "'";
    66      throw pdal_error(oss.str());
    67    }
    68
    69    m_dataDim = d;
    70
    71    *m_stream << "#X:Y:Z:MyData" << m_newline;
    72  }
    73
    74
    75  void MyWriter::write(PointViewPtr view)
    76  {
    77      for (PointId idx = 0; idx < view->size(); ++idx)
    78      {
    79        double x = view->getFieldAs<double>(Dimension::Id::X, idx);
    80        double y = view->getFieldAs<double>(Dimension::Id::Y, idx);
    81        double z = view->getFieldAs<double>(Dimension::Id::Z, idx);
    82        unsigned int myData = 0;
    83
    84        if (!m_datafield.empty()) {
    85          myData = (int)(view->getFieldAs<double>(m_dataDim, idx) + 0.5);
    86        }
    87
    88        *m_stream << x << ":" << y << ":" << z << ":"
    89          << myData << m_newline;
    90      }
    91  }
    92
    93
    94  void MyWriter::done(PointTableRef)
    95  {
    96    m_stream.reset();
    97  }
    98}

In the writer implementation, we will use a macro defined in pdal_macros, which is included in the include chain we are using.

      static PluginInfo const s_info
      {
        "writers.mywriter",
        "My Awesome Writer",
        "http://path/to/documentation"
      };

      CREATE_SHARED_STAGE(MyWriter, s_info);

Here we define a struct with information regarding the writer, such as the name, a description, and a path to documentation. We then use the macro to create a SHARED stage, which means it will be external to the main PDAL installation. When using the macro, we specify the name of the Stage and the PluginInfo struct we defined earlier.

When making a shared plugin, the name of the shared library must correspond with the name of the writer provided here. The name of the generated shared object must be

::

  libpdal_plugin_writer_<writer name>.<shared library extension>

     1  struct FileStreamDeleter
     2  {
     3    template <typename T>
     4    void operator()(T* ptr)
     5    {
     6      if (ptr)
     7      {
     8        ptr->flush();
     9        FileUtils::closeFile(ptr);
    10      }
    11    }
    12  };

This struct is used for helping with the FileStreamPtr for cleanup.

    1  void MyWriter::addArgs(ProgramArgs& args)
    2  {
    3    // setPositional() Makes the argument required.
    4    args.add("filename", "Output filename", m_filename).setPositional();
    5    args.add("newline", "Line terminator", m_newline, "\n");
    6    args.add("datafield", "Data field", m_datafield, "UserData");
    7    args.add("precision", "Precision", m_precision, 3);
    8  }

This method defines the arguments the writer provides and binds them to private variables.

      void MyWriter::initialize()
      {
        m_stream = FileStreamPtr(FileUtils::createFile(m_filename, true),
          FileStreamDeleter());
        if (!m_stream)
        {
          std::stringstream out;
          out << "writers.mywriter couldn't open '" << m_filename <<
            "' for output.";
          throw pdal_error(out.str());
        }
      }

This method initializes our file stream in preparation for writing.

     1  void MyWriter::ready(PointTableRef table)
     2  {
     3    m_stream->precision(m_precision);
     4    *m_stream << std::fixed;
     5
     6    Dimension::Id d = table.layout()->findDim(m_datafield);
     7    if (d == Dimension::Id::Unknown)
     8    {
     9      std::ostringstream oss;
    10      oss << "Dimension not found with name '" << m_datafield << "'";
    11      throw pdal_error(oss.str());
    12    }
    13
    14    m_dataDim = d;
    15
    16    *m_stream << "#X:Y:Z:MyData" << m_newline;
    17  }

The ready method is used to prepare the writer for any number of PointViews that may be passed in. In this case, we are setting the precision for our double writes, looking up the dimension specified as the one to write into MyData, and writing the header of the output file.

     1  void MyWriter::write(PointViewPtr view)
     2  {
     3      for (PointId idx = 0; idx < view->size(); ++idx)
     4      {
     5        double x = view->getFieldAs<double>(Dimension::Id::X, idx);
     6        double y = view->getFieldAs<double>(Dimension::Id::Y, idx);
     7        double z = view->getFieldAs<double>(Dimension::Id::Z, idx);
     8        unsigned int myData = 0;
     9
    10        if (!m_datafield.empty()) {
    11          myData = (int)(view->getFieldAs<double>(m_dataDim, idx) + 0.5);
    12        }
    13
    14        *m_stream << x << ":" << y << ":" << z << ":"
    15          << myData << m_newline;
    16      }
    17  }

This method is the main method for writing. In our case, we are writing a very simple file, with data in the format of X:Y:Z:MyData. We loop through each index in the PointView, and for each one we take the X, Y, and Z values, as well as the value for the specified MyData dimension, and write this to the output file. In particular, note the reading of MyData; in our case, MyData is an integer, but the field we are reading might be a double. Converting from double to integer is done via truncation, not rounding, so by adding .5 before making the conversion will ensure rounding is done properly.

Note that in this case, the output format is pretty simple. For more complex outputs, you may need to generate helper methods (and possibly helper classes) to help generate the proper output. The key is reading in the appropriate values from the PointView, and then writing those in whatever necessary format to the output stream.

    1  void MyWriter::done(PointTableRef)
    2  {
    3    m_stream.reset();
    4  }

This method is called when the writing is done. In this case, it simply cleans up the output stream by resetting it.

## Compiling and Usage

To compile this reader, we will use cmake. Here is the CMakeLists.txt file we will use for this process:

     1cmake_minimum_required(VERSION 2.8.12)
     2project(WriterTutorial)
     3
     4find_package(PDAL 2.0.0 REQUIRED CONFIG)
     5set(CMAKE_CXX_STANDARD 11)
     6set(CMAKE_CXX_STANDARD_REQUIRED ON)
     7
     8add_library(pdal_plugin_writer_mywriter SHARED MyWriter.cpp)
     9target_link_libraries(pdal_plugin_writer_mywriter PRIVATE ${PDAL_LIBRARIES})
    10
    11target_link_directories(pdal_plugin_writer_mywriter PRIVATE ${PDAL_LIBRARY_DIRS})
    12target_include_directories(pdal_plugin_writer_mywriter PRIVATE
    13    ${PDAL_INCLUDE_DIRS})

If this file is in the directory with the MyWriter.hpp and MyWriter.cpp files, simply run `cmake .` followed by `make`. This will generate a file called `libpdal_plugin_writer_mywriter.dylib`.

Put this dylib file into the directory pointed to by `PDAL_DRIVER_PATH`, and then when you run `pdal --drivers`, you will see an entry for writers.mywriter.

To test the writer, we will put it into a pipeline and read in a LAS file and covert it to our output format. For this example, use interesting.las, and run it through pipeline-mywriter.json.

If those files are in the same directory, you would just run the command `pdal pipeline pipeline-mywriter.json`, and it will generate an output file called output.txt, which will be in the proper format. From there, if you wanted, you could run that output file through the MyReader that was created in the previous tutorial, as well.