writing PointData to UnstructuredGrid (and Xdmf time series)

I’m trying to write only Points and PointData to an UnstructuredGrid type.
I can’t find any examples on how to do this so having difficulties figuring it out, but I think I’m 90% of the way there I think.

My points work fine. My point data doesn’t write. I can create the data and give it a name. When I look in the file, the name and some other metadata are there, but the data is all zeroes even tho I assigned it.

I’d also like to utilize Xdmf3’s time series storage, which I know is supported through the VTK writer, but I also can’t figure out how to write multiple timesteps.

#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkUnstructuredGrid.h>
#include <vtkXMLUnstructuredGridWriter.h>
#include <vtkXdmf3Writer.h>
#include <vtkDoubleArray.h>

int main()
{
    vtkNew<vtkPoints> points;
    points->SetNumberOfPoints(3);
    points->SetPoint(0, 0, 0, 0);
    points->SetPoint(1, 0, 0, 1);
    points->SetPoint(2, 0, 1, 0);
    points->Modified();

    vtkNew<vtkDoubleArray> data;
    data->Allocate(3);
    data->SetName("NAME");
    data->SetValue(0, 42);
    data->SetValue(1, 42);
    data->SetValue(2, 42);
    data->Modified();

    vtkNew<vtkUnstructuredGrid> grid;
    grid->SetPoints(points);
    grid->GetPointData()->AddArray(data);

    vtkNew<vtkXMLUnstructuredGridWriter> writer1;
    writer1->SetFileName("0.vtu");
    writer1->SetInputData(grid);
    writer1->Write();

    vtkNew<vtkXdmf3Writer> writer2;
    writer2->SetFileName("0.xdmf");
    writer2->SetInputData(grid);
    writer2->Write();

I’m compiling with CMake.

cmake_minimum_required(VERSION 3.20)
project(A)
find_package(VTK COMPONENTS IOXML IOXdmf3)
add_executable(a a.cc)
target_link_libraries(a PRIVATE ${VTK_LIBRARIES})

I believe that you have to replace “Allocate()” with “SetNumberOfTuples()” as follows. Allocate() is analogous to std::vector.reserve() - it allocates memory but does not change the size (i.e., number of tuples) of the data array.

vtkNew data; data->SetNumberOfTuples(3); //instead if Allocate(3) data->SetName(“NAME”); data->SetValue(0, 42); data->SetValue(1, 42); data->SetValue(2, 42);

Ah I see, I misinterpreted the Allocate function. This solution works, thanks a lot! It was confusing because I used data->GetSize() to check the size, and sure enough it was 3. data->GetTuples() however was still 0. With your solution, both are 3. So I guess GetSize() returns the reserved size.