9d9a537acadf1c43f22622a6c42179e0705f02e4
[ctsim.git] / libctsim / phantom.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 ** 
4 **     Name:                   phm.cpp
5 **     Purpose:                Routines for phantom objects
6 **     Progammer:              Kevin Rosenberg
7 **     Date Started:           Aug 1984
8 **
9 **  This is part of the CTSim program
10 **  Copyright (c) 1983-2001 Kevin Rosenberg
11 **
12 **  $Id: phantom.cpp,v 1.33 2003/03/15 14:52:36 kevin Exp $
13 **
14 **  This program is free software; you can redistribute it and/or modify
15 **  it under the terms of the GNU General Public License (version 2) as
16 **  published by the Free Software Foundation.
17 **
18 **  This program is distributed in the hope that it will be useful,
19 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
20 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 **  GNU General Public License for more details.
22 **
23 **  You should have received a copy of the GNU General Public License
24 **  along with this program; if not, write to the Free Software
25 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 ******************************************************************************/
27
28 #include "ct.h"
29
30 const int PhantomElement::POINTS_PER_CIRCLE = 360;
31 const double PhantomElement::SCALE_PELEM_EXTENT=0.000;  // increase pelem limits by 0.5% 
32 //const double PhantomElement::SCALE_PELEM_EXTENT=0.005;  // increase pelem limits by 0.5% 
33
34 const int Phantom::PHM_INVALID = -1;
35 const int Phantom::PHM_HERMAN = 0;
36 const int Phantom::PHM_SHEPP_LOGAN = 1;
37 const int Phantom::PHM_UNITPULSE = 2;
38
39 const char* Phantom::s_aszPhantomName[] = 
40 {
41   {"herman"},
42   {"shepp-logan"},
43   {"unit-pulse"},
44 };
45
46 const char* Phantom::s_aszPhantomTitle[] = 
47 {
48   {"Herman Head"},
49   {"Shepp-Logan"},
50   {"Unit Pulse"},
51 };
52
53 const int Phantom::s_iPhantomCount = sizeof(s_aszPhantomName) / sizeof(const char*);
54
55
56 // CLASS IDENTIFICATION
57 //   Phantom
58 //
59
60 Phantom::Phantom ()
61 {
62   init ();
63 }
64
65
66 Phantom::Phantom (const char* const phmName)
67 {
68   init ();
69   createFromPhantom (phmName);
70 }
71
72 void 
73 Phantom::init ()
74 {
75   m_nPElem = 0;
76   m_xmin = 1E30;
77   m_xmax = -1E30;
78   m_ymin = 1E30;
79   m_ymax = -1E30;
80   m_composition = P_PELEMS;
81   m_fail = false;
82   m_id = PHM_INVALID;
83 }
84
85 Phantom::~Phantom ()
86 {
87   for (PElemIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
88     delete *i;
89   }
90 }
91
92
93 const char*
94 Phantom::convertPhantomIDToName (int phmID)
95 {
96   static const char *name = "";
97   
98   if (phmID >= 0 && phmID < s_iPhantomCount)
99     return (s_aszPhantomName[phmID]);
100   
101   return (name);
102 }
103
104 const char*
105 Phantom::convertPhantomIDToTitle (int phmID)
106 {
107   static const char *title = "";
108   
109   if (phmID >= 0 && phmID < s_iPhantomCount)
110     return (s_aszPhantomName[phmID]);
111   
112   return (title);
113 }
114
115 int
116 Phantom::convertNameToPhantomID (const char* const phmName) 
117 {
118   int id = PHM_INVALID;
119   
120   for (int i = 0; i < s_iPhantomCount; i++)
121     if (strcasecmp (phmName, s_aszPhantomName[i]) == 0) {
122       id = i;
123       break;
124     }
125     
126     return (id);
127 }
128
129
130 bool
131 Phantom::createFromPhantom (const char* const phmName)
132 {
133   int phmid = convertNameToPhantomID (phmName);
134   if (phmid == PHM_INVALID) {
135     m_fail = true;
136     m_failMessage = "Invalid phantom name ";
137     m_failMessage += phmName;
138     return false;
139   }
140   
141   m_name = phmName;
142   createFromPhantom (phmid);
143   return true;
144 }
145
146 bool
147 Phantom::createFromPhantom (const int phmid)
148 {
149   switch (phmid) 
150   {
151   case PHM_HERMAN:
152     addStdHerman();
153     break;
154   case PHM_SHEPP_LOGAN:
155     addStdSheppLogan();
156     break;
157   case PHM_UNITPULSE:
158     m_composition = P_UNIT_PULSE;
159     addPElem ("rectangle", 0., 0., 100., 100., 0., 0.);     // outline 
160     addPElem ("ellipse", 0., 0., 1., 1., 0., 1.);             // pulse 
161     break;
162   default:
163     m_fail = true;
164     m_failMessage = "Illegal phantom id ";
165     m_failMessage += phmid;
166     return false;
167   }
168   
169   m_id = phmid;
170   
171   return true;
172 }
173
174
175 /* METHOD IDENTIFICATION
176 *   createFromFile          Add PhantomElements from file
177 *
178 * SYNOPSIS
179 *   createFromFile (filename)
180 *
181 * RETURNS
182 *   true if pelem were added
183 *   false if an pelem not added
184 */
185
186 bool
187 Phantom::createFromFile (const char* const fname)
188 {
189   bool bGoodFile = true;
190   FILE *fp;
191   
192   if ((fp = fopen (fname, "r")) == NULL)
193     return (false);
194   
195   m_name = fname;
196   
197   while (1) {
198     double cx, cy, u, v, rot, dens;
199     char pelemtype[80];
200     
201     int status = fscanf (fp, "%79s %lf %lf %lf %lf %lf %lf", pelemtype, &cx, &cy, &u, &v, &rot, &dens);
202     
203     if (status == static_cast<int>(EOF)) 
204       break;
205     else if (status != 7) {
206       sys_error (ERR_WARNING, "Insufficient fields reading phantom file %s [Phantom::createFromFile]", fname);
207       bGoodFile = false;
208     }
209     addPElem (pelemtype, cx, cy, u, v, rot, dens);
210   }
211   
212   fclose (fp);
213   
214   return (bGoodFile);
215 }
216
217 bool
218 Phantom::fileWrite (const char* const fname)
219 {
220   fstream file (fname, std::ios::out);
221   
222   if (! file.fail())
223     printDefinitions (file);
224   return ! file.fail();
225 }
226
227 /* NAME
228 *   addPElem            Add pelem
229 *
230 * SYNOPSIS
231 *   addPElem (type, cx, cy, u, v, rot, atten)
232 *   char *type          type of pelem (box, ellipse, etc)
233 *   double cx, cy       pelem center
234 *   double u,v          pelem size
235 *   double rot          rotation angle of pelem (in degrees)
236 *   double atten        x-ray attenuation cooefficient
237 */
238
239 void 
240 Phantom::addPElem (const char *type, const double cx, const double cy, const double u, const double v, const double rot, const double atten)
241 {
242   PhmElemType pe_type = PhantomElement::convertNameToType (type);
243   if (pe_type == PELEM_INVALID) {
244     sys_error (ERR_WARNING, "Unknown PhantomElement type %s [PhantomElement::PhantomElement]", type);
245     return;
246   }
247   
248   PhantomElement *pelem = new PhantomElement (type, cx, cy, u, v, rot, atten);
249   m_listPElem.push_front (pelem);
250   
251   // update phantom limits
252   if (m_xmin > pelem->xmin())    m_xmin = pelem->xmin();
253   if (m_xmax < pelem->xmax())    m_xmax = pelem->xmax();
254   if (m_ymin > pelem->ymin())    m_ymin = pelem->ymin();
255   if (m_ymax < pelem->ymax())    m_ymax = pelem->ymax();
256   
257   m_nPElem++;
258 }
259
260
261 /*----------------------------------------------------------------------*/
262 /*                      Input-Output Routines                           */
263 /*----------------------------------------------------------------------*/
264
265
266 /* NAME
267 *   print                               Print vertices of Phantom pelems
268 *
269 * SYNOPSIS
270 *   print (phm)
271 */
272
273 void 
274 Phantom::print (std::ostream& os) const
275 {
276   os << "Number of PElements: " << m_nPElem << "\n";
277   os << "Limits: xmin=" << m_xmin << ", ymin=" << m_ymin << ", xmax=" << m_xmax << ", ymax=" << m_ymax << "\n";
278   
279   for (PElemConstIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
280     const PhantomElement& rPE = **i;
281     os << "PhantomElement: nPoints=" << rPE.nOutlinePoints();
282     os << ", atten=" << rPE.atten() << " rot=" << convertRadiansToDegrees (rPE.rot()) << "\n";
283     os << "xmin=" << rPE.xmin() << ", ymin=" << rPE.ymin() << ", xmax=" << rPE.xmax() << ", ymax=" << rPE.ymax() << "\n";
284     
285     if (false)
286       for (int i = 0; i < rPE.nOutlinePoints(); i++)
287         os << rPE.xOutline()[i] << "," << rPE.yOutline()[i] << "\n";
288   }
289 }
290 void 
291 Phantom::print (std::ostringstream& os) const
292 {
293   os << "Number of PElements: " << m_nPElem << "\n";
294   os << "Limits: xmin=" << m_xmin << ", ymin=" << m_ymin << ", xmax=" << m_xmax << ", ymax=" << m_ymax << "\n";
295   
296   for (PElemConstIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
297     const PhantomElement& rPE = **i;
298     os << "PhantomElement: nPoints=" << rPE.nOutlinePoints();
299     os << ", atten=" << rPE.atten() << " rot=" << convertRadiansToDegrees (rPE.rot()) << "\n";
300     os << "xmin=" << rPE.xmin() << ", ymin=" << rPE.ymin() << ", xmax=" << rPE.xmax() << ", ymax=" << rPE.ymax() << "\n";
301     
302     if (false)
303       for (int i = 0; i < rPE.nOutlinePoints(); i++)
304         os << rPE.xOutline()[i] << "," << rPE.yOutline()[i] << "\n";
305   }
306 }
307
308 void
309 Phantom::printDefinitions (std::ostream& os) const
310 {
311   for (PElemConstIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
312     const PhantomElement& rPE = **i;
313     rPE.printDefinition (os);
314   }
315 }
316
317 void
318 Phantom::printDefinitions (std::ostringstream& os) const
319 {
320   for (PElemConstIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
321     const PhantomElement& rPE = **i;
322     rPE.printDefinition (os);
323   }
324 }
325
326
327 /* NAME
328 *   show                Show vector outline of Phantom to user
329 *
330 * SYNOPSIS
331 *   show (pic)
332 */
333
334 #ifdef HAVE_SGP
335 void 
336 Phantom::show () const
337 {
338   SGPDriver driverSGP ("Phantom Show");
339   SGP sgp (driverSGP);
340   
341   show (sgp);
342   
343   std::cout << "Press return to continue";
344   cio_kb_getc();
345 }
346
347 void 
348 Phantom::show (SGP& sgp) const
349 {
350   double wsize = m_xmax - m_xmin;
351   if ((m_ymax - m_ymin) > wsize) 
352     wsize = m_ymax - m_ymin;
353   wsize *= 1.01;
354   double halfWindow = wsize / 2;
355   
356   double xcent = m_xmin + (m_xmax - m_xmin) / 2;
357   double ycent = m_ymin + (m_ymax - m_ymin) / 2;
358   
359   sgp.setWindow (xcent - halfWindow, ycent - halfWindow, xcent + halfWindow, ycent + halfWindow);
360   
361   draw (sgp);
362 }
363 #endif
364
365
366 /* NAME
367 *   draw                Draw vector outline of Phantom
368 *
369 * SYNOPSIS
370 *   draw ()
371 */
372
373 #ifdef HAVE_SGP
374 void 
375 Phantom::draw (SGP& sgp) const
376 {
377   for (PElemIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++)
378     sgp.polylineAbs ((*i)->xOutline(), (*i)->yOutline(), (*i)->nOutlinePoints());
379 }
380 #endif
381
382
383 /* NAME
384 *   addStdSheppLogan    Make head phantom of Shepp-Logan
385 *
386 * REFERENCES
387 *   S. W. Rowland, "Computer Implementation of Image Reconstruction
388 *       Formulas", in "Image Reconstruction from Projections: Implementation
389 *       and Applications", edited by G. T. Herman, 1978.
390 */
391
392 void 
393 Phantom::addStdSheppLogan ()
394 {
395   addPElem ("ellipse",  0.0000,  0.0000, 0.6900,  0.9200,   0.0,  1.00);
396   addPElem ("ellipse",  0.0000, -0.0184, 0.6624,  0.8740,   0.0, -0.98);
397   addPElem ("ellipse",  0.2200,  0.0000, 0.1100,  0.3100, -18.0, -0.02);
398   addPElem ("ellipse", -0.2200,  0.0000, 0.1600,  0.4100,  18.0, -0.02);
399   addPElem ("ellipse",  0.0000,  0.3500, 0.2100,  0.2500,   0.0,  0.01);
400   addPElem ("ellipse",  0.0000,  0.1000, 0.0460,  0.0460,   0.0,  0.01);
401   addPElem ("ellipse",  0.0000, -0.1000, 0.0460,  0.0460,   0.0,  0.01);
402   addPElem ("ellipse", -0.0800, -0.6050, 0.0460,  0.0230,   0.0,  0.01);
403   addPElem ("ellipse",  0.0000, -0.6050, 0.0230,  0.0230,   0.0,  0.01);
404   addPElem ("ellipse",  0.0600, -0.6050, 0.0230,  0.0230,   0.0,  0.01);
405   addPElem ("ellipse",  0.5538, -0.3858, 0.0330,  0.2060, -18.0,  0.03);
406 }
407
408
409 /* NAME
410 *   addStdHerman                        Standard head phantom of G. T. Herman
411 *
412 * REFERENCES
413 *   G. T. Herman, "Image Reconstructions from Projections:  The Fundementals
414 *       of Computed Tomography", 1979.
415 */
416
417 void 
418 Phantom::addStdHerman ()
419 {
420   addPElem ("ellipse",  0.000,  1.50,  0.375, 0.3000,  90.00, -0.003);
421   addPElem ("ellipse",  0.675, -0.75,  0.225, 0.1500, 140.00,  0.010);
422   addPElem ("ellipse",  0.750,  1.50,  0.375, 0.2250,  50.00,  0.003);
423   addPElem ("segment",  1.375, -7.50,  1.100, 0.6250,  19.20, -0.204);
424   addPElem ("segment",  1.375, -7.50,  1.100, 4.3200,  19.21,  0.204);
425   addPElem ("segment",  0.000, -2.25,  1.125, 0.3750,   0.00, -0.003);
426   addPElem ("segment",  0.000, -2.25,  1.125, 3.0000,   0.00,  0.003);
427   addPElem ("segment", -1.000,  3.75,  1.000, 0.5000, 135.00, -0.003);
428   addPElem ("segment", -1.000,  3.75,  1.000, 3.0000, 135.00,  0.003);
429   addPElem ("segment",  1.000,  3.75,  1.000, 0.5000, 225.00, -0.003);
430   addPElem ("segment",  1.000,  3.75,  1.000, 3.0000, 225.00,  0.003);
431   addPElem ("triangle", 5.025,  3.75,  1.125, 0.5000, 110.75,  0.206);
432   addPElem ("triangle",-5.025,  3.75,  1.125, 0.9000,-110.75,  0.206);
433   addPElem ("ellipse",  0.000,  0.00,  8.625, 6.4687,  90.00,  0.416);
434   addPElem ("ellipse",  0.000,  0.00,  7.875, 5.7187,  90.00, -0.206);
435 }
436
437
438
439 /* NAME
440 *    convertToImagefile         Make image array from Phantom
441 *
442 * SYNOPSIS
443 *    pic_to_imagefile (pic, im, nsample)
444 *    Phantom& pic               Phantom definitions
445 *    ImageFile  *im             Computed pixel array
446 *    int nsample                Number of samples along each axis for each pixel
447 *                               (total samples per pixel = nsample * nsample)
448 */
449
450 void
451 Phantom::convertToImagefile (ImageFile& im, double dViewRatio, const int in_nsample, const int trace) const
452 {
453   convertToImagefile (im, dViewRatio, in_nsample, trace, 0, im.nx(), true);
454 }
455
456 void 
457 Phantom::convertToImagefile (ImageFile& im, const double dViewRatio, const int in_nsample, const int trace, 
458                              const int colStart, const int colCount, bool bStoreAtColumnPos) const
459 {
460   int iStorageOffset = (bStoreAtColumnPos ? colStart : 0);
461   convertToImagefile (im, im.nx(), dViewRatio, in_nsample, trace, colStart, colCount, iStorageOffset);
462 }
463
464 void 
465 Phantom::convertToImagefile (ImageFile& im, const int iTotalRasterCols, const double dViewRatio, 
466             const int in_nsample, const int trace, const int colStart, const int colCount, int iStorageOffset) const
467 {
468   const int nx = im.nx();
469   const int ny = im.ny();
470   if (nx < 2 || ny < 2)
471     return;
472   
473   int nsample = in_nsample;
474   if (nsample < 1)  
475     nsample = 1;
476   
477   double dx = m_xmax - m_xmin;
478   double dy = m_ymax - m_ymin;
479   double xcent = m_xmin + dx / 2;
480   double ycent = m_ymin + dy / 2;
481   double dHalflen = dViewRatio * (getDiameterBoundaryCircle() / SQRT2 / 2);
482   
483   double xmin = xcent - dHalflen;
484   double xmax = xcent + dHalflen;
485   double ymin = ycent - dHalflen;
486   double ymax = ycent + dHalflen;
487   
488   // Each pixel holds the average of the intensity of the cell with (ix,iy) at the center of the pixel
489   // Set major increments so that the last cell v[nx-1][ny-1] will start at xmax - xinc, ymax - yinc).
490   // Set minor increments so that sample points are centered in cell
491   
492   double xinc = (xmax - xmin) / (iTotalRasterCols);
493   double yinc = (ymax - ymin) / ny;
494   
495   double kxinc = xinc / nsample;                /* interval between samples */
496   double kyinc = yinc / nsample;
497   double kxofs = kxinc / 2;             /* offset of 1st point */
498   double kyofs = kyinc / 2;
499   
500   im.setAxisExtent (xmin, xmax, ymin, ymax);
501   im.setAxisIncrement (xinc, yinc);
502   
503   ImageFileArray v = im.getArray();
504   
505   for (int ix = 0; ix < colCount; ix++) {
506     int iColStore = ix + iStorageOffset;
507     ImageFileColumn vCol = v[iColStore];
508     for (int iy = 0; iy < ny; iy++)
509       *vCol++ = 0;
510   }
511   
512   double x_start = xmin + (colStart * xinc);
513   for (PElemConstIterator pelem = m_listPElem.begin(); pelem != m_listPElem.end(); pelem++) {
514     const PhantomElement& rPElem = **pelem;
515     double x, y, xi, yi;
516     int ix, iy, kx, ky;
517     for (ix = 0, x = x_start; ix < colCount; ix++, x += xinc) {
518       int iColStore = ix + iStorageOffset;
519       ImageFileColumn vCol = v[iColStore];
520       for (iy = 0, y = ymin; iy < ny; iy++, y += yinc) {
521         double dAtten = 0;
522         for (kx = 0, xi = x + kxofs; kx < nsample; kx++, xi += kxinc) {
523           for (ky = 0, yi = y + kyofs; ky < nsample; ky++, yi += kyinc)
524             if (rPElem.isPointInside (xi, yi, PHM_COORD))
525               dAtten += rPElem.atten();
526         } // for kx
527         *vCol++ += dAtten;
528       } /* for iy */
529     }  /* for ix */
530   }  /* for pelem */
531   
532   
533   if (nsample > 1) {
534     double factor = 1.0 / static_cast<double>(nsample * nsample);
535     
536     
537     for (int ix = 0; ix < colCount; ix++) {
538       int iColStore = ix + iStorageOffset;
539       ImageFileColumn vCol = v[iColStore];
540       for (int iy = 0; iy < ny; iy++)
541         *vCol++ *= factor;
542     }
543   }
544 }
545
546 ////////////////////////////////////////////////////////////////////////////////////////////////////////
547 // CLASS IDENTIFICATION
548 //
549 //      PhantomElement
550 //
551 // PURPOSE
552 //
553 ////////////////////////////////////////////////////////////////////////////////////////////////////////
554
555
556 PhantomElement::PhantomElement (const char *type, const double cx, const double cy, const double u, const double v, const double rot, const double atten)
557 : m_cx(cx), m_cy(cy), m_u(u), m_v(v), m_atten(atten), m_nPoints(0), m_xOutline(0), m_yOutline(0)
558 {
559   m_rot = convertDegreesToRadians (rot);   // convert angle to radians
560   
561   m_type = convertNameToType (type);
562   
563   makeTransformMatrices ();     // calc transform matrices between phantom and normalized phantomelement
564   makeVectorOutline ();         // calculate vector outline of pelem 
565   
566   m_rectLimits[0] = m_xmin;   m_rectLimits[1] = m_ymin;
567   m_rectLimits[2] = m_xmax;   m_rectLimits[3] = m_ymax;
568 }
569
570
571
572 PhantomElement::~PhantomElement ()
573 {
574   delete m_xOutline;
575   delete m_yOutline;
576 }
577
578 void
579 PhantomElement::printDefinition (std::ostream& os) const
580 {
581   os << convertTypeToName (m_type) << " " << m_cx << " " << m_cy << " " << m_u << " "
582     << m_v << " " << convertRadiansToDegrees (m_rot) << " " << m_atten << "\n";
583 }
584
585 void
586 PhantomElement::printDefinition (std::ostringstream& os) const
587 {
588   os << convertTypeToName (m_type) << " " << m_cx << " " << m_cy << " " << m_u << " "
589     << m_v << " " << convertRadiansToDegrees (m_rot) << " " << m_atten << "\n";
590 }
591
592 PhmElemType
593 PhantomElement::convertNameToType (const char* const typeName)
594 {
595   PhmElemType type = PELEM_INVALID;
596   
597   if (strcasecmp (typeName, "rectangle") == 0)
598     type = PELEM_RECTANGLE;
599   else if (strcasecmp (typeName, "triangle") == 0)
600     type = PELEM_TRIANGLE;
601   else if (strcasecmp (typeName, "ellipse") == 0)
602     type = PELEM_ELLIPSE;
603   else if (strcasecmp (typeName, "sector") == 0)
604     type = PELEM_SECTOR;
605   else if (strcasecmp (typeName, "segment") == 0)
606     type = PELEM_SEGMENT;
607   
608   return (type);
609 }
610
611 const char* const
612 PhantomElement::convertTypeToName (PhmElemType iType)
613 {
614   static char* pszType = "Unknown";
615   
616   if (iType == PELEM_RECTANGLE)
617     pszType = "rectangle";
618   else if (iType == PELEM_TRIANGLE)
619     pszType = "triangle";
620   else if (iType == PELEM_ELLIPSE)
621     pszType = "ellipse";
622   else if (iType == PELEM_SECTOR)
623     pszType = "sector";
624   else if (iType == PELEM_SEGMENT)
625     pszType = "segment";
626   
627   return pszType;
628 }
629
630
631 void 
632 PhantomElement::makeTransformMatrices ()
633 {
634   GRFMTX_2D temp;
635   
636   // To map normalized Pelem coords to world Phantom 
637   //     scale by (u, v)                                       
638   //     rotate by rot                                  
639   //     translate by (cx, cy)                         
640   
641   scale_mtx2 (m_xformObjToPhm, m_u, m_v);
642   rot_mtx2  (temp, m_rot);
643   mult_mtx2 (m_xformObjToPhm, temp, m_xformObjToPhm);
644   xlat_mtx2 (temp, m_cx, m_cy);
645   mult_mtx2 (m_xformObjToPhm, temp, m_xformObjToPhm);
646   
647   // to map world Phantom coodinates to normalized PElem coords
648   //     translate by (-cx, -cy)
649   //     rotate by -rot
650   //     scale by (1/u, 1/v)
651   
652   xlat_mtx2 (m_xformPhmToObj, -m_cx, -m_cy);
653   rot_mtx2  (temp, -m_rot);
654   mult_mtx2 (m_xformPhmToObj, temp, m_xformPhmToObj);
655   scale_mtx2 (temp, 1 / m_u, 1 / m_v);
656   mult_mtx2 (m_xformPhmToObj, temp, m_xformPhmToObj);
657 }
658
659
660 /* NAME
661 *   pelem_make_points           INTERNAL routine to calculate point array for an pelem
662 *
663 * SYNOPSIS
664 *   makepelempts (pelem)
665 *   PELEM *pelem        pelem whose points we are calculating
666 *
667 * NOTES
668 *   Called by phm_add_pelem()
669 */
670
671 void
672 PhantomElement::makeVectorOutline ()
673 {
674   double radius, theta, start, stop;
675   double xfact, yfact;
676   int cpts;
677   
678   m_nPoints = 0;
679   switch (m_type) {
680   case PELEM_RECTANGLE:
681     m_nPoints = 5;
682     m_xOutline = new double [m_nPoints];
683     m_yOutline = new double [m_nPoints];
684     m_xOutline[0] =-m_u;        m_yOutline[0] =-m_v;
685     m_xOutline[1] = m_u;        m_yOutline[1] =-m_v;
686     m_xOutline[2] = m_u;        m_yOutline[2] = m_v;
687     m_xOutline[3] =-m_u;        m_yOutline[3] = m_v;
688     m_xOutline[4] =-m_u;        m_yOutline[4] =-m_v;
689     break;
690   case PELEM_TRIANGLE:
691     m_nPoints = 4;
692     m_xOutline = new double [m_nPoints];
693     m_yOutline = new double [m_nPoints];
694     m_xOutline[0] =-m_u;        m_yOutline[0] = 0.0;
695     m_xOutline[1] = m_u;        m_yOutline[1] = 0.0;
696     m_xOutline[2] = 0.0;        m_yOutline[2] = m_v;
697     m_xOutline[3] =-m_u;        m_yOutline[3] = 0.0;
698     break;
699   case PELEM_ELLIPSE:
700     cpts = numCirclePoints (TWOPI);
701     m_nPoints = cpts;
702     m_xOutline = new double [m_nPoints];
703     m_yOutline = new double [m_nPoints];
704     calcEllipsePoints (m_xOutline, m_yOutline, cpts, m_u, m_v);
705     break;
706   case PELEM_SECTOR:
707     radius = sqrt(m_u * m_u + m_v * m_v);
708     theta = atan(m_u / m_v);            // angle with y-axis 
709     start = 3.0 * HALFPI - theta;
710     stop  = 3.0 * HALFPI + theta;
711     cpts = numCirclePoints (stop - start);
712     m_nPoints = 3 + cpts;
713     m_xOutline = new double [m_nPoints];
714     m_yOutline = new double [m_nPoints];
715     
716     m_xOutline[0] = 0.0;                m_yOutline[0] = m_v;
717     m_xOutline[1] =-m_u;                m_yOutline[1] = 0.0;
718     calcArcPoints (&m_xOutline[2], &m_yOutline[2], cpts, 0.0, m_v, radius, start, stop);
719     m_xOutline[cpts + 2] = 0.0;
720     m_yOutline[cpts + 2] = m_v;
721     break;
722   case PELEM_SEGMENT:
723     radius = sqrt(m_u * m_u + m_v * m_v);
724     theta = atan (m_u / m_v);           // angle with y-axis 
725     start = 3.0 * HALFPI - theta;
726     stop  = 3.0 * HALFPI + theta;
727     
728     cpts = numCirclePoints (stop - start);
729     m_nPoints = cpts + 1;
730     m_xOutline = new double [m_nPoints];
731     m_yOutline = new double [m_nPoints];
732     
733     calcArcPoints (m_xOutline, m_yOutline, cpts, 0.0, m_v, radius, start, stop);
734     m_xOutline[cpts] = -m_u;
735     m_yOutline[cpts] = 0.0;
736     break;
737   default:
738     sys_error(ERR_WARNING, "Illegal phantom element type %d [makeVectorOutline]", m_type);
739     return;
740   }
741   
742   rotate2d (m_xOutline, m_yOutline, m_nPoints, m_rot);
743   xlat2d (m_xOutline, m_yOutline, m_nPoints, m_cx, m_cy);
744   
745   minmax_array (m_xOutline, m_nPoints, m_xmin, m_xmax);
746   minmax_array (m_yOutline, m_nPoints, m_ymin, m_ymax);
747   
748   // increase pelem extent by SCALE_PELEM_EXTENT to eliminate chance of
749   //   missing actual pelem maximum due to polygonal sampling 
750   
751   xfact = (m_xmax - m_xmin) * SCALE_PELEM_EXTENT;
752   yfact = (m_ymax - m_ymin) * SCALE_PELEM_EXTENT;
753   
754   m_xmin -= xfact;
755   m_ymin -= yfact;
756   m_xmax += xfact;
757   m_ymax += yfact;
758 }
759
760
761 /* NAME
762 *   calc_arc                    Calculate outline of a arc of a circle
763 *
764 * SYNOPSIS
765 *   calc_arc (x, y, xcent, ycent, pts, r, start, stop)
766 *   double x[], y[];            Array of points
767 *   int pts                     Number of points in array
768 *   double xcent, ycent Center of cirlce
769 *   double r                    Radius of circle
770 *   double start, stop          Beginning & ending angles
771 */
772
773 void 
774 PhantomElement::calcArcPoints (double x[], double y[], const int pts, const double xcent, const double ycent, const double r, const double start, const double stop)
775 {
776   if (r <= 0.0)
777     sys_error (ERR_WARNING, "negative or zero radius in calc_arc()");
778   
779   double theta = (stop - start) / (pts - 1);    // angle incr. between points 
780   double c = cos(theta);
781   double s = sin(theta);
782   
783   x[0] = r * cos (start) + xcent;
784   y[0] = r * sin (start) + ycent;
785   
786   double xp = x[0] - xcent;
787   double yp = y[0] - ycent;
788   for (int i = 1; i < pts; i++) {
789     double xc = c * xp - s * yp;
790     double yc = s * xp + c * yp;
791     x[i] = xc + xcent;
792     y[i] = yc + ycent;
793     xp = xc;  yp = yc;
794   }
795 }
796
797
798 // NAME
799 //   PhantomElement::calcEllipsePoints    Calculate outline of a ellipse
800 //
801 // SYNOPSIS
802 //   calcEllipsePoints ()
803 //
804
805
806 void 
807 PhantomElement::calcEllipsePoints (double x[], double y[], const int pts, const double u, const double v)
808 {
809   calcArcPoints (x, y, m_nPoints, 0.0, 0.0, 1.0, 0.0, TWOPI);   // make a unit circle 
810   scale2d (x, y, m_nPoints, m_u, m_v);                       // scale to ellipse 
811 }
812
813
814 /* NAME
815 *   circle_pts          Calculate number of points to use for circle segment
816 *
817 * SYNOPSIS
818 *   n = circle_pts (theta)
819 *   int n               Number of points to use for arc
820 *   double theta        Length of arc in radians
821 */
822
823 int 
824 PhantomElement::numCirclePoints (double theta)
825 {
826   theta = clamp (theta, 0., TWOPI);
827   
828   return static_cast<int> (POINTS_PER_CIRCLE * theta / TWOPI + 1.5);
829 }
830
831
832 bool
833 PhantomElement::clipLineWorldCoords (double& x1, double& y1, double& x2, double &y2) const
834 {
835   /* check if ray is outside of pelem extents */
836   double cx1 = x1, cy1 = y1, cx2 = x2, cy2 = y2;
837   if (! clip_rect (cx1, cy1, cx2, cy2, m_rectLimits))
838     return false;
839   
840   // convert phantom coordinates to pelem coordinates 
841   xform_mtx2 (m_xformPhmToObj, x1, y1);
842   xform_mtx2 (m_xformPhmToObj, x2, y2);
843   
844   if (! clipLineNormalizedCoords (x1, y1, x2, y2))
845     return false;
846   
847   // convert standard pelem coordinates back to phantom coordinates 
848   xform_mtx2 (m_xformObjToPhm, x1, y1);
849   xform_mtx2 (m_xformObjToPhm, x2, y2);
850   
851   return true;
852 }
853
854
855 /* NAME
856 *   pelem_clip_line                     Clip pelem against an arbitrary line
857 *
858 * SYNOPSIS
859 *   pelem_clip_line (pelem, x1, y1, x2, y2)
860 *   PhantomElement& pelem;              Pelem to be clipped
861 *   double *x1, *y1, *x2, *y2   Endpoints of line to be clipped
862 *
863 * RETURNS
864 *   true   if line passes through pelem
865 *               (x1, y1, x2, y2 hold coordinates of new line)
866 *   false  if line do not pass through pelem
867 *               (x1, y1, x2, y2 are undefined)
868 */
869
870 bool
871 PhantomElement::clipLineNormalizedCoords (double& x1, double& y1, double& x2, double& y2) const
872 {
873   bool accept = false;
874   
875   switch (m_type) {
876   case PELEM_RECTANGLE:
877     double rect[4];
878     rect[0] = -1.0;  rect[1] = -1.0;
879     rect[2] = 1.0;  rect[3] = 1.0;
880     accept = clip_rect (x1, y1, x2, y2, rect);
881     break;
882   case PELEM_ELLIPSE:
883     accept = clip_circle (x1, y1, x2, y2, 0.0, 0.0, 1.0, 0.0, 0.0);
884     break;
885   case PELEM_TRIANGLE:
886     accept = clip_triangle (x1, y1, x2, y2, 1.0, 1.0, true);
887     break;
888   case PELEM_SEGMENT:
889     accept = clip_segment (x1, y1, x2, y2, m_u, m_v);
890     break;
891   case PELEM_SECTOR:
892     accept = clip_sector (x1, y1, x2, y2, m_u, m_v);
893     break;
894   default:
895     sys_error (ERR_WARNING, "Illegal pelem type %d [pelem_clip_line]", m_type);
896     break;
897   }
898   
899   return(accept);
900 }
901
902
903 // METHOD IDENTIFICATION 
904 //    PhantomElement::isPointInside             Check if point is inside pelem
905 //
906 // SYNOPSIS
907 //    is_point_inside (pelem, x, y, coord_type)
908 //    double x, y               Point to see if lies in pelem
909 //    int coord_type            Coordinate type (PELEM_COORD or PHM_COORD)
910 //
911 // RETURNS
912 //    true if point lies within pelem
913 //    false if point lies outside of pelem
914
915 bool
916 PhantomElement::isPointInside (double x, double y, const CoordType coord_type) const
917 {
918   if (coord_type == PHM_COORD) {
919     xform_mtx2 (m_xformPhmToObj, x, y);
920   } else if (coord_type != PELEM_COORD) {
921     sys_error(ERR_WARNING, "Illegal coordinate type in pelem_is_point_inside");
922     return (false);
923   }
924   
925   switch (m_type) {
926   case PELEM_RECTANGLE:
927     if (x > 1. || x < -1. || y > 1. || y < -1.)
928       return (false);
929     else
930       return (true);
931     break;
932   case PELEM_TRIANGLE:
933     if (y < 0. || y > 1. - x || y > 1. + x)
934       return (false);
935     else
936       return (true);
937     break;
938   case PELEM_ELLIPSE:
939     if (x > 1. || x < -1. || y > 1. || y < -1.)
940       return (false);
941     if (x * x + y * y > 1.)             // check if inside unit circle
942       return (false);
943     else
944       return (true);
945     break;
946     
947     // for clipping segments & sectors, must NOT scale by (1/u, 1/v)
948     // because this destroys information about size of arc component 
949     
950   case PELEM_SEGMENT:
951     if (x > 1. || x < -1. || y > 0.)
952       return (false);           // clip against y > 0 
953     x *= m_u;                   // put back u & v scale 
954     y *= m_v;
955     if (x * x + (y-m_v) * (y-m_v) > m_u * m_u + m_v * m_v)
956       return (false);           // clip against circle, r = sqrt(@)
957     else
958       return (true);
959     break;
960   case PELEM_SECTOR:
961     if (x > 1. || x < -1. || y > 1.)   // extent 
962       return (false);
963     if (y > 1. - x || y > 1. + x)      // triangle      
964       return (false);                  // clip against triangle 
965     x *= m_u;                  // circle: put back u & v scale 
966     y *= m_v;
967     if (x * x + (y-m_v) * (y-m_v) > m_u * m_u + m_v * m_v)
968       return (false);                  // clip against circle 
969     else
970       return (true);
971     break;
972   default:
973     sys_error (ERR_WARNING, "Illegal pelem type in pelem_is_point_inside()");
974     break;
975   }
976   
977   return (false);
978 }
979
980