vtkMatplotlibMathTextUtilities.cxx 31 KB
Newer Older
David C. Lonie's avatar
David C. Lonie committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkMatplotlibMathTextUtilities.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkMatplotlibMathTextUtilities.h"

18
19
20
21
22
23
24
// Prevent redefined symbol warnings in vtkPython.h:
#ifdef _POSIX_C_SOURCE
#  undef _POSIX_C_SOURCE
#endif // _POSIX_C_SOURCE
#ifdef _XOPEN_SOURCE
#  undef _XOPEN_SOURCE
#endif // _XOPEN_SOURCE
25
26
27
#ifdef _LARGEFILE_SOURCE
#  undef _LARGEFILE_SOURCE
#endif // _LARGEFILE_SOURCE
David C. Lonie's avatar
David C. Lonie committed
28
29
30
#include "vtkPython.h"

#include "vtkImageData.h"
31
32
33
#include "vtkImageReslice.h"
#include "vtkMath.h"
#include "vtkNew.h"
David C. Lonie's avatar
David C. Lonie committed
34
35
36
#include "vtkObjectFactory.h"
#include "vtkPath.h"
#include "vtkPoints.h"
37
#include "vtkStdString.h"
David C. Lonie's avatar
David C. Lonie committed
38
#include "vtkTextProperty.h"
39
#include "vtkTransform.h"
David C. Lonie's avatar
David C. Lonie committed
40

41
42
#include <vtksys/SystemTools.hxx>

David C. Lonie's avatar
David C. Lonie committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <vector>

// Smart pointer for PyObjects. Calls Py_XDECREF when scope ends.
class SmartPyObject
{
  PyObject *Object;

public:
  SmartPyObject(PyObject *obj = NULL)
    : Object(obj)
  {
  }

  ~SmartPyObject()
  {
    Py_XDECREF(this->Object);
  }

  PyObject *operator->() const
  {
    return this->Object;
  }

  PyObject *GetPointer() const
  {
    return this->Object;
  }
};

//----------------------------------------------------------------------------
73
74
75
76
vtkMatplotlibMathTextUtilities::Availablity
vtkMatplotlibMathTextUtilities::MPLMathTextAvailable =
    vtkMatplotlibMathTextUtilities::NOT_TESTED;

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// A macro that is used in New() to print warnings if VTK_MATPLOTLIB_DEBUG
// is defined in the environment. Use warnings to allow this to work in
// release mode builds. This is adapted from vtkWarningWithObjectMacro
#define vtkMplStartUpDebugMacro(x)                             \
if (debug)                                                     \
  {                                                            \
  if (vtkObject::GetGlobalWarningDisplay())                    \
    {                                                          \
    vtkOStreamWrapper::EndlType endl;                          \
    vtkOStreamWrapper::UseEndl(endl);                          \
    vtkOStrStreamWrapper vtkmsg;                               \
    vtkmsg << "Warning: In " __FILE__ ", line " << __LINE__    \
           << "\nvtkMatplotlibMathTextUtilities::New(): "      \
           << x << "\n\n";                                     \
    vtkOutputWindowDisplayWarningText(vtkmsg.str());           \
    vtkmsg.rdbuf()->freeze(0);                                 \
    }                                                          \
  }

96
97
98
//----------------------------------------------------------------------------
vtkMatplotlibMathTextUtilities* vtkMatplotlibMathTextUtilities::New()
{
99
100
101
102
  // Enable startup debugging output. This will be set to true when
  // VTK_MATPLOTLIB_DEBUG is defined in the process environment.
  bool debug = false;

103
104
105
106
107
108
109
110
111
  // Attempt to import matplotlib to check for availability
  switch (vtkMatplotlibMathTextUtilities::MPLMathTextAvailable)
    {
    default:
    case vtkMatplotlibMathTextUtilities::UNAVAILABLE:
      return NULL;
    case vtkMatplotlibMathTextUtilities::AVAILABLE:
      break;
    case vtkMatplotlibMathTextUtilities::NOT_TESTED:
112

113
114
      // Print setup details if this env flag is set. The debug variable is used
      // by the vtkMplStartUpDebugMacro.
115
      debug = (vtksys::SystemTools::GetEnv("VTK_MATPLOTLIB_DEBUG") != NULL);
116

117
      // Initialize the python interpretor if needed
118
      vtkMplStartUpDebugMacro("Testing if matplotlib is already init'd.");
119
120
121
      if (!Py_IsInitialized())
        {
        // Check for a specified interpreter in the system environment.
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
        vtkMplStartUpDebugMacro("Not initialized. Checking "
                                "VTK_MATPLOTLIB_PYTHONHOME.");

        vtkStdString mplPyHome;
        if (vtksys::SystemTools::GetEnv("VTK_MATPLOTLIB_PYTHONHOME",
                                        mplPyHome) &&
            mplPyHome.size() != 0)
          {
          vtkMplStartUpDebugMacro("VTK_MATPLOTLIB_PYTHONHOME="<<mplPyHome);
          Py_SetPythonHome(const_cast<char*>(mplPyHome.c_str()));
          }
        else
          {
          vtkMplStartUpDebugMacro("VTK_MATPLOTLIB_PYTHONHOME undefined.");
          }

        vtkMplStartUpDebugMacro("Checking VTK_MATPLOTLIB_PYTHONINTERP.");
139
140
141
142
143
        vtkStdString mplPyInterp;
        if (vtksys::SystemTools::GetEnv("VTK_MATPLOTLIB_PYTHONINTERP",
                                        mplPyInterp) &&
            mplPyInterp.size() != 0)
          {
144
          vtkMplStartUpDebugMacro("VTK_MATPLOTLIB_PYTHONINTERP="<<mplPyInterp);
145
146
          Py_SetProgramName(const_cast<char*>(mplPyInterp.c_str()));
          }
147
148
149
150
151
152
153
154
        else
          {
          vtkMplStartUpDebugMacro("VTK_MATPLOTLIB_PYTHONINTERP undefined.");
          }

        vtkMplStartUpDebugMacro("Initializing python. (if there is a segfault "
                                "and error 'ImportError: No module named site',"
                                " VTK_MATPLOTLIB_PYTHONHOME is incorrect).");
155
156
157
        Py_Initialize();
        }

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
      if (!Py_IsInitialized())
        {
        vtkMplStartUpDebugMacro("Python environment failed to initialize. "
                                "Matplotlib will be unavailable.");
        vtkMatplotlibMathTextUtilities::MPLMathTextAvailable = UNAVAILABLE;
        return NULL;
        }

      vtkMplStartUpDebugMacro("Python environment initialized. Checking "
                              "VTK_MATPLOTLIB_PYTHONPATH.");

      PyObject *pypath = PySys_GetObject(const_cast<char*>("path"));
      vtkStdString envPaths;
      if (vtksys::SystemTools::GetEnv("VTK_MATPLOTLIB_PYTHONPATH",
                                      envPaths) && envPaths.size() != 0)
        {
        vtkMplStartUpDebugMacro("VTK_MATPLOTLIB_PYTHONPATH=" << envPaths);

        // Split paths and prepend them to the python path object.
#ifdef _WIN32
        char delim = ';';
#else // _WIN32
        char delim = ':';
#endif // _WIN32
        size_t pathEnd = vtkStdString::npos;
        size_t pathStart = envPaths.rfind(delim, pathEnd);
        while (pathStart != vtkStdString::npos)
          {
          vtkStdString envPath(envPaths, pathStart + 1,
                               pathEnd == vtkStdString::npos
                               ? vtkStdString::npos : pathEnd - pathStart);
          PyList_Insert(pypath, 0, PyString_FromString(envPath.c_str()));
          pathEnd = pathStart - 1;
          pathStart = envPaths.rfind(delim, pathEnd);
          }
        vtkStdString envPath(envPaths, 0,
                             pathEnd == vtkStdString::npos
                             ? vtkStdString::npos : pathEnd + 1);
        PyList_Insert(pypath, 0, PyString_FromString(envPath.c_str()));
        }
      else
        {
        vtkMplStartUpDebugMacro("VTK_MATPLOTLIB_PYTHONPATH undefined.");
        }

      SmartPyObject pypathStr = PyObject_Str(pypath);
      vtkMplStartUpDebugMacro("sys.path =\n"
                              << PyString_AsString(pypathStr.GetPointer()));


      vtkMplStartUpDebugMacro("Attempting to import matplotlib.");
209
210
211
212
      if (PyErr_Occurred() ||
          !PyImport_ImportModule("matplotlib") ||
          PyErr_Occurred())
        {
213
214
215
        vtkMplStartUpDebugMacro("Error occurred. Writing exception info to "
                                "stdout/stderr.");
        PyErr_PrintEx(0);
216
        vtkMatplotlibMathTextUtilities::MPLMathTextAvailable = UNAVAILABLE;
217
        return NULL;
218
219
220
        }
      else
        {
221
        vtkMplStartUpDebugMacro("Successfully imported matplotlib.");
222
223
224
225
        vtkMatplotlibMathTextUtilities::MPLMathTextAvailable = AVAILABLE;
        }
      break;
    }
226
227
228
229
230
231
232
233
234
235
  // Adapted from VTK_OBJECT_FACTORY_NEW_BODY to enable debugging output when
  // requested.
  vtkObject* ret =
      vtkObjectFactory::CreateInstance("vtkMatplotlibMathTextUtilities");
  if(ret)
    {
    ret->SetDebug(debug);
    return static_cast<vtkMatplotlibMathTextUtilities*>(ret);
    }
  return new vtkMatplotlibMathTextUtilities;
236
237
}
vtkInstantiatorNewMacro(vtkMatplotlibMathTextUtilities)
David C. Lonie's avatar
David C. Lonie committed
238
239
240

//----------------------------------------------------------------------------
vtkMatplotlibMathTextUtilities::vtkMatplotlibMathTextUtilities()
241
242
  : Superclass(), MaskParser(NULL), PathParser(NULL), FontPropertiesClass(NULL),
    ScaleToPowerOfTwo(true)
David C. Lonie's avatar
David C. Lonie committed
243
244
245
246
247
248
249
250
251
{
}

//----------------------------------------------------------------------------
vtkMatplotlibMathTextUtilities::~vtkMatplotlibMathTextUtilities()
{
  Py_XDECREF(this->MaskParser);
  Py_XDECREF(this->PathParser);
  Py_XDECREF(this->FontPropertiesClass);
252
  Py_Finalize();
David C. Lonie's avatar
David C. Lonie committed
253
254
255
256
257
}

//----------------------------------------------------------------------------
bool vtkMatplotlibMathTextUtilities::InitializeMaskParser()
{
David C. Lonie's avatar
David C. Lonie committed
258
  SmartPyObject mplMathTextLib(PyImport_ImportModule("matplotlib.mathtext"));
David C. Lonie's avatar
David C. Lonie committed
259
260
261
262
263
  if (this->CheckForError(mplMathTextLib.GetPointer()))
    {
    return false;
    }

David C. Lonie's avatar
David C. Lonie committed
264
265
  SmartPyObject mathTextParserClass(
        PyObject_GetAttrString(mplMathTextLib.GetPointer(), "MathTextParser"));
David C. Lonie's avatar
David C. Lonie committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
  if (this->CheckForError(mathTextParserClass.GetPointer()))
    {
    return false;
    }

  this->MaskParser =
      PyObject_CallFunction(mathTextParserClass.GetPointer(),
                            const_cast<char*>("s"), "bitmap");
  if (this->CheckForError(this->MaskParser))
    {
    Py_CLEAR(this->MaskParser);
    return false;
    }

  return true;
}

//----------------------------------------------------------------------------
bool vtkMatplotlibMathTextUtilities::InitializePathParser()
{
David C. Lonie's avatar
David C. Lonie committed
286
  SmartPyObject mplTextPathLib(PyImport_ImportModule("matplotlib.textpath"));
David C. Lonie's avatar
David C. Lonie committed
287
288
289
290
291
  if (this->CheckForError(mplTextPathLib.GetPointer()))
    {
    return false;
    }

David C. Lonie's avatar
David C. Lonie committed
292
293
  SmartPyObject textToPathClass(
        PyObject_GetAttrString(mplTextPathLib.GetPointer(), "TextToPath"));
David C. Lonie's avatar
David C. Lonie committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
  if (this->CheckForError(textToPathClass.GetPointer()))
    {
    return false;
    }

  this->PathParser = PyObject_CallFunction(textToPathClass.GetPointer(), NULL);
  if (this->CheckForError(this->PathParser))
    {
    Py_CLEAR(this->PathParser);
    return false;
    }

  return true;
}

//----------------------------------------------------------------------------
bool vtkMatplotlibMathTextUtilities::InitializeFontPropertiesClass()
{
David C. Lonie's avatar
David C. Lonie committed
312
313
  SmartPyObject mplFontManagerLib(
        PyImport_ImportModule("matplotlib.font_manager"));
David C. Lonie's avatar
David C. Lonie committed
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
  if (this->CheckForError(mplFontManagerLib.GetPointer()))
    {
    return false;
    }

  this->FontPropertiesClass = PyObject_GetAttrString(
        mplFontManagerLib.GetPointer(), "FontProperties");
  if (this->CheckForError(this->FontPropertiesClass))
    {
    Py_CLEAR(this->FontPropertiesClass);
    return false;
    }

  return true;
}

//----------------------------------------------------------------------------
bool vtkMatplotlibMathTextUtilities::CheckForError()
{
  PyObject *exception = PyErr_Occurred();
  if (exception)
    {
    vtkDebugMacro(<< "Python exception raised.");
337
338
339
340
    if (this->Debug)
      {
      PyErr_PrintEx(0);
      }
David C. Lonie's avatar
David C. Lonie committed
341
342
343
344
345
346
347
348
349
350
351
352
353
    return true;
    }
  return false;
}

//----------------------------------------------------------------------------
bool vtkMatplotlibMathTextUtilities::CheckForError(PyObject *object)
{
  // Print any exceptions
  bool result = this->CheckForError();

  if (object == NULL)
    {
354
    vtkDebugMacro(<< "Object is NULL!");
David C. Lonie's avatar
David C. Lonie committed
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
    return true;
    }
  return result;
}

