% -*- latex -*-

\chapter{Basic Filter Implementation}
\label{chap:BasicFilterImpl}

\index{filter!implementation|(}

Chapter \ref{chap:SimpleWorklets} introduced the concept of a worklet and demonstrated how to create and run one to execute an algorithm on a device.
Although worklets provide a powerful mechanism for designing heavily threaded visualization algorithms, invoking them requires quite a bit of knowledge of the workings of \VTKm.
Instead, most users execute algorithms in \VTKm using filters.
Thus, to expose algorithms implemented with worklets to general users, we need to implement a filter to encapsulate the worklets.
In this chapter we will create a filter that encapsulates the worklet algorithm presented in Chapter \ref{chap:SimpleWorklets}, which converted the units of a pressure field from pounds per square inch (psi) to Newtons per square meter ($\mathrm{N}/\mathrm{m}^2$).

Filters in \VTKm are implemented by deriving one of the filter base classes provided in \vtkmfilter{}.
There are multiple base filter classes that we can choose from.
These different classes are documented later in Chapter \ref{chap:FilterTypeReference}.
For this example we will use the \vtkmfilter{FilterField} base class, which is used to derive one field from another field.

The following example shows the declaration of our pressure unit conversion filter.
By convention, this declaration would be placed in a header file with a \textfilename{.h} extension.
\VTKm filters are divided into libraries.
In this example, we are assuming this filter is being compiled in a library named \textfilename{vtkm\_filter\_unit\_conversion}.
By convention, the source files would be placed in a directory named \textfilename{vtkm/filter/unit\_conversion}.

\vtkmlisting[ex:SimpleField]{Header declaration for a simple filter.}{SimpleField.cxx}

It is typical for a filter to have a constructor to set up its initial state.
A filter will also override the \classmember*{Filter}{DoExecute} method.
The \classmember*{Filter}{DoExecute} method takes a \vtkmcont{DataSet} as input and likewise returns a \textidentifier{DataSet} containing the results of the filter operation.

Note that the declaration of the \textcode{PoundsPerSquareInchToNewtonsPerSquareMeterFilter} contains the export macro \textmacro{VTKM\_FILTER\_UNIT\_CONVERSION\_EXPORT}.
This is a macro generated by CMake to handle the appropriate modifies for exporting a class from a library.
Remember that this code is to be placed in a library named \textfilename{vtkm\_filter\_unit\_conversion}.
For this library, CMake creates a header file named \textfilename{vtkm\_filter\_unit\_conversion.h} that declares macros like \textmacro{VTKM\_FILTER\_UNIT\_CONVERSION\_EXPORT}.

\begin{didyouknow}
  A filter can also override the \classmember*{Filter}{DoExecutePartitions}, which operates on a \vtkmcont{PartitionedDataSet}.
  If \classmember*{Filter}{DoExecutePartitions} is not overridden, then the filter will call \classmember*{Filter}{DoExecute} on each of the partitions and build a new \textidentifier{PartitionedDataSet} with the outputs.
\end{didyouknow}

Once the filter class is declared in the \textfilename{.h} file, the implementation filter is by convention given in a separate \textfilename{.cxx} file.
Given the definition of our filter in Example \ref{ex:SimpleField}, we will need to provide the implementation for the constructor and the \classmember*{Filter}{DoExecute} method.
The constructor is quite simple.
It initializes the name of the output field name, which is managed by the superclass.

\vtkmlisting[ex:SimpleFieldConstructor]{Constructor for a simple filter.}{SimpleFieldConstructor.cxx}

In this case, we are setting the output field name to the empty string.
This is not to mean that the default name of the output field should be the empty string, which is not a good idea.
Rather, as we will see later, we will use the empty string to flag an output name that should be derived from the input name.

The meat of the filter implementation is located in the \classmember*{Filter}{DoExecute} method.

\vtkmlisting[ex:SimpleFieldDoExecute]{Implementation of \textcode{DoExecute} for a simple filter.}{SimpleFieldDoExecute.cxx}

The single argument to \classmember*{Filter}{DoExecute} is a \vtkmcont{DataSet} containing the data to operate on, and \classmember*{Filter}{DoExecute} returns a derived \textidentifier{DataSet}.
The filter must pull the appropriate information out of the input \textidentifier{DataSet} to operate on.
This simple algorithm just operates on a single field array of the data.
The \textidentifier{FilterField} base class provides several methods to allow filter users to select the active field to operate on.
The filter implementation can get the appropriate field to operate on using the \classmember*{FilterField}{GetFieldFromDataSet} method provided by \textidentifier{FilterField} as shown in Example \ref{ex:SimpleFieldDoExecute} line \ref{ex:SimpleFieldDoExecute.cxx:InputField}.

One of the challenges with writing filters is determining the actual types the algorithm is operating on.
The \textidentifier{Field} object pulled from the input \textidentifier{DataSet} contains an \textidentifier{ArrayHandle} (see Chapter \ref{chap:BasicArrayHandles}), but you do not know what the template parameters of the \textidentifier{ArrayHandle} are.
There are numerous ways to extract an array of an unknown type out of an \textidentifier{ArrayHandle} (many of which will be explored later in Chapter \ref{chap:UnknownArrayHandle}), but the \textidentifier{FilterField} contains some convenience functions to simplify this.

In particular, this filter operates specifically on scalar fields.
For this purpose, \textidentifier{FilterField} provides the \classmember*{FilterField}{CastAndCallScalarField} helper method.
The first argument to \classmember*{FilterField}{CastAndCallScalarField} is the field containing the data to operate on.
The second argument is a functor that will operate on the array once it is identified.
\classmember*{FilterField}{CastAndCallScalarField} will pull a \textidentifier{ArrayHandle} out of the field and call the provided functor with that object.
\classmember*{FilterField}{CastAndCallScalarField} is called in Example \ref{ex:SimpleFieldDoExecute} on line \ref{ex:SimpleFieldDoExecute.cxx:CastAndCall}.

\begin{didyouknow}
  If your filter requires a field containing \vtkm{Vec}s of a particular size (e.g. 3), you can use the convenience method \classmember*{FilterField}{CastAndCallVecField}.
  \classmember*{FilterField}{CastAndCallVecField} works similarly to \classmember*{FilterField}{CastAndCallScalarField} except that it takes a template parameter specifying the size of the \textidentifier{Vec}.
  For example, \classmember*{FilterField}{CastAndCallVecField}\tparams{3}\textcode{(inField, functor);}.
\end{didyouknow}

As previously stated, one of the arguments to \classmember*{FilterField}{CastAndCallScalarField} is a functor that contains the routine to call with the found \textidentifier{ArrayHandle}.
A functor can be created as its own \textcode{class} or \textcode{struct}, but a more convenient method is to use a C++ lambda.
A lambda is an unnamed function defined inline with the code.
The lambda in Example \ref{ex:SimpleFieldDoExecute} starts on line \ref{ex:SimpleFieldDoExecute.cxx:Lambda}.
Apart from being more convenient than creating a named class, lambda functions offer another important feature.
Lambda functions can ``capture'' variables in the current scope.
They can therefore access things like local variables and the \textcode{this} reference to the method's class (even accessing private members).

The callback to the lambda function in Example \ref{ex:SimpleFieldDoExecute} first creates an output \textidentifier{ArrayHandle} of a compatible type (line \ref{ex:SimpleFieldDoExecute.cxx:CreateOutputArray}), then invokes the worklet that computes the derived field (line \ref{ex:SimpleFieldDoExecute.cxx:Invoke}), and finally captures the resulting array.
Note that the \textidentifier{Filter} base class provides an \classmember*{Filter}{Invoke} member that can be used to invoke the worklet.
(See Section \ref{sec:InvokingWorklet} for information on invoking a worklet.)
Recall that the worklet created in Chapter \ref{chap:SimpleWorklets} takes two parameters: an input array and an output array, which are shown in this invocation.

With the output data created, the filter has to build the output structure to return.
All implementations of \classmember*{Filter}{DoExecute} must return a \vtkmcont{DataSet}, and for a simple field filter like this we want to return the same \textidentifier{DataSet} as the input with the output field added.
The output field needs a name, and we get the appropriate name from the superclass (line \ref{ex:SimpleFieldDoExecute.cxx:OutputName}).
However, we would like a special case where if the user does not specify an output field name we construct one based on the input field name.
Recall from Example \ref{ex:SimpleFieldConstructor} that by default we set the output field name to the empty string.
Thus, our filter checks for this empty string, and if it is encountered, it builds a field name by appending ``\_N/M\^{}2'' to it.

Finally, our filter constructs the output \textidentifier{DataSet} using one of the \classmember*{Filter}{CreateResult} member functions (line \ref{ex:SimpleFieldDoExecute.cxx:CreateResult}).
In this particular case, the filter uses \classmember{FilterField}{CreateResultField}, which constructs a \textidentifier{DataSet} with the same structure as the input and adds the computed filter.

\begin{commonerrors}
  The \classmember{NewField}{CreateResult} methods do more than just construct a new \vtkmcont{DataSet}.
  They also set up the structure of the data and pass fields as specified by the state of the filter object.
  Thus, implementations of \classmember*{Filter}{DoExecute} should always return \textidentifier{DataSet}s that were created with \classmember{NewField}{CreateResult} or a similarly named method in the base filter classes.
\end{commonerrors}

This chapter has just provided a brief introduction to creating filters.
There are several more filter superclasses to help express algorithms of different types.
After some more worklet concepts to implement more complex algorithms are introduced in Part \ref{part:Advanced}, we will see a more complete documentation of the types of filters in Chapter \ref{chap:FilterTypeReference}.

\index{filter!implementation|)}