//----------------------------------------------------------------------------
PyObject *
vtkMatplotlibMathTextUtilities::GetFontProperties(vtkTextProperty *tprop)
{
  if (!this->FontPropertiesClass)
    {
    if (!this->InitializeFontPropertiesClass())
      {
      vtkErrorMacro(<<"FontPropertiesClass is not initialized!");
      return NULL;
      }
    }

  char tpropFamily[16];
  char tpropStyle[16];
  char tpropVariant[16] = "normal";
  char tpropWeight[16];
  long tpropFontSize;

  switch (tprop->GetFontFamily())
    {
    default:
    case VTK_ARIAL:
      strcpy(tpropFamily, "sans-serif");
      break;
    case VTK_COURIER:
      strcpy(tpropFamily, "monospace");
      break;
    case VTK_TIMES:
      strcpy(tpropFamily, "serif");
      break;
    }

  if (tprop->GetItalic())
    {
    strcpy(tpropStyle, "italic");
    }
  else
    {
    strcpy(tpropStyle, "normal");
    }

  if (tprop->GetBold())
    {
    strcpy(tpropWeight, "bold");
    }
  else
    {
    strcpy(tpropWeight, "normal");
    }

  tpropFontSize = tprop->GetFontSize();

  return PyObject_CallFunction(this->FontPropertiesClass,
                               const_cast<char*>("sssssi"), tpropFamily,
                               tpropStyle, tpropVariant, tpropStyle,
                               tpropWeight, tpropFontSize);
}

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//----------------------------------------------------------------------------
void vtkMatplotlibMathTextUtilities::RotateCorners(double angleDeg,
                                                   double corners[4][2],
                                                   double bbox[4])
{
  double angleRad = vtkMath::RadiansFromDegrees(angleDeg);
  double c = cos(angleRad);
  double s = sin(angleRad);
  // Rotate corners
  for (int i = 0; i < 4; ++i)
    {
    int newpt[2];
    newpt[0] = c * corners[i][0] - s * corners[i][1];
    newpt[1] = s * corners[i][0] + c * corners[i][1];
    corners[i][0] = newpt[0];
    corners[i][1] = newpt[1];
    }
  // Find new bounds
  bbox[0] = VTK_INT_MAX;
  bbox[1] = VTK_INT_MIN;
  bbox[2] = VTK_INT_MAX;
  bbox[3] = VTK_INT_MIN;
  for (int i = 0; i < 4; ++i)
    {
    if (corners[i][0] < bbox[0])
      {
      bbox[0] = corners[i][0];
      }
    if (corners[i][0] > bbox[1])
      {
      bbox[1] = corners[i][0];
      }
    if (corners[i][1] < bbox[2])
      {
      bbox[2] = corners[i][1];
      }
    if (corners[i][1] > bbox[3])
      {
      bbox[3] = corners[i][1];
      }
    }
}

462
463
464
//----------------------------------------------------------------------------
// This is more or less ported from vtkFreeTypeTools.
bool vtkMatplotlibMathTextUtilities::PrepareImageData(vtkImageData *data,
465
                                                      int bbox[4])
466
{
467
468
  int width = bbox[1] - bbox[0] + 1;
  int height = bbox[3] - bbox[2] + 1;
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
  // If the current image data is too small to render the text,
  // or more than twice as big (too hungry), then resize
  int imgDims[3], newImgDims[3];
  data->GetDimensions(imgDims);

  if (data->GetScalarType() != VTK_UNSIGNED_CHAR ||
      data->GetNumberOfScalarComponents() != 4 ||
      imgDims[0] < width || imgDims[1] < height ||
      width * 2 < imgDims[0] || height * 2 < imgDims[1])
    {
    // Scale to the next highest power of 2 if required.
    if (this->ScaleToPowerOfTwo)
      {
      newImgDims[0] =
          1 << static_cast<int>(ceil(log(static_cast<double>(width+1)) /
                                     log(2.0)));
      newImgDims[1] =
          1 << static_cast<int>(ceil(log(static_cast<double>(height+1)) /
                                     log(2.0)));
      }
    else
      {
      newImgDims[0] = width;
      newImgDims[1] = height;
      }
    newImgDims[2] = 1;

    // Allocate the new image if needed
    if (data->GetScalarType() != VTK_UNSIGNED_CHAR ||
        data->GetNumberOfScalarComponents() != 4 ||
        newImgDims[0] != imgDims[0] ||
        newImgDims[1] != imgDims[1] ||
        newImgDims[2] != imgDims[2])
      {
503
504
505
      data->SetExtent(bbox[0], bbox[0] + newImgDims[0] - 1,
                      bbox[2], bbox[2] + newImgDims[1] - 1,
                      0, 0);
506
507
508
509
510
511
512
      data->AllocateScalars(VTK_UNSIGNED_CHAR, 4);
      }
    }

  // Clear the image
  memset(data->GetScalarPointer(), 0,
         (data->GetNumberOfPoints() * data->GetNumberOfScalarComponents()));
David C. Lonie's avatar
David C. Lonie committed
513
514

  return true;
515
516
}

517
518
519
520
521
522
523
524
525
526
527
528
529
//----------------------------------------------------------------------------
bool vtkMatplotlibMathTextUtilities::GetBoundingBox(
    vtkTextProperty *tprop, const char *str, unsigned int dpi, int bbox[4])
{
  if (!this->MaskParser)
    {
    if (!this->InitializeMaskParser())
      {
      vtkErrorMacro(<<"MaskParser is not initialized!");
      return false;
      }
    }

530
  vtkDebugMacro(<<"Calculating bbox for '" << str << "'");
531
532
533
534
535
536

  long int rows = 0;
  long int cols = 0;
  // matplotlib.mathtext seems to mishandle the dpi, this conversion makes the
  // text size match the images produced by vtkFreeTypeUtilities, as well as the
  // paths generated by StringToPath
David C. Lonie's avatar
David C. Lonie committed
537
  long int fontSize = tprop->GetFontSize() * 72.0 / static_cast<float>(dpi);
538

David C. Lonie's avatar
David C. Lonie committed
539
540
541
542
543
  SmartPyObject resultTuple(PyObject_CallMethod(this->MaskParser,
                                                const_cast<char*>("to_mask"),
                                                const_cast<char*>("sii"),
                                                const_cast<char*>(str),
                                                fontSize, dpi));
544
545
546
547
548
549
550
551
552
553
554
555
  if (this->CheckForError(resultTuple.GetPointer()))
    {
    return false;
    }

  // numpyArray is a borrowed reference, no smart wrapper needed:
  PyObject *numpyArray = PyTuple_GetItem(resultTuple.GetPointer(), 0);
  if (this->CheckForError(numpyArray))
    {
    return false;
    }

David C. Lonie's avatar
David C. Lonie committed
556
557
  SmartPyObject dimTuple(PyObject_GetAttrString(numpyArray,
                                                const_cast<char*>("shape")));
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
  if (this->CheckForError(dimTuple.GetPointer()))
    {
    return false;
    }

  PyArg_ParseTuple(dimTuple.GetPointer(), "ii", &rows, &cols);
  if (this->CheckForError())
    {
    return false;
    }


  // Determine the dimensions of the rotated image
  double angleDeg = tprop->GetOrientation();
  // Corners of original image
  double corners[4][2] = { {0, 0},
574
575
576
                           {static_cast<double>(cols), 0},
                           {0, static_cast<double>(rows)},
                           {static_cast<double>(cols), static_cast<double>(rows)} };
577
578
579

  double bboxd[4];
  this->RotateCorners(angleDeg, corners, bboxd);
580
581
582
583
  bbox[0] = vtkMath::Ceil(bboxd[0]);
  bbox[1] = vtkMath::Ceil(bboxd[1]);
  bbox[2] = vtkMath::Ceil(bboxd[2]);
  bbox[3] = vtkMath::Ceil(bboxd[3]);
584
585
586
587

  return true;
}

David C. Lonie's avatar
David C. Lonie committed
588
589
590
591
//----------------------------------------------------------------------------
bool vtkMatplotlibMathTextUtilities::RenderString(const char *str,
                                                  vtkImageData *image,
                                                  vtkTextProperty *tprop,
592
593
                                                  unsigned int dpi,
                                                  int textDims[2])
David C. Lonie's avatar
David C. Lonie committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
{
  if (!this->MaskParser)
    {
    if (!this->InitializeMaskParser())
      {
      vtkErrorMacro(<<"MaskParser is not initialized!");
      return false;
      }
    }

  vtkDebugMacro(<<"Converting '" << str << "' into MathText image...");

  long int rows = 0;
  long int cols = 0;
  long int ind = 0;
Dave DeMarle's avatar
Dave DeMarle committed
609
  //long int numPixels = 0;
David C. Lonie's avatar
David C. Lonie committed
610
611
612
  // matplotlib.mathtext seems to mishandle the dpi, this conversion makes the
  // text size match the images produced by vtkFreeTypeUtilities, as well as the
  // paths generated by StringToPath
David C. Lonie's avatar
David C. Lonie committed
613
  long int fontSize = tprop->GetFontSize() * 72.0 / static_cast<float>(dpi);
David C. Lonie's avatar
David C. Lonie committed
614
615
616
617
618
619
  double *dcolor = tprop->GetColor();
  unsigned char r = static_cast<unsigned char>(dcolor[0] * 255);
  unsigned char g = static_cast<unsigned char>(dcolor[1] * 255);
  unsigned char b = static_cast<unsigned char>(dcolor[2] * 255);
  double alpha = tprop->GetOpacity();

David C. Lonie's avatar
David C. Lonie committed
620
621
622
623
624
  SmartPyObject resultTuple(PyObject_CallMethod(this->MaskParser,
                                                const_cast<char*>("to_mask"),
                                                const_cast<char*>("sii"),
                                                const_cast<char*>(str),
                                                fontSize, dpi));
David C. Lonie's avatar
David C. Lonie committed
625
626
627
628
629
630
631
632
633
634
635
636
  if (this->CheckForError(resultTuple.GetPointer()))
    {
    return false;
    }

  // numpyArray is a borrowed reference, no smart wrapper needed:
  PyObject *numpyArray = PyTuple_GetItem(resultTuple.GetPointer(), 0);
  if (this->CheckForError(numpyArray))
    {
    return false;
    }

David C. Lonie's avatar
David C. Lonie committed
637
638
639
  SmartPyObject flatArray(PyObject_CallMethod(numpyArray,
                                              const_cast<char*>("flatten"),
                                              const_cast<char*>("")));
David C. Lonie's avatar
David C. Lonie committed
640
641
642
643
644
  if (this->CheckForError(flatArray.GetPointer()))
    {
    return false;
    }

David C. Lonie's avatar
David C. Lonie committed
645
646
647
  SmartPyObject list(PyObject_CallMethod(flatArray.GetPointer(),
                                         const_cast<char*>("tolist"),
                                         const_cast<char*>("")));
David C. Lonie's avatar
David C. Lonie committed
648
649
650
651
652
  if (this->CheckForError(list.GetPointer()))
    {
    return false;
    }

David C. Lonie's avatar
David C. Lonie committed
653
654
  SmartPyObject dimTuple(PyObject_GetAttrString(numpyArray,
                                                const_cast<char*>("shape")));
David C. Lonie's avatar
David C. Lonie committed
655
656
657
658
659
660
661
662
663
664
665
  if (this->CheckForError(dimTuple.GetPointer()))
    {
    return false;
    }

  PyArg_ParseTuple(dimTuple.GetPointer(), "ii", &rows, &cols);
  if (this->CheckForError())
    {
    return false;
    }

Dave DeMarle's avatar
Dave DeMarle committed
666
  //numPixels = PyObject_Length(list.GetPointer());
David C. Lonie's avatar
David C. Lonie committed
667
668
669
670
671
  if (this->CheckForError())
    {
    return false;
    }

672
673
674
675
676
677
  if (textDims)
    {
    textDims[0] = cols;
    textDims[1] = rows;
    }

678
679
  int bbox[4] = {0, static_cast<int>(cols - 1),
                 0, static_cast<int>(rows - 1)};
680
  this->PrepareImageData(image, bbox);
681

David C. Lonie's avatar
David C. Lonie committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
  for (long int row = rows-1; row >= 0; --row)
    {
    for (long int col = 0; col < cols; ++col)
      {
      // item is borrowed, no need for a smart wrapper
      PyObject *item = PyList_GetItem(list.GetPointer(), ind++);
      if (this->CheckForError(item))
        {
        return false;
        }
      unsigned char val =
          static_cast<unsigned char>(alpha * PyInt_AsLong(item));
      if (this->CheckForError())
        {
        return false;
        }
      unsigned char *ptr =
          static_cast<unsigned char*>(image->GetScalarPointer(col, row, 0));
      ptr[0] = r;
      ptr[1] = g;
      ptr[2] = b;
      ptr[3] = val;
      }
    }

707
708
709
710
711
712
713
714
715
  // Determine the dimensions of the rotated image
  double angleDeg = tprop->GetOrientation();
  // Save some time if no rotation needed
  if (fabs(angleDeg) < 0.01)
    {
    return true;
    }

  // Corners of original image
716
717
718
719
720
721
722
723
724
  double corners[4][2] = { {static_cast<double>(bbox[0]),
                            static_cast<double>(bbox[2])},
                           {static_cast<double>(bbox[1]),
                            static_cast<double>(bbox[2])},
                           {static_cast<double>(bbox[0]),
                            static_cast<double>(bbox[3])},
                           {static_cast<double>(bbox[1]),
                            static_cast<double>(bbox[3])} };
  double bbox2[4];
725
726

  // Rotate the corners of the image and determine the bounding box
727
  this->RotateCorners(angleDeg, corners, bbox2);
728

729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
  // Also rotate the text dimensions.
  if (textDims)
    {
    double text_bbox[4];
    corners[0][0] = static_cast<double>(0);
    corners[0][1] = static_cast<double>(0);
    corners[1][0] = static_cast<double>(0);
    corners[1][1] = static_cast<double>(textDims[1]);
    corners[2][0] = static_cast<double>(textDims[0]);
    corners[2][1] = static_cast<double>(textDims[1]);
    corners[3][0] = static_cast<double>(textDims[0]) ;
    corners[3][1] = static_cast<double>(0);
    this->RotateCorners(angleDeg, corners, text_bbox);
    textDims[0] = std::ceil(text_bbox[1] - text_bbox[0]);
    textDims[1] = std::ceil(text_bbox[3] - text_bbox[2]);
    }

746
747
748
749
750
  bbox[0] = static_cast<int>(bbox2[0]);
  bbox[1] = static_cast<int>(bbox2[1]);
  bbox[2] = static_cast<int>(bbox2[2]);
  bbox[3] = static_cast<int>(bbox2[3]);

751
752
753
754
755
  // Rotate the temporary image into the returned image:
  vtkNew<vtkTransform> rotation;
  rotation->RotateWXYZ(-angleDeg, 0, 0, 1);
  // Dummy image with the output dimensions
  vtkNew<vtkImageData> dummyImage;
756
  this->PrepareImageData(dummyImage.GetPointer(), bbox);
757
758
759
760
761
762
763
764
  vtkNew<vtkImageReslice> rotator;
  rotator->SetInputData(image);
  rotator->SetInformationInput(dummyImage.GetPointer());
  rotator->SetResliceTransform(rotation.GetPointer());
  rotator->SetInterpolationModeToLinear();
  rotator->Update();
  image->ShallowCopy(rotator->GetOutput());

David C. Lonie's avatar
David C. Lonie committed
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
  return true;
}

//----------------------------------------------------------------------------
bool vtkMatplotlibMathTextUtilities::StringToPath(const char *str,
                                                  vtkPath *path,
                                                  vtkTextProperty *tprop)
{
  if (!this->PathParser)
    {
    if (!this->InitializePathParser())
      {
      vtkErrorMacro(<<"PathParser is not initialized!");
      return false;
      }
    }

  vtkDebugMacro(<<"Converting '" << str << "' into a vtkPath...");

  // Matplotlib path codes:
  const int pathStop = 0;
  const int pathMoveTo = 1;
  const int pathLineTo = 2;
  const int pathCurve3 = 3;
  const int pathCurve4 = 4;
  const int pathClosePoly = 0x4f;

  // List sizes:
  Py_ssize_t numCodes;
  Py_ssize_t numVerts;

  // Temp vars:
797
  float origin[2] = {0.0, 0.0};
David C. Lonie's avatar
David C. Lonie committed
798
799
800
  float vert[2];
  float delta[2] = {0.0, 0.0};
  int code;
801
  bool hasOrigin = false;
David C. Lonie's avatar
David C. Lonie committed
802
803
804
805
806
807
808
809
810
811

  // Bounding box for all control points, used for justification
  float cbox[4] = {VTK_FLOAT_MAX, VTK_FLOAT_MAX, VTK_FLOAT_MIN, VTK_FLOAT_MIN};

  // The path is always generated at a font size of 100. Use this factor to
  // recover the font.
  const float fontScale = ((tprop->GetFontSize()) / 100.);
  path->Reset();

  // Create the font property
David C. Lonie's avatar
David C. Lonie committed
812
  SmartPyObject pyFontProp(this->GetFontProperties(tprop));
David C. Lonie's avatar
David C. Lonie committed
813
814
815
816
817
  if (this->CheckForError(pyFontProp.GetPointer()))
    {
    return false;
    }

David C. Lonie's avatar
David C. Lonie committed
818
  SmartPyObject pyResultTuple(
David C. Lonie's avatar
David C. Lonie committed
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
        PyObject_CallMethod(this->PathParser,
                            const_cast<char*>("get_text_path"),
                            const_cast<char*>("Osi"),
                            pyFontProp.GetPointer(),// prop
                            const_cast<char*>(str), // texstring
                            1,                      // boolean, ismath
                            0));                    // boolean, usetex
  if (this->CheckForError(pyResultTuple.GetPointer()))
    {
    return false;
    }

  // pyVerts and pyCodes are borrowed references -- no need for smart wrappers
  PyObject *pyVerts = PyTuple_GetItem(pyResultTuple.GetPointer(), 0);
  PyObject *pyCodes = PyTuple_GetItem(pyResultTuple.GetPointer(), 1);
  if (this->CheckForError(pyVerts)  ||
      this->CheckForError(pyCodes))
    {
    return false;
    }

  // Both verts and codes are lists?
  if (!PySequence_Check(pyVerts) || !PySequence_Check(pyCodes))
    {
    return false;
    }

  numVerts = PySequence_Size(pyVerts);
  numCodes = PySequence_Size(pyCodes);
  if (numVerts != numCodes)
    {
    return false;
    }

  path->Allocate(numVerts);

  for (Py_ssize_t i = 0; i < numVerts; ++i)
    {
David C. Lonie's avatar
David C. Lonie committed
857
858
    SmartPyObject pyVert(PySequence_GetItem(pyVerts, i));
    SmartPyObject pyCode(PySequence_GetItem(pyCodes, i));
David C. Lonie's avatar
David C. Lonie committed
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
    if (this->CheckForError(pyVert.GetPointer()) ||
        this->CheckForError(pyCode.GetPointer()))
      {
      return false;
      }

    // pyVert is sometimes a numpy array, sometimes it's a tuple.
    // Initialize the following objects in the following conditional, then
    // convert to smart pointers afterwards.
    PyObject *pyVertXObj = NULL;
    PyObject *pyVertYObj = NULL;
    if (pyVert->ob_type == &PyTuple_Type)
      {
      pyVertXObj = PyTuple_GetItem(pyVert.GetPointer(), 0);
      pyVertYObj = PyTuple_GetItem(pyVert.GetPointer(), 1);
      // Increase reference count -- the other branch returns a new reference,
      // this keeps cleanup consistent
      if (pyVertXObj)
        {
        Py_INCREF(pyVertXObj);
        }
      if (pyVertYObj)
        {
        Py_INCREF(pyVertYObj);
        }
      }
    else // Assume numpy array. Convert to list and extract elements.
      {
David C. Lonie's avatar
David C. Lonie committed
887
888
889
      SmartPyObject pyVertList(PyObject_CallMethod(pyVert.GetPointer(),
                                                   const_cast<char*>("tolist"),
                                                   NULL));
David C. Lonie's avatar
David C. Lonie committed
890
891
892
893
894
895
896
897
898
899
      if (this->CheckForError(pyVertList.GetPointer()) ||
          PySequence_Size(pyVertList.GetPointer()) < 2)
        {
        return false;
        }

      pyVertXObj = PySequence_GetItem(pyVertList.GetPointer(), 0);
      pyVertYObj = PySequence_GetItem(pyVertList.GetPointer(), 1);
      }

David C. Lonie's avatar
David C. Lonie committed
900
901
    SmartPyObject pyVertX(pyVertXObj);
    SmartPyObject pyVertY(pyVertYObj);
David C. Lonie's avatar
David C. Lonie committed
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
    if (this->CheckForError(pyVertX.GetPointer()) ||
        this->CheckForError(pyVertY.GetPointer()))
      {
      return false;
      }

    vert[0] = PyFloat_AsDouble(pyVertX.GetPointer()) * fontScale;
    vert[1] = PyFloat_AsDouble(pyVertY.GetPointer()) * fontScale;
    if (this->CheckForError())
      {
      return false;
      }

    if (vert[0] < cbox[0])
      {
      cbox[0] = vert[0];
      }
    if (vert[1] < cbox[1])
      {
      cbox[1] = vert[1];
      }
    if (vert[0] > cbox[2])
      {
      cbox[2] = vert[0];
      }
    if (vert[1] > cbox[3])
      {
      cbox[3] = vert[1];
      }

    code = PyInt_AsLong(pyCode.GetPointer());
    if (this->CheckForError())
      {
      return false;
      }

    switch (code)
      {
      case pathStop:
        hasOrigin = false;
        break;
      case pathMoveTo:
        path->InsertNextPoint(vert[0], vert[1], 0, vtkPath::MOVE_TO);
        origin[0] = vert[0];
        origin[1] = vert[1];
        hasOrigin = true;
        break;
      case pathLineTo:
        path->InsertNextPoint(vert[0], vert[1], 0, vtkPath::LINE_TO);
        break;
      case pathCurve3:
        path->InsertNextPoint(vert[0], vert[1], 0, vtkPath::CONIC_CURVE);
        break;
      case pathCurve4:
        path->InsertNextPoint(vert[0], vert[1], 0, vtkPath::CUBIC_CURVE);
        break;
      case pathClosePoly:
        if (hasOrigin)
          path->InsertNextPoint(origin[0], origin[1], 0, vtkPath::LINE_TO);
        hasOrigin = false;
        break;
      default:
        vtkWarningMacro(<<"Unrecognized code: " << code);
        break;
      }
    }

  // Apply justification:
  switch (tprop->GetJustification())
    {
    default:
    case VTK_TEXT_LEFT:
      delta[0] = -cbox[0];
      break;
    case VTK_TEXT_CENTERED:
      delta[0] = -(cbox[2] - cbox[0]) * 0.5;
      break;
    case VTK_TEXT_RIGHT:
      delta[0] = -cbox[2];
      break;
    }
  switch (tprop->GetVerticalJustification())
    {
    default:
    case VTK_TEXT_BOTTOM:
      delta[1] = -cbox[1];
      break;
    case VTK_TEXT_CENTERED:
      delta[1] = -(cbox[3] - cbox[1]) * 0.5;
      break;
    case VTK_TEXT_TOP:
      delta[1] = -cbox[3];
    }

  vtkPoints *points = path->GetPoints();
  for (vtkIdType i = 0; i < points->GetNumberOfPoints(); ++i)
    {
    double *point = points->GetPoint(i);
    point[0] += delta[0];
    point[1] += delta[1];
    points->SetPoint(i, point);
    }


  return true;
}

//----------------------------------------------------------------------------
void vtkMatplotlibMathTextUtilities::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "MaskParser: " << this->MaskParser << endl;
  os << indent << "PathParser: " << this->PathParser << endl;
  os << indent << "FontPropertiesClass: " << this->FontPropertiesClass << endl;
}