repo
stringlengths 1
152
⌀ | file
stringlengths 15
205
| code
stringlengths 0
41.6M
| file_length
int64 0
41.6M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 90
values |
---|---|---|---|---|---|---|
octomap | octomap-master/octovis/src/extern/QGLViewer/saveSnapshot.cpp | /****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "qglviewer.h"
#ifndef NO_VECTORIAL_RENDER
# include "ui_VRenderInterface.h"
# include "VRender/VRender.h"
#endif
#include "ui_ImageInterface.h"
// Output format list
# include <QImageWriter>
#include <qfileinfo.h>
#include <qfiledialog.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include <qmap.h>
#include <qinputdialog.h>
#include <qprogressdialog.h>
#include <qcursor.h>
using namespace std;
////// Static global variables - local to this file //////
// List of available output file formats, formatted for QFileDialog.
static QString formats;
// Converts QFileDialog resulting format to Qt snapshotFormat.
static QMap<QString, QString> Qtformat;
// Converts Qt snapshotFormat to QFileDialog menu string.
static QMap<QString, QString> FDFormatString;
// Converts snapshotFormat to file extension
static QMap<QString, QString> extension;
/*! Sets snapshotFileName(). */
void QGLViewer::setSnapshotFileName(const QString& name)
{
snapshotFileName_ = QFileInfo(name).absoluteFilePath();
}
#ifndef DOXYGEN
const QString& QGLViewer::snapshotFilename() const
{
qWarning("snapshotFilename is deprecated. Use snapshotFileName() (uppercase N) instead.");
return snapshotFileName();
}
#endif
/*! Opens a dialog that displays the different available snapshot formats.
Then calls setSnapshotFormat() with the selected one (unless the user cancels).
Returns \c false if the user presses the Cancel button and \c true otherwise. */
bool QGLViewer::openSnapshotFormatDialog()
{
bool ok = false;
QStringList list = formats.split(";;", QString::SkipEmptyParts);
int current = list.indexOf(FDFormatString[snapshotFormat()]);
QString format = QInputDialog::getItem(this, "Snapshot format", "Select a snapshot format", list, current, false, &ok);
if (ok)
setSnapshotFormat(Qtformat[format]);
return ok;
}
// Finds all available Qt output formats, so that they can be available in
// saveSnapshot dialog. Initialize snapshotFormat() to the first one.
void QGLViewer::initializeSnapshotFormats()
{
QList<QByteArray> list = QImageWriter::supportedImageFormats();
QStringList formatList;
for (int i=0; i < list.size(); ++i)
formatList << QString(list.at(i).toUpper());
// qWarning("Available image formats: ");
// QStringList::Iterator it = formatList.begin();
// while( it != formatList.end() )
// qWarning((*it++).); QT4 change this. qWarning no longer accepts QString
#ifndef NO_VECTORIAL_RENDER
// We add the 3 vectorial formats to the list
formatList += "EPS";
formatList += "PS";
formatList += "XFIG";
#endif
// Check that the interesting formats are available and add them in "formats"
// Unused formats: XPM XBM PBM PGM
QStringList QtText, MenuText, Ext;
QtText += "JPEG"; MenuText += "JPEG (*.jpg)"; Ext += "jpg";
QtText += "PNG"; MenuText += "PNG (*.png)"; Ext += "png";
QtText += "EPS"; MenuText += "Encapsulated Postscript (*.eps)"; Ext += "eps";
QtText += "PS"; MenuText += "Postscript (*.ps)"; Ext += "ps";
QtText += "PPM"; MenuText += "24bit RGB Bitmap (*.ppm)"; Ext += "ppm";
QtText += "BMP"; MenuText += "Windows Bitmap (*.bmp)"; Ext += "bmp";
QtText += "XFIG"; MenuText += "XFig (*.fig)"; Ext += "fig";
QStringList::iterator itText = QtText.begin();
QStringList::iterator itMenu = MenuText.begin();
QStringList::iterator itExt = Ext.begin();
while (itText != QtText.end())
{
//QMessageBox::information(this, "Snapshot ", "Trying format\n"+(*itText));
if (formatList.contains((*itText)))
{
//QMessageBox::information(this, "Snapshot ", "Recognized format\n"+(*itText));
if (formats.isEmpty())
setSnapshotFormat(*itText);
else
formats += ";;";
formats += (*itMenu);
Qtformat[(*itMenu)] = (*itText);
FDFormatString[(*itText)] = (*itMenu);
extension[(*itText)] = (*itExt);
}
// Synchronize parsing
itText++;
itMenu++;
itExt++;
}
}
// Returns false if the user refused to use the fileName
static bool checkFileName(QString& fileName, QWidget* widget, const QString& snapshotFormat)
{
if (fileName.isEmpty())
return false;
// Check that extension has been provided
QFileInfo info(fileName);
if (info.suffix().isEmpty())
{
// No extension given. Silently add one
if (fileName.right(1) != ".")
fileName += ".";
fileName += extension[snapshotFormat];
info.setFile(fileName);
}
else if (info.suffix() != extension[snapshotFormat])
{
// Extension is not appropriate. Propose a modification
QString modifiedName = info.absolutePath() + '/' + info.baseName() + "." + extension[snapshotFormat];
QFileInfo modifInfo(modifiedName);
int i=(QMessageBox::warning(widget,"Wrong extension",
info.fileName()+" has a wrong extension.\nSave as "+modifInfo.fileName()+" instead ?",
QMessageBox::Yes,
QMessageBox::No,
QMessageBox::Cancel));
if (i==QMessageBox::Cancel)
return false;
if (i==QMessageBox::Yes)
{
fileName = modifiedName;
info.setFile(fileName);
}
}
return true;
}
#ifndef NO_VECTORIAL_RENDER
// static void drawVectorial(void* param)
void drawVectorial(void* param)
{
( (QGLViewer*) param )->drawVectorial();
}
#ifndef DOXYGEN
class ProgressDialog
{
public:
static void showProgressDialog(QGLWidget* parent);
static void updateProgress(float progress, const QString& stepString);
static void hideProgressDialog();
private:
static QProgressDialog* progressDialog;
};
QProgressDialog* ProgressDialog::progressDialog = NULL;
void ProgressDialog::showProgressDialog(QGLWidget* parent)
{
progressDialog = new QProgressDialog(parent);
progressDialog->setWindowTitle("Image rendering progress");
progressDialog->setMinimumSize(300, 40);
progressDialog->setCancelButton(NULL);
progressDialog->show();
}
void ProgressDialog::updateProgress(float progress, const QString& stepString)
{
progressDialog->setValue(int(progress*100));
QString message(stepString);
if (message.length() > 33)
message = message.left(17) + "..." + message.right(12);
progressDialog->setLabelText(message);
progressDialog->update();
qApp->processEvents();
}
void ProgressDialog::hideProgressDialog()
{
progressDialog->close();
delete progressDialog;
progressDialog = NULL;
}
class VRenderInterface: public QDialog, public Ui::VRenderInterface
{
public: VRenderInterface(QWidget *parent) : QDialog(parent) { setupUi(this); }
};
#endif //DOXYGEN
// Pops-up a vectorial output option dialog box and save to fileName
// Returns -1 in case of Cancel, 0 for success and (todo) error code in case of problem.
static int saveVectorialSnapshot(const QString& fileName, QGLWidget* widget, const QString& snapshotFormat)
{
static VRenderInterface* VRinterface = NULL;
if (!VRinterface)
VRinterface = new VRenderInterface(widget);
// Configure interface according to selected snapshotFormat
if (snapshotFormat == "XFIG")
{
VRinterface->tightenBBox->setEnabled(false);
VRinterface->colorBackground->setEnabled(false);
}
else
{
VRinterface->tightenBBox->setEnabled(true);
VRinterface->colorBackground->setEnabled(true);
}
if (VRinterface->exec() == QDialog::Rejected)
return -1;
vrender::VRenderParams vparams;
vparams.setFilename(fileName);
if (snapshotFormat == "EPS") vparams.setFormat(vrender::VRenderParams::EPS);
if (snapshotFormat == "PS") vparams.setFormat(vrender::VRenderParams::PS);
if (snapshotFormat == "XFIG") vparams.setFormat(vrender::VRenderParams::XFIG);
vparams.setOption(vrender::VRenderParams::CullHiddenFaces, !(VRinterface->includeHidden->isChecked()));
vparams.setOption(vrender::VRenderParams::OptimizeBackFaceCulling, VRinterface->cullBackFaces->isChecked());
vparams.setOption(vrender::VRenderParams::RenderBlackAndWhite, VRinterface->blackAndWhite->isChecked());
vparams.setOption(vrender::VRenderParams::AddBackground, VRinterface->colorBackground->isChecked());
vparams.setOption(vrender::VRenderParams::TightenBoundingBox, VRinterface->tightenBBox->isChecked());
switch (VRinterface->sortMethod->currentIndex())
{
case 0: vparams.setSortMethod(vrender::VRenderParams::NoSorting); break;
case 1: vparams.setSortMethod(vrender::VRenderParams::BSPSort); break;
case 2: vparams.setSortMethod(vrender::VRenderParams::TopologicalSort); break;
case 3: vparams.setSortMethod(vrender::VRenderParams::AdvancedTopologicalSort); break;
default:
qWarning("VRenderInterface::saveVectorialSnapshot: Unknown SortMethod");
}
vparams.setProgressFunction(&ProgressDialog::updateProgress);
ProgressDialog::showProgressDialog(widget);
widget->makeCurrent();
widget->raise();
vrender::VectorialRender(drawVectorial, (void*) widget, vparams);
ProgressDialog::hideProgressDialog();
widget->setCursor(QCursor(Qt::ArrowCursor));
// Should return vparams.error(), but this is currently not set.
return 0;
}
#endif // NO_VECTORIAL_RENDER
class ImageInterface: public QDialog, public Ui::ImageInterface
{
public: ImageInterface(QWidget *parent) : QDialog(parent) { setupUi(this); }
};
// Pops-up an image settings dialog box and save to fileName.
// Returns false in case of problem.
bool QGLViewer::saveImageSnapshot(const QString& fileName)
{
static ImageInterface* imageInterface = NULL;
if (!imageInterface)
imageInterface = new ImageInterface(this);
imageInterface->imgWidth->setValue(width());
imageInterface->imgHeight->setValue(height());
imageInterface->imgQuality->setValue(snapshotQuality());
if (imageInterface->exec() == QDialog::Rejected)
return true;
// Hide closed dialog
qApp->processEvents();
setSnapshotQuality(imageInterface->imgQuality->value());
QColor previousBGColor = backgroundColor();
if (imageInterface->whiteBackground->isChecked())
setBackgroundColor(Qt::white);
QSize finalSize(imageInterface->imgWidth->value(), imageInterface->imgHeight->value());
qreal oversampling = imageInterface->oversampling->value();
QSize subSize(int(this->width()/oversampling), int(this->height()/oversampling));
qreal aspectRatio = width() / static_cast<qreal>(height());
qreal newAspectRatio = finalSize.width() / static_cast<qreal>(finalSize.height());
qreal zNear = camera()->zNear();
qreal zFar = camera()->zFar();
qreal xMin, yMin;
bool expand = imageInterface->expandFrustum->isChecked();
if (camera()->type() == qglviewer::Camera::PERSPECTIVE)
if ((expand && (newAspectRatio>aspectRatio)) || (!expand && (newAspectRatio<aspectRatio)))
{
yMin = zNear * tan(camera()->fieldOfView() / 2.0);
xMin = newAspectRatio * yMin;
}
else
{
xMin = zNear * tan(camera()->fieldOfView() / 2.0) * aspectRatio;
yMin = xMin / newAspectRatio;
}
else
{
camera()->getOrthoWidthHeight(xMin, yMin);
if ((expand && (newAspectRatio>aspectRatio)) || (!expand && (newAspectRatio<aspectRatio)))
xMin = newAspectRatio * yMin;
else
yMin = xMin / newAspectRatio;
}
QImage image(finalSize.width(), finalSize.height(), QImage::Format_ARGB32);
if (image.isNull())
{
QMessageBox::warning(this, "Image saving error",
"Unable to create resulting image",
QMessageBox::Ok, QMessageBox::NoButton);
return false;
}
// ProgressDialog disabled since it interfers with the screen grabing mecanism on some platforms. Too bad.
// ProgressDialog::showProgressDialog(this);
qreal scaleX = subSize.width() / static_cast<qreal>(finalSize.width());
qreal scaleY = subSize.height() / static_cast<qreal>(finalSize.height());
qreal deltaX = 2.0 * xMin * scaleX;
qreal deltaY = 2.0 * yMin * scaleY;
int nbX = finalSize.width() / subSize.width();
int nbY = finalSize.height() / subSize.height();
// Extra subimage on the right/bottom border(s) if needed
if (nbX * subSize.width() < finalSize.width())
nbX++;
if (nbY * subSize.height() < finalSize.height())
nbY++;
makeCurrent();
// tileRegion_ is used by startScreenCoordinatesSystem to appropriately set the local
// coordinate system when tiling
tileRegion_ = new TileRegion();
qreal tileXMin, tileWidth, tileYMin, tileHeight;
if ((expand && (newAspectRatio>aspectRatio)) || (!expand && (newAspectRatio<aspectRatio)))
{
qreal tileTotalWidth = newAspectRatio * height();
tileXMin = (width() - tileTotalWidth) / 2.0;
tileWidth = tileTotalWidth * scaleX;
tileYMin = 0.0;
tileHeight = height() * scaleY;
tileRegion_->textScale = 1.0 / scaleY;
}
else
{
qreal tileTotalHeight = width() / newAspectRatio;
tileYMin = (height() - tileTotalHeight) / 2.0;
tileHeight = tileTotalHeight * scaleY;
tileXMin = 0.0;
tileWidth = width() * scaleX;
tileRegion_->textScale = 1.0 / scaleX;
}
int count=0;
for (int i=0; i<nbX; i++)
for (int j=0; j<nbY; j++)
{
preDraw();
// Change projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (camera()->type() == qglviewer::Camera::PERSPECTIVE)
glFrustum(-xMin + i*deltaX, -xMin + (i+1)*deltaX, yMin - (j+1)*deltaY, yMin - j*deltaY, zNear, zFar);
else
glOrtho(-xMin + i*deltaX, -xMin + (i+1)*deltaX, yMin - (j+1)*deltaY, yMin - j*deltaY, zNear, zFar);
glMatrixMode(GL_MODELVIEW);
tileRegion_->xMin = tileXMin + i * tileWidth;
tileRegion_->xMax = tileXMin + (i+1) * tileWidth;
tileRegion_->yMin = tileYMin + j * tileHeight;
tileRegion_->yMax = tileYMin + (j+1) * tileHeight;
draw();
postDraw();
// ProgressDialog::hideProgressDialog();
// qApp->processEvents();
QImage snapshot = grabFrameBuffer(true);
// ProgressDialog::showProgressDialog(this);
// ProgressDialog::updateProgress(count / (qreal)(nbX*nbY),
// "Generating image ["+QString::number(count)+"/"+QString::number(nbX*nbY)+"]");
// qApp->processEvents();
QImage subImage = snapshot.scaled(subSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
// Copy subImage in image
for (int ii=0; ii<subSize.width(); ii++)
{
int fi = i*subSize.width() + ii;
if (fi == image.width())
break;
for (int jj=0; jj<subSize.height(); jj++)
{
int fj = j*subSize.height() + jj;
if (fj == image.height())
break;
image.setPixel(fi, fj, subImage.pixel(ii,jj));
}
}
count++;
}
bool saveOK = image.save(fileName, snapshotFormat().toLatin1().constData(), snapshotQuality());
// ProgressDialog::hideProgressDialog();
// setCursor(QCursor(Qt::ArrowCursor));
delete tileRegion_;
tileRegion_ = NULL;
if (imageInterface->whiteBackground->isChecked())
setBackgroundColor(previousBGColor);
return saveOK;
}
/*! Saves a snapshot of the current image displayed by the widget.
Options are set using snapshotFormat(), snapshotFileName() and snapshotQuality(). For non vectorial
image formats, the image size is equal to the current viewer's dimensions (see width() and
height()). See snapshotFormat() for details on supported formats.
If \p automatic is \c false (or if snapshotFileName() is empty), a file dialog is opened to ask for
the file name.
When \p automatic is \c true, the file name is set to \c NAME-NUMBER, where \c NAME is
snapshotFileName() and \c NUMBER is snapshotCounter(). The snapshotCounter() is automatically
incremented after each snapshot saving. This is useful to create videos from your application:
\code
void Viewer::init()
{
resize(720, 576); // PAL DV format (use 720x480 for NTSC DV)
connect(this, SIGNAL(drawFinished(bool)), SLOT(saveSnapshot(bool)));
}
\endcode
Then call draw() in a loop (for instance using animate() and/or a camera() KeyFrameInterpolator
replay) to create your image sequence.
If you want to create a Quicktime VR panoramic sequence, simply use code like this:
\code
void Viewer::createQuicktime()
{
const int nbImages = 36;
for (int i=0; i<nbImages; ++i)
{
camera()->setOrientation(2.0*M_PI/nbImages, 0.0); // Theta-Phi orientation
showEntireScene();
update(); // calls draw(), which emits drawFinished(), which calls saveSnapshot()
}
}
\endcode
If snapshotCounter() is negative, no number is appended to snapshotFileName() and the
snapshotCounter() is not incremented. This is useful to force the creation of a file, overwriting
the previous one.
When \p overwrite is set to \c false (default), a window asks for confirmation if the file already
exists. In \p automatic mode, the snapshotCounter() is incremented (if positive) until a
non-existing file name is found instead. Otherwise the file is overwritten without confirmation.
The VRender library was written by Cyril Soler (Cyril dot Soler at imag dot fr). If the generated
PS or EPS file is not properly displayed, remove the anti-aliasing option in your postscript viewer.
\note In order to correctly grab the frame buffer, the QGLViewer window is raised in front of
other windows by this method. */
void QGLViewer::saveSnapshot(bool automatic, bool overwrite)
{
// Ask for file name
if (snapshotFileName().isEmpty() || !automatic)
{
QString fileName;
QString selectedFormat = FDFormatString[snapshotFormat()];
fileName = QFileDialog::getSaveFileName(this, "Choose a file name to save under", snapshotFileName(), formats, &selectedFormat,
overwrite?QFileDialog::DontConfirmOverwrite:QFlags<QFileDialog::Option>(0));
setSnapshotFormat(Qtformat[selectedFormat]);
if (checkFileName(fileName, this, snapshotFormat()))
setSnapshotFileName(fileName);
else
return;
}
QFileInfo fileInfo(snapshotFileName());
if ((automatic) && (snapshotCounter() >= 0))
{
// In automatic mode, names have a number appended
const QString baseName = fileInfo.baseName();
QString count;
count.sprintf("%.04d", snapshotCounter_++);
QString suffix;
suffix = fileInfo.suffix();
if (suffix.isEmpty())
suffix = extension[snapshotFormat()];
fileInfo.setFile(fileInfo.absolutePath()+ '/' + baseName + '-' + count + '.' + suffix);
if (!overwrite)
while (fileInfo.exists())
{
count.sprintf("%.04d", snapshotCounter_++);
fileInfo.setFile(fileInfo.absolutePath() + '/' +baseName + '-' + count + '.' + fileInfo.suffix());
}
}
bool saveOK;
#ifndef NO_VECTORIAL_RENDER
if ( (snapshotFormat() == "EPS") || (snapshotFormat() == "PS") || (snapshotFormat() == "XFIG") )
// Vectorial snapshot. -1 means cancel, 0 is ok, >0 (should be) an error
saveOK = (saveVectorialSnapshot(fileInfo.filePath(), this, snapshotFormat()) <= 0);
else
#endif
if (automatic)
{
QImage snapshot = frameBufferSnapshot();
saveOK = snapshot.save(fileInfo.filePath(), snapshotFormat().toLatin1().constData(), snapshotQuality());
}
else
saveOK = saveImageSnapshot(fileInfo.filePath());
if (!saveOK)
QMessageBox::warning(this, "Snapshot problem", "Unable to save snapshot in\n"+fileInfo.filePath());
}
QImage QGLViewer::frameBufferSnapshot()
{
// Viewer must be on top of other windows.
makeCurrent();
raise();
// Hack: Qt has problems if the frame buffer is grabbed after QFileDialog is displayed.
// We grab the frame buffer before, even if it might be not necessary (vectorial rendering).
// The problem could not be reproduced on a simple example to submit a Qt bug.
// However, only grabs the backgroundImage in the eponym example. May come from the driver.
return grabFrameBuffer(true);
}
/*! Same as saveSnapshot(), except that it uses \p fileName instead of snapshotFileName().
If \p fileName is empty, opens a file dialog to select the name.
Snapshot settings are set from snapshotFormat() and snapshotQuality().
Asks for confirmation when \p fileName already exists and \p overwrite is \c false (default).
\attention If \p fileName is a char* (as is "myFile.jpg"), it may be casted into a \c bool, and the
other saveSnapshot() method may be used instead. Pass QString("myFile.jpg") as a parameter to
prevent this. */
void QGLViewer::saveSnapshot(const QString& fileName, bool overwrite)
{
const QString previousName = snapshotFileName();
const int previousCounter = snapshotCounter();
setSnapshotFileName(fileName);
setSnapshotCounter(-1);
saveSnapshot(true, overwrite);
setSnapshotFileName(previousName);
setSnapshotCounter(previousCounter);
}
/*! Takes a snapshot of the current display and pastes it to the clipboard.
This action is activated by the KeyboardAction::SNAPSHOT_TO_CLIPBOARD enum, binded to \c Ctrl+C by default.
*/
void QGLViewer::snapshotToClipboard()
{
QClipboard *cb = QApplication::clipboard();
cb->setImage(frameBufferSnapshot());
}
| 21,279 | 32.302034 | 129 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/vec.cpp | /****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "domUtils.h"
#include "vec.h"
// Most of the methods are declared inline in vec.h
using namespace qglviewer;
using namespace std;
/*! Projects the Vec on the axis of direction \p direction that passes through the origin.
\p direction does not need to be normalized (but must be non null). */
void Vec::projectOnAxis(const Vec& direction)
{
#ifndef QT_NO_DEBUG
if (direction.squaredNorm() < 1.0E-10)
qWarning("Vec::projectOnAxis: axis direction is not normalized (norm=%f).", direction.norm());
#endif
*this = (((*this)*direction) / direction.squaredNorm()) * direction;
}
/*! Projects the Vec on the plane whose normal is \p normal that passes through the origin.
\p normal does not need to be normalized (but must be non null). */
void Vec::projectOnPlane(const Vec& normal)
{
#ifndef QT_NO_DEBUG
if (normal.squaredNorm() < 1.0E-10)
qWarning("Vec::projectOnPlane: plane normal is not normalized (norm=%f).", normal.norm());
#endif
*this -= (((*this)*normal) / normal.squaredNorm()) * normal;
}
/*! Returns a Vec orthogonal to the Vec. Its norm() depends on the Vec, but is zero only for a
null Vec. Note that the function that associates an orthogonalVec() to a Vec is not continous. */
Vec Vec::orthogonalVec() const
{
// Find smallest component. Keep equal case for null values.
if ((fabs(y) >= 0.9*fabs(x)) && (fabs(z) >= 0.9*fabs(x)))
return Vec(0.0, -z, y);
else
if ((fabs(x) >= 0.9*fabs(y)) && (fabs(z) >= 0.9*fabs(y)))
return Vec(-z, 0.0, x);
else
return Vec(-y, x, 0.0);
}
/*! Constructs a Vec from a \c QDomElement representing an XML code of the form
\code< anyTagName x=".." y=".." z=".." />\endcode
If one of these attributes is missing or is not a number, a warning is displayed and the associated
value is set to 0.0.
See also domElement() and initFromDOMElement(). */
Vec::Vec(const QDomElement& element)
{
QStringList attribute;
attribute << "x" << "y" << "z";
for (int i=0; i<attribute.size(); ++i)
#ifdef QGLVIEWER_UNION_NOT_SUPPORTED
this->operator[](i) = DomUtils::qrealFromDom(element, attribute[i], 0.0);
#else
v_[i] = DomUtils::qrealFromDom(element, attribute[i], 0.0);
#endif
}
/*! Returns an XML \c QDomElement that represents the Vec.
\p name is the name of the QDomElement tag. \p doc is the \c QDomDocument factory used to create
QDomElement.
When output to a file, the resulting QDomElement will look like:
\code
<name x=".." y=".." z=".." />
\endcode
Use initFromDOMElement() to restore the Vec state from the resulting \c QDomElement. See also the
Vec(const QDomElement&) constructor.
Here is complete example that creates a QDomDocument and saves it into a file:
\code
Vec sunPos;
QDomDocument document("myDocument");
QDomElement sunElement = document.createElement("Sun");
document.appendChild(sunElement);
sunElement.setAttribute("brightness", sunBrightness());
sunElement.appendChild(sunPos.domElement("sunPosition", document));
// Other additions to the document hierarchy...
// Save doc document
QFile f("myFile.xml");
if (f.open(IO_WriteOnly))
{
QTextStream out(&f);
document.save(out, 2);
f.close();
}
\endcode
See also Quaternion::domElement(), Frame::domElement(), Camera::domElement()... */
QDomElement Vec::domElement(const QString& name, QDomDocument& document) const
{
QDomElement de = document.createElement(name);
de.setAttribute("x", QString::number(x));
de.setAttribute("y", QString::number(y));
de.setAttribute("z", QString::number(z));
return de;
}
/*! Restores the Vec state from a \c QDomElement created by domElement().
The \c QDomElement should contain \c x, \c y and \c z attributes. If one of these attributes is
missing or is not a number, a warning is displayed and the associated value is set to 0.0.
To restore the Vec state from an xml file, use:
\code
// Load DOM from file
QDomDocument doc;
QFile f("myFile.xml");
if (f.open(IO_ReadOnly))
{
doc.setContent(&f);
f.close();
}
// Parse the DOM tree and initialize
QDomElement main=doc.documentElement();
myVec.initFromDOMElement(main);
\endcode
See also the Vec(const QDomElement&) constructor. */
void Vec::initFromDOMElement(const QDomElement& element)
{
const Vec v(element);
*this = v;
}
ostream& operator<<(ostream& o, const Vec& v)
{
return o << v.x << '\t' << v.y << '\t' << v.z;
}
| 5,296 | 31.10303 | 99 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/vec.h | /****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef QGLVIEWER_VEC_H
#define QGLVIEWER_VEC_H
#include <math.h>
#include <iostream>
# include <QDomElement>
// Included by all files as vec.h is at the end of the include hierarchy
#include "config.h" // Specific configuration options.
namespace qglviewer {
/*! \brief The Vec class represents 3D positions and 3D vectors.
\class Vec vec.h QGLViewer/vec.h
Vec is used as a parameter and return type by many methods of the library. It provides classical
algebraic computational methods and is compatible with OpenGL:
\code
// Draws a point located at 3.0 OpenGL units in front of the camera
Vec pos = camera()->position() + 3.0 * camera()->viewDirection();
glBegin(GL_POINTS);
glVertex3fv(pos);
glEnd();
\endcode
This makes of Vec a good candidate for representing positions and vectors in your programs. Since
it is part of the \c qglviewer namespace, specify \c qglviewer::Vec or use the qglviewer
namespace:
\code
using namespace qglviewer;
\endcode
<h3>Interface with other vector classes</h3>
Vec implements a universal explicit converter, based on the \c [] \c operator.
Everywhere a \c const \c Vec& argument is expected, you can use your own vector type
instead, as long as it implements this operator (see the Vec(const C& c) documentation).
See also the Quaternion and the Frame documentations.
\nosubgrouping */
class QGLVIEWER_EXPORT Vec
{
// If your compiler complains the "The class "qglviewer::Vec" has no member "x"."
// Add your architecture Q_OS_XXXX flag (see qglobal.h) in this list.
#if defined (Q_OS_IRIX) || defined (Q_OS_AIX) || defined (Q_OS_HPUX)
# define QGLVIEWER_UNION_NOT_SUPPORTED
#endif
public:
/*! The internal data representation is public. One can use v.x, v.y, v.z. See also operator[](). */
#if defined (DOXYGEN) || defined (QGLVIEWER_UNION_NOT_SUPPORTED)
qreal x, y, z;
#else
union
{
struct { qreal x, y, z; };
qreal v_[3];
};
#endif
/*! @name Setting the value */
//@{
/*! Default constructor. Value is set to (0,0,0). */
Vec() : x(0.0), y(0.0), z(0.0) {}
/*! Standard constructor with the x, y and z values. */
Vec(qreal X, qreal Y, qreal Z) : x(X), y(Y), z(Z) {}
/*! Universal explicit converter from any class to Vec. You can use your own vector class everywhere
a \c const \c Vec& parameter is required, as long as it implements the \c operator[ ]:
\code
class MyVec
{
// ...
qreal operator[](int i) const { returns x, y or z when i=0, 1 or 2; }
}
MyVec v(...);
camera()->setPosition(v);
\endcode
Note that standard vector types (STL, \c qreal[3], ...) implement this operator and can hence
be used in place of Vec. See also operator const qreal*() .*/
template <class C>
explicit Vec(const C& c) : x(c[0]), y(c[1]), z(c[2]) {}
// Should NOT be explicit to prevent conflicts with operator<<.
// ! Copy constructor
// Vec(const Vec& v) : x(v.x), y(v.y), z(v.z) {}
/*! Equal operator. */
Vec& operator=(const Vec& v)
{
x = v.x; y = v.y; z = v.z;
return *this;
}
/*! Set the current value. May be faster than using operator=() with a temporary Vec(x,y,z). */
void setValue(qreal X, qreal Y, qreal Z)
{ x=X; y=Y; z=Z; }
// Universal equal operator which allows the use of any type in place of Vec,
// as long as the [] operator is implemented (v[0]=v.x, v[1]=v.y, v[2]=v.z).
// template <class C>
// Vec& operator=(const C& c)
// {
// x=c[0]; y=c[1]; z=c[2];
// return *this;
// }
//@}
/*! @name Accessing the value */
//@{
/*! Bracket operator, with a constant return value. \p i must range in [0..2]. */
qreal operator[](int i) const {
#ifdef QGLVIEWER_UNION_NOT_SUPPORTED
return (&x)[i];
#else
return v_[i];
#endif
}
/*! Bracket operator returning an l-value. \p i must range in [0..2]. */
qreal& operator[](int i) {
#ifdef QGLVIEWER_UNION_NOT_SUPPORTED
return (&x)[i];
#else
return v_[i];
#endif
}
#ifndef DOXYGEN
/*! This method is deprecated since version 2.0. Use operator const double* instead. */
const double* address() const { qWarning("Vec::address() is deprecated, use operator const double* instead."); return operator const double*(); }
#endif
/*! Conversion operator returning the memory address of the vector.
Very convenient to pass a Vec pointer as a parameter to \c GLdouble OpenGL functions:
\code
Vec pos, normal;
glNormal3dv(normal);
glVertex3dv(pos);
\endcode */
operator const double*() const {
#ifdef QGLVIEWER_UNION_NOT_SUPPORTED
return &x;
#else
return v_;
#endif
}
/*! Non const conversion operator returning the memory address of the vector.
Useful to pass a Vec to a method that requires and fills a \c double*, as provided by certain libraries. */
operator double*() {
#ifdef QGLVIEWER_UNION_NOT_SUPPORTED
return &x;
#else
return v_;
#endif
}
/*! Conversion operator returning the memory address of the vector.
Very convenient to pass a Vec pointer as a \c float parameter to OpenGL functions:
\code
Vec pos, normal;
glNormal3fv(normal);
glVertex3fv(pos);
\endcode
\note The returned float array is a static shared by all \c Vec instances. */
operator const float*() const {
static float* const result = new float[3];
result[0] = (float)x;
result[1] = (float)y;
result[2] = (float)z;
return result;
}
//@}
/*! @name Algebraic computations */
//@{
/*! Returns the sum of the two vectors. */
friend Vec operator+(const Vec &a, const Vec &b)
{
return Vec(a.x+b.x, a.y+b.y, a.z+b.z);
}
/*! Returns the difference of the two vectors. */
friend Vec operator-(const Vec &a, const Vec &b)
{
return Vec(a.x-b.x, a.y-b.y, a.z-b.z);
}
/*! Unary minus operator. */
friend Vec operator-(const Vec &a)
{
return Vec(-a.x, -a.y, -a.z);
}
/*! Returns the product of the vector with a scalar. */
friend Vec operator*(const Vec &a, qreal k)
{
return Vec(a.x*k, a.y*k, a.z*k);
}
/*! Returns the product of a scalar with the vector. */
friend Vec operator*(qreal k, const Vec &a)
{
return a*k;
}
/*! Returns the division of the vector with a scalar.
Too small \p k values are \e not tested (unless the library was compiled with the "debug" Qt \c
CONFIG flag) and may result in \c NaN values. */
friend Vec operator/(const Vec &a, qreal k)
{
#ifndef QT_NO_DEBUG
if (fabs(k) < 1.0E-10)
qWarning("Vec::operator / : dividing by a null value (%f)", k);
#endif
return Vec(a.x/k, a.y/k, a.z/k);
}
/*! Returns \c true only when the two vector are not equal (see operator==()). */
friend bool operator!=(const Vec &a, const Vec &b)
{
return !(a==b);
}
/*! Returns \c true when the squaredNorm() of the difference vector is lower than 1E-10. */
friend bool operator==(const Vec &a, const Vec &b)
{
const qreal epsilon = 1.0E-10;
return (a-b).squaredNorm() < epsilon;
}
/*! Adds \p a to the vector. */
Vec& operator+=(const Vec &a)
{
x += a.x; y += a.y; z += a.z;
return *this;
}
/*! Subtracts \p a to the vector. */
Vec& operator-=(const Vec &a)
{
x -= a.x; y -= a.y; z -= a.z;
return *this;
}
/*! Multiply the vector by a scalar \p k. */
Vec& operator*=(qreal k)
{
x *= k; y *= k; z *= k;
return *this;
}
/*! Divides the vector by a scalar \p k.
An absolute \p k value lower than 1E-10 will print a warning if the library was compiled with the
"debug" Qt \c CONFIG flag. Otherwise, no test is performed for efficiency reasons. */
Vec& operator/=(qreal k)
{
#ifndef QT_NO_DEBUG
if (fabs(k)<1.0E-10)
qWarning("Vec::operator /= : dividing by a null value (%f)", k);
#endif
x /= k; y /= k; z /= k;
return *this;
}
/*! Dot product of the two Vec. */
friend qreal operator*(const Vec &a, const Vec &b)
{
return a.x*b.x + a.y*b.y + a.z*b.z;
}
/*! Cross product of the two vectors. Same as cross(). */
friend Vec operator^(const Vec &a, const Vec &b)
{
return cross(a,b);
}
/*! Cross product of the two Vec. Mind the order ! */
friend Vec cross(const Vec &a, const Vec &b)
{
return Vec(a.y*b.z - a.z*b.y,
a.z*b.x - a.x*b.z,
a.x*b.y - a.y*b.x);
}
Vec orthogonalVec() const;
//@}
/*! @name Norm of the vector */
//@{
#ifndef DOXYGEN
/*! This method is deprecated since version 2.0. Use squaredNorm() instead. */
qreal sqNorm() const { return x*x + y*y + z*z; }
#endif
/*! Returns the \e squared norm of the Vec. */
qreal squaredNorm() const { return x*x + y*y + z*z; }
/*! Returns the norm of the vector. */
qreal norm() const { return sqrt(x*x + y*y + z*z); }
/*! Normalizes the Vec and returns its original norm.
Normalizing a null vector will result in \c NaN values. */
qreal normalize()
{
const qreal n = norm();
#ifndef QT_NO_DEBUG
if (n < 1.0E-10)
qWarning("Vec::normalize: normalizing a null vector (norm=%f)", n);
#endif
*this /= n;
return n;
}
/*! Returns a unitary (normalized) \e representation of the vector. The original Vec is not modified. */
Vec unit() const
{
Vec v = *this;
v.normalize();
return v;
}
//@}
/*! @name Projection */
//@{
void projectOnAxis(const Vec& direction);
void projectOnPlane(const Vec& normal);
//@}
/*! @name XML representation */
//@{
explicit Vec(const QDomElement& element);
QDomElement domElement(const QString& name, QDomDocument& document) const;
void initFromDOMElement(const QDomElement& element);
//@}
#ifdef DOXYGEN
/*! @name Output stream */
//@{
/*! Output stream operator. Enables debugging code like:
\code
Vec pos(...);
cout << "Position=" << pos << endl;
\endcode */
std::ostream& operator<<(std::ostream& o, const qglviewer::Vec&);
//@}
#endif
};
} // namespace
std::ostream& operator<<(std::ostream& o, const qglviewer::Vec&);
#endif // QGLVIEWER_VEC_H
| 10,657 | 26.258312 | 146 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/AxisAlignedBox.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_AXISALIGNEDBOX_H
#define _VRENDER_AXISALIGNEDBOX_H
namespace vrender
{
class Vector2;
class Vector3;
template<class T> class AxisAlignedBox
{
public:
AxisAlignedBox() ;
AxisAlignedBox(const T& v) ;
AxisAlignedBox(const T& v,const T& w) ;
const T& mini() const { return _min ; }
const T& maxi() const { return _max ; }
void include(const T& v) ;
void include(const AxisAlignedBox<T>& b) ;
private:
T _min ;
T _max ;
};
typedef AxisAlignedBox< Vector2 > AxisAlignedBox_xy ;
typedef AxisAlignedBox< Vector3 > AxisAlignedBox_xyz ;
template<class T> AxisAlignedBox<T>::AxisAlignedBox()
: _min(T::inf), _max(-T::inf)
{
}
template<class T> AxisAlignedBox<T>::AxisAlignedBox(const T& v)
: _min(v), _max(v)
{
}
template<class T> AxisAlignedBox<T>::AxisAlignedBox(const T& v,const T& w)
: _min(v), _max(v)
{
include(w) ;
}
template<class T> void AxisAlignedBox<T>::include(const T& v)
{
_min = T::mini(_min,v) ;
_max = T::maxi(_max,v) ;
}
template<class T> void AxisAlignedBox<T>::include(const AxisAlignedBox<T>& b)
{
include(b._min) ;
include(b._max) ;
}
}
#endif
| 2,992 | 28.343137 | 78 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/BSPSortMethod.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "VRender.h"
#include "Primitive.h"
#include "SortMethod.h"
#include "math.h" // fabs
using namespace vrender;
using namespace std;
double EGALITY_EPS = 0.0001;
double LINE_EGALITY_EPS = 0.0001;
typedef enum { BSP_CROSS_PLANE, BSP_UPPER, BSP_LOWER } BSPPosition;
class BSPNode;
class BSPTree
{
public:
BSPTree();
~BSPTree();
void insert(Polygone *);
void insert(Segment *);
void insert(Point *);
void recursFillPrimitiveArray(vector<PtrPrimitive>&) const;
private:
BSPNode *_root;
vector<Segment *> _segments; // these are for storing segments and points when _root is null
vector<Point *> _points;
};
void BSPSortMethod::sortPrimitives(std::vector<PtrPrimitive>& primitive_tab,VRenderParams& vparams)
{
// 1 - build BSP using polygons only
BSPTree tree;
Polygone *P;
unsigned int N = primitive_tab.size()/200 +1;
int nbinserted = 0;
vector<PtrPrimitive> segments_and_points; // Store segments and points for pass 2, because polygons are deleted
// by the insertion and can not be dynamic_casted anymore.
for(unsigned int i=0;i<primitive_tab.size();++i,++nbinserted)
{
if((P = dynamic_cast<Polygone *>(primitive_tab[i])) != NULL)
tree.insert(P);
else
segments_and_points.push_back(primitive_tab[i]);
if(nbinserted%N==0)
vparams.progress(nbinserted/(float)primitive_tab.size(), QGLViewer::tr("BSP Construction"));
}
// 2 - insert points and segments into the BSP
Segment *S;
Point *p;
for(unsigned int j=0;j<segments_and_points.size();++j,++nbinserted)
{
if((S = dynamic_cast<Segment *>(segments_and_points[j])) != NULL)
tree.insert(S);
else if((p = dynamic_cast<Point *>(segments_and_points[j])) != NULL)
tree.insert(p);
if(nbinserted%N==0)
vparams.progress(nbinserted/(float)primitive_tab.size(), QGLViewer::tr("BSP Construction"));
}
// 3 - refill the array with the content of the BSP
primitive_tab.resize(0);
tree.recursFillPrimitiveArray(primitive_tab);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
class BSPNode
{
public:
BSPNode(Polygone *);
~BSPNode();
void recursFillPrimitiveArray(vector<PtrPrimitive>&) const;
void insert(Polygone *);
void insert(Segment *);
void insert(Point *);
private:
double a,b,c,d;
BSPNode *fils_moins;
BSPNode *fils_plus;
vector<Segment *> seg_plus;
vector<Segment *> seg_moins;
vector<Point *> pts_plus;
vector<Point *> pts_moins;
Polygone *polygone;
void Classify(Polygone *, Polygone * &, Polygone * &);
void Classify(Segment *, Segment * &, Segment * &);
int Classify(Point *);
void initEquation(const Polygone *P,double & a, double & b, double & c, double & d);
};
BSPTree::BSPTree()
{
_root = NULL;
}
BSPTree::~BSPTree()
{
delete _root;
}
void BSPTree::insert(Point *P) { if(_root == NULL) _points.push_back(P) ; else _root->insert(P); }
void BSPTree::insert(Segment *S) { if(_root == NULL) _segments.push_back(S); else _root->insert(S); }
void BSPTree::insert(Polygone *P){ if(_root == NULL) _root = new BSPNode(P); else _root->insert(P); }
void BSPTree::recursFillPrimitiveArray(vector<PtrPrimitive>& tab) const
{
if(_root != NULL) _root->recursFillPrimitiveArray(tab);
for(unsigned int i=0;i<_points.size();++i) tab.push_back(_points[i]);
for(unsigned int j=0;j<_segments.size();++j) tab.push_back(_segments[j]);
}
//----------------------------------------------------------------------------//
BSPNode::~BSPNode()
{
delete fils_moins;
delete fils_plus;
}
int BSPNode::Classify(Point *P)
{
double Z = P->sommet3DColor(0).x() * a + P->sommet3DColor(0).y() * b + P->sommet3DColor(0).z() * c - d;
if(Z > EGALITY_EPS)
return 1;
else
return -1;
}
void BSPNode::Classify(Segment *S, Segment * & moins_, Segment * & plus_)
{
double Z1 = S->sommet3DColor(0).x() * a + S->sommet3DColor(0).y() * b + S->sommet3DColor(0).z() * c - d;
double Z2 = S->sommet3DColor(1).x() * a + S->sommet3DColor(1).y() * b + S->sommet3DColor(1).z() * c - d;
int s1, s2;
if(Z1 < -LINE_EGALITY_EPS)
s1 = -1;
else if(Z1 > EGALITY_EPS)
s1 = 1;
else
s1 = 0;
if(Z2 < -LINE_EGALITY_EPS)
s2 = -1;
else if(Z2 > EGALITY_EPS)
s2 = 1;
else
s2 = 0;
if(s1 == -s2)
{
if(s1 == 0)
{
moins_ = S;
plus_ = NULL;
return;
}
else
{
double t = fabs(Z1/(Z2 - Z1));
if((t < 0.0)||(t > 1.0))
{
if(t > 1.0) t = 0.999;
if(t < 0.0) t = 0.001;
}
Feedback3DColor newVertex((1-t)*S->sommet3DColor(0) + t*S->sommet3DColor(1));
if(s1 > 0)
{
plus_ = new Segment(S->sommet3DColor(0), newVertex);
moins_ = new Segment(newVertex, S->sommet3DColor(1));
}
else
{
plus_ = new Segment(newVertex, S->sommet3DColor(1));
moins_ = new Segment(S->sommet3DColor(0), newVertex);
}
delete S;
return;
}
}
else if(s1 == s2)
{
if(s1 == -1)
{
moins_ = S;
plus_ = NULL;
return;
}
else
{
moins_ = NULL;
plus_ = S;
return;
}
}
else if(s1 == 0)
{
if(s2 > 0)
{
moins_ = NULL;
plus_ = S;
return;
}
else
{
moins_ = S;
plus_ = NULL;
return;
}
}
else if(s2 == 0)
{
if(s1 > 0)
{
moins_ = NULL;
plus_ = S;
return;
}
else
{
moins_ = S;
plus_ = NULL;
return;
}
}
//else
//printf("BSPNode::Classify: unexpected classification case !!\n");
}
void BSPNode::Classify(Polygone *P, Polygone * & moins_, Polygone * & plus_)
{
static int Signs[100];
static double Zvals[100];
moins_ = NULL;
plus_ = NULL;
if(P == NULL)
{
//printf("BSPNode::Classify: Error. Null polygon.\n");
return;
}
int n = P->nbVertices();
int Smin = 1;
int Smax = -1;
// On classe les sommets en fonction de leur signe
for(int i=0;i<n;i++)
{
double Z = P->vertex(i).x() * a + P->vertex(i).y() * b + P->vertex(i).z() * c - d;
if(Z < -EGALITY_EPS)
Signs[i] = -1;
else if(Z > EGALITY_EPS)
Signs[i] = 1;
else
Signs[i] = 0;
Zvals[i] = Z;
if(Smin > Signs[i]) Smin = Signs[i];
if(Smax < Signs[i]) Smax = Signs[i];
}
// Polygone inclus dans le plan
if((Smin == 0)&&(Smax == 0))
{
moins_ = P;
plus_ = NULL;
return;
}
// Polygone tout positif
if(Smin == 1)
{
plus_ = P;
moins_ = NULL;
return;
}
// Polygone tout negatif
if(Smax == -1)
{
plus_ = NULL;
moins_ = P;
return;
}
if((Smin == -1)&&(Smax == 0))
{
plus_ = NULL;
moins_ = P;
return;
}
if((Smin == 0)&&(Smax == 1))
{
plus_ = P;
moins_ = NULL;
return;
}
// Reste le cas Smin = -1 et Smax = 1. Il faut couper
vector<Feedback3DColor> Ps;
vector<Feedback3DColor> Ms;
// On teste la coherence des signes.
int nZero = 0;
int nconsZero = 0;
for(int j=0;j<n;j++)
{
if(Signs[j] == 0)
{
nZero++;
if(Signs[(j+1)%n] == 0)
nconsZero++;
}
}
if((nZero > 2)||(nconsZero > 0))
{
// Ils y a des imprecisions numeriques dues au fait que le poly estpres du plan.
moins_ = P;
plus_ = NULL;
return;
}
int dep=0;
while(Signs[dep] == 0) dep++;
int prev_sign = Signs[dep];
for(int k=1;k<=n;k++)
{
int sign = Signs[(k+dep)%n];
if(sign == prev_sign)
{
if(sign == 1)
Ps.push_back(P->sommet3DColor(k+dep));
if(sign == -1)
Ms.push_back(P->sommet3DColor(k+dep));
}
else if(sign == -prev_sign)
{
// Il faut effectuer le calcul en utilisant les memes valeurs que pour le calcul des signes,
// sinon on risque des incoherences dues aux imprecisions numeriques.
double Z1 = Zvals[(k+dep-1)%n];
double Z2 = Zvals[(k+dep)%n];
double t = fabs(Z1/(Z2 - Z1));
if((t < 0.0)||(t > 1.0))
{
if(t > 1.0) t = 0.999;
if(t < 0.0) t = 0.001;
}
Feedback3DColor newVertex((1-t)*P->sommet3DColor(k+dep-1) + t*P->sommet3DColor(k+dep));
Ps.push_back(newVertex);
Ms.push_back(newVertex);
if(sign == 1)
Ps.push_back(P->sommet3DColor(k+dep));
if(sign == -1)
Ms.push_back(P->sommet3DColor(k+dep));
prev_sign = sign;
} // prev_sign != 0 donc necessairement sign = 0. Le sommet tombe dans le plan
else
{
Feedback3DColor newVertex = P->sommet3DColor(k+dep);
Ps.push_back(newVertex);
Ms.push_back(newVertex);
prev_sign = -prev_sign;
}
}
//if((Ps.size() > 100)||(Ms.size() > 100))
//printf("BSPNode::Classify: Error. nPs = %d, nMs = %d.\n",int(Ps.size()),int(Ms.size()));
//if(Ps.size() < 3)
//printf("BSPNode::Classify: Error. nPs = %d.\n",int(Ps.size()));
//if(Ms.size() < 3)
//printf("BSPNode::Classify: Error. nMs = %d.\n",int(Ms.size()));
// Les polygones sont convexes, car OpenGL les clip lui-meme.
// Si les parents ne sont pas degeneres, plus et moins ne le
// sont pas non plus.
plus_ = new Polygone(Ps);
moins_ = new Polygone(Ms);
delete P;
}
void BSPNode::insert(Polygone *P)
{
Polygone *side_plus = NULL, *side_moins = NULL;
// 1 - Check on which size the polygon is, possibly split.
Classify(P,side_moins,side_plus);
// 2 - insert polygons
if(side_plus != NULL) {
if(fils_plus == NULL)
fils_plus = new BSPNode(side_plus);
else
fils_plus->insert(side_plus);
}
if(side_moins != NULL) {
if(fils_moins == NULL)
fils_moins = new BSPNode(side_moins);
else
fils_moins->insert(side_moins);
}
}
void BSPNode::recursFillPrimitiveArray(vector<PtrPrimitive>& primitive_tab) const
{
if(fils_plus != NULL)
fils_plus->recursFillPrimitiveArray(primitive_tab);
for(unsigned int i=0;i<seg_plus.size();++i)
primitive_tab.push_back(seg_plus[i]);
for(unsigned int j=0;j<pts_plus.size();++j)
primitive_tab.push_back(pts_plus[j]);
if(polygone != NULL)
primitive_tab.push_back(polygone);
if(fils_moins != NULL)
fils_moins->recursFillPrimitiveArray(primitive_tab);
for(unsigned int i2=0;i2<seg_moins.size();++i2)
primitive_tab.push_back(seg_moins[i2]);
for(unsigned int j2=0;j2<pts_moins.size();++j2)
primitive_tab.push_back(pts_moins[j2]);
}
void BSPNode::insert(Point *P)
{
int res = Classify(P);
if(res == -1) {
if(fils_moins == NULL)
pts_moins.push_back(P);
else
fils_moins->insert(P);
}
if(res == 1) {
if(fils_plus == NULL)
pts_plus.push_back(P);
else
fils_plus->insert(P);
}
}
void BSPNode::insert(Segment *S)
{
Segment *side_plus = NULL, *side_moins = NULL;
Classify(S,side_moins,side_plus);
if(side_plus != NULL) {
if(fils_plus == NULL)
seg_plus.push_back(side_plus);
else
fils_plus->insert(side_plus);
}
if(side_moins != NULL) {
if(fils_moins == NULL)
seg_moins.push_back(side_moins);
else
fils_moins->insert(side_moins);
}
}
BSPNode::BSPNode(Polygone *P)
{
polygone = P;
initEquation(P,a,b,c,d);
fils_moins = NULL;
fils_plus = NULL;
}
void BSPNode::initEquation(const Polygone *P,double & a, double & b, double & c, double & d)
{
Vector3 n(0.,0.,0.);
unsigned int j = 0;
while((j < P->nbVertices())&& n.infNorm() <= 0.00001)
{
n = (P->vertex(j+2) - P->vertex(j+1))^(P->vertex(j) - P->vertex(j+1));
j++;
}
if(n.infNorm() <= 0.00001)
{
unsigned int ind = P->nbVertices();
for(unsigned int i=0;i<P->nbVertices();i++)
if((P->vertex(i+1)-P->vertex(i)).infNorm() > 0.00001)
{
ind = i;
i = P->nbVertices();
}
if(ind < P->nbVertices()) // the polygon is a true segment
{
if((P->vertex(ind+1).x() != P->vertex(ind).x())||(P->vertex(ind+1).y() != P->vertex(ind).y()))
{
n[0] = - P->vertex(ind+1).y() + P->vertex(ind).y();
n[1] = P->vertex(ind+1).x() - P->vertex(ind).x();
n[2] = 0;
}
else
{
n[0] = - P->vertex(ind+1).z() + P->vertex(ind).z();
n[1] = 0;
n[2] = P->vertex(ind+1).x() - P->vertex(ind).x();
}
}
else // the polygon is a point
{
n[0] = 1.0;
n[1] = 0.0;
n[2] = 0.0;
}
}
double D = n.norm();
if(n[2] < 0.0)
n /= -D;
else
n /= D;
d = n*P->vertex(0);
a = n[0];
b = n[1];
c = n[2];
}
| 13,716 | 20.266667 | 112 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/BackFaceCullingOptimizer.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <vector>
#include "VRender.h"
#include "Optimizer.h"
#include "Primitive.h"
using namespace std ;
using namespace vrender ;
// Over-simplified algorithm to check wether a polygon is front-facing or not.
// Only works for convex polygons.
void BackFaceCullingOptimizer::optimize(std::vector<PtrPrimitive>& primitives_tab,VRenderParams&)
{
Polygone *P ;
int nb_culled = 0 ;
for(size_t i=0;i<primitives_tab.size();++i)
if((P = dynamic_cast<Polygone *>(primitives_tab[i])) != NULL)
{
for(unsigned int j=0;j<P->nbVertices();++j)
if(( (P->vertex(j+2) - P->vertex(j+1))^(P->vertex(j+1) - P->vertex(j))).z() > 0.0 )
{
delete primitives_tab[i] ;
primitives_tab[i] = NULL ;
++nb_culled ;
break ;
}
}
// Rule out gaps. This avoids testing for null primitives later.
int j=0 ;
for(size_t k=0;k<primitives_tab.size();++k)
if(primitives_tab[k] != NULL)
primitives_tab[j++] = primitives_tab[k] ;
primitives_tab.resize(j) ;
#ifdef DEBUG_BFC
cout << "Backface culling: " << nb_culled << " polygons culled." << endl ;
#endif
}
| 2,921 | 32.976744 | 97 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/EPSExporter.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <stdio.h>
#include "Primitive.h"
#include "Exporter.h"
#include "math.h"
using namespace vrender ;
using namespace std ;
const double EPSExporter::EPS_GOURAUD_THRESHOLD = 0.05 ;
const char *EPSExporter::CREATOR = "VRender library - (c) Cyril Soler 2005" ;
float EPSExporter::last_r = -1.0 ;
float EPSExporter::last_g = -1.0 ;
float EPSExporter::last_b = -1.0 ;
EPSExporter::EPSExporter()
{
last_r = -1 ;
last_g = -1 ;
last_b = -1 ;
}
void EPSExporter::writeHeader(QTextStream& out) const
{
/* Emit EPS header. */
out << "%!PS-Adobe-2.0 EPSF-2.0\n";
out << "%%%%HiResBoundingBox: " << _xmin << " " << _ymin << " " << _xmax << " " << _ymax << "\n";
out << "%%%%Creator: " << CREATOR << " (using OpenGL feedback)\n";
out << "%%EndComments\n\ngsave\n\n";
out << "%\n";
out << "% Contributors:\n";
out << "%\n";
out << "% Frederic Delhoume ([email protected]):\n";
out << "% Gouraud triangle PostScript fragment\n";
out << "%\n";
out << "% Cyril Soler ([email protected]):\n";
out << "% BSP Sort,\n";
out << "% Topological and advanced topological Sort,\n";
out << "% Hidden surface removal,\n";
out << "% Xfig3.2 (and EPS) format\n";
out << "%\n\n";
out << "/threshold " << EPS_GOURAUD_THRESHOLD << " def\n";
for(int i = 0; GOURAUD_TRIANGLE_EPS[i] != NULL; i++)
out << GOURAUD_TRIANGLE_EPS[i] << "\n";
#ifdef A_VOIR
out << "\n" << << " setlinewidth\n\n", _lineWidth;
#endif
/* Clear the background like OpenGL had it. */
if(_clearBG)
{
out << _clearR << " " << _clearG << " " << _clearB << " setrgbcolor\n";
out << _xmin << " " << _ymin << " " << _xmax << " " << _ymax << " rectfill\n\n";
}
}
void EPSExporter::writeFooter(QTextStream& out) const
{
out << "grestore\n\n";
out << "% uncomment next line to be able to print to a printer.\n";
out << "% showpage\n";
}
void PSExporter::writeFooter(QTextStream& out) const
{
out << "showpage\n";
}
const char *EPSExporter::GOURAUD_TRIANGLE_EPS[] =
{
"/bd{bind def}bind def /triangle { aload pop ",
"setrgbcolor aload pop 5 3 roll 4 2 roll 3 2 roll exch moveto lineto ",
"lineto closepath fill } bd /computediff1 { 2 copy sub abs threshold ",
"ge {pop pop pop true} { exch 2 index sub abs threshold ge { pop pop ",
"true} { sub abs threshold ge } ifelse } ifelse } bd /computediff3 { 3 ",
"copy 0 get 3 1 roll 0 get 3 1 roll 0 get computediff1 {true} { 3 copy ",
"1 get 3 1 roll 1 get 3 1 roll 1 get computediff1 {true} { 3 copy 2 ",
"get 3 1 roll 2 get 3 1 roll 2 get computediff1 } ifelse } ifelse } ",
"bd /middlecolor { aload pop 4 -1 roll aload pop 4 -1 roll add 2 div 5 ",
"1 roll 3 -1 roll add 2 div 3 1 roll add 2 div 3 1 roll exch 3 array ",
"astore } bd /gdt { computediff3 { 4 -1 roll aload 7 1 roll ",
"6 -1 roll pop 3 -1 roll pop add 2 div 3 1 roll add 2 div exch 3 -1 roll ",
"aload 7 1 roll exch pop 4 -1 roll pop add 2 div 3 1 roll add 2 div ",
"exch 3 -1 roll aload 7 1 roll pop 3 -1 roll pop add 2 div 3 1 roll add ",
"2 div exch 7 3 roll 10 -3 roll dup 3 index middlecolor 4 1 roll 2 copy ",
"middlecolor 4 1 roll 3 copy pop middlecolor 4 1 roll 13 -1 roll aload ",
"pop 17 index 6 index 15 index 19 index 6 index 17 index 6 array astore ",
"10 index 10 index 14 index gdt 17 index 5 index 17 index ",
"19 index 5 index 19 index 6 array astore 10 index 9 index 13 index ",
"gdt 13 index 16 index 5 index 15 index 18 index 5 index 6 ",
"array astore 12 index 12 index 9 index gdt 17 index 16 ",
"index 15 index 19 index 18 index 17 index 6 array astore 10 index 12 ",
"index 14 index gdt 18 {pop} repeat } { aload pop 5 3 roll ",
"aload pop 7 3 roll aload pop 9 3 roll 8 index 6 index 4 index add add 3 ",
"div 10 1 roll 7 index 5 index 3 index add add 3 div 10 1 roll 6 index 4 ",
"index 2 index add add 3 div 10 1 roll 9 {pop} repeat 3 array astore ",
"triangle } ifelse } bd",
NULL
};
void EPSExporter::spewPolygone(const Polygone *P, QTextStream& out)
{
int nvertices;
GLfloat red, green, blue;
bool smooth;
nvertices = P->nbVertices() ;
const Feedback3DColor& vertex = Feedback3DColor(P->sommet3DColor(0)) ;
if(nvertices > 0)
{
red = vertex.red();
green = vertex.green();
blue = vertex.blue();
smooth = false;
for(int i=1;i < nvertices && !smooth; i++)
if(fabs(red - P->sommet3DColor(i).red()) > 0.01 || fabs(green - P->sommet3DColor(i).green()) > 0.01 || fabs(blue - P->sommet3DColor(i).blue()) > 0.01)
smooth = true;
if(smooth && !_blackAndWhite)
{
/* Smooth shaded polygon; varying colors at vertices. */
/* Break polygon into "nvertices-2" triangle fans. */
for (int j = 0; j < nvertices - 2; j++)
{
out << "[" << P->sommet3DColor(0).x() << " " << P->sommet3DColor(j + 1).x() << " " << P->sommet3DColor(j + 2).x()
<< " " << P->sommet3DColor(0).y() << " " << P->sommet3DColor(j + 1).y() << " " << P->sommet3DColor(j + 2).y() << "]";
out << " [" << P->sommet3DColor(0 ).red() << " " << P->sommet3DColor(0 ).green() << " " << P->sommet3DColor(0 ).blue()
<< "] [" << P->sommet3DColor(j + 1).red() << " " << P->sommet3DColor(j + 1).green() << " " << P->sommet3DColor(j + 1).blue()
<< "] [" << P->sommet3DColor(j + 2).red() << " " << P->sommet3DColor(j + 2).green() << " " << P->sommet3DColor(j + 2).blue() << "] gdt\n";
last_r = last_g = last_b = -1.0 ;
}
}
else
{
/* Flat shaded polygon and white polygons; all vertex colors the same. */
out << "newpath\n";
if(_blackAndWhite)
setColor(out,1.0,1.0,1.0) ;
else
setColor(out,red,green,blue) ;
/* Draw a filled triangle. */
out << P->sommet3DColor(0).x() << " " << P->sommet3DColor(0).y() << " moveto\n";
for (int i = 1; i < nvertices; i++)
out << P->sommet3DColor(i).x() << " " << P->sommet3DColor(i).y() << " lineto\n";
out << "closepath fill\n\n";
}
}
}
void EPSExporter::spewSegment(const Segment *S, QTextStream& out)
{
GLdouble dx, dy;
GLfloat dr, dg, db, absR, absG, absB, colormax;
int steps;
GLdouble xstep=0.0, ystep=0.0;
GLfloat rstep=0.0, gstep=0.0, bstep=0.0;
GLdouble xnext=0.0, ynext=0.0, distance=0.0;
GLfloat rnext=0.0, gnext=0.0, bnext=0.0;
const Feedback3DColor& P1 = Feedback3DColor(S->sommet3DColor(0)) ;
const Feedback3DColor& P2 = Feedback3DColor(S->sommet3DColor(1)) ;
dr = P2.red() - P1.red();
dg = P2.green() - P1.green();
db = P2.blue() - P1.blue();
if((!_blackAndWhite)&&(dr != 0 || dg != 0 || db != 0))
{
/* Smooth shaded line. */
dx = P2.x() - P1.x();
dy = P2.y() - P1.y();
distance = sqrt(dx*dx + dy*dy);
absR = fabs(dr);
absG = fabs(dg);
absB = fabs(db);
colormax = max(absR, max(absG, absB));
steps = int(0.5f + max(1.0, colormax * distance * EPS_SMOOTH_LINE_FACTOR));
xstep = dx / steps;
ystep = dy / steps;
rstep = dr / steps;
gstep = dg / steps;
bstep = db / steps;
xnext = P1.x();
ynext = P1.y();
rnext = P1.red();
gnext = P1.green();
bnext = P1.blue();
/* Back up half a step; we want the end points to be
exactly the their endpoint colors. */
xnext -= xstep / 2.0;
ynext -= ystep / 2.0;
rnext -= rstep / 2.0f;
gnext -= gstep / 2.0f;
bnext -= bstep / 2.0f;
}
else
steps = 0; /* Single color line. */
if(_blackAndWhite)
setColor(out,0.0,0.0,0.0) ;
else
setColor(out,P1.red(),P1.green(),P1.blue()) ;
out << P1.x() << " " << P1.y() << " moveto\n";
for(int i = 0;i < steps;i++)
{
xnext += xstep;
ynext += ystep;
rnext += rstep;
gnext += gstep;
bnext += bstep;
out << xnext << " " << ynext << " lineto stroke\n";
out << rnext << " " << gnext << " " << bnext << " setrgbcolor\n";
out << xnext << " " << ynext << " moveto\n";
last_r = last_g = last_b = -1.0 ;
}
out << P2.x() << " " << P2.y() << " lineto stroke\n";
}
void EPSExporter::spewPoint(const Point *P, QTextStream& out)
{
const Feedback3DColor& p = Feedback3DColor(P->sommet3DColor(0)) ;
if(_blackAndWhite)
setColor(out,0.0,0.0,0.0) ;
else
setColor(out,p.red(),p.green(),p.blue()) ;
out << p.x() << " " << p.y() << " " << (_pointSize / 2.0) << " 0 360 arc fill\n\n";
}
void EPSExporter::setColor(QTextStream& out, float red, float green, float blue)
{
if(last_r != red || last_g != green || last_b != blue)
out << red << " " << green << " " << blue << " setrgbcolor\n";
last_r = red ;
last_g = green ;
last_b = blue ;
}
| 10,250 | 31.235849 | 153 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Exporter.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "VRender.h"
#include "Exporter.h"
#include "../qglviewer.h"
#include <QFile>
#include <QMessageBox>
using namespace vrender ;
using namespace std ;
Exporter::Exporter()
{
_xmin=_xmax=_ymin=_ymax=_zmin=_zmax = 0.0 ;
_pointSize=1 ;
}
void Exporter::exportToFile(const QString& filename,
const vector<PtrPrimitive>& primitive_tab,
VRenderParams& vparams)
{
QFile file(filename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(NULL, QGLViewer::tr("Exporter error", "Message box window title"), QGLViewer::tr("Unable to open file %1.").arg(filename));
return;
}
QTextStream out(&file);
writeHeader(out) ;
unsigned int N = primitive_tab.size()/200 + 1 ;
for(unsigned int i=0;i<primitive_tab.size();++i)
{
Point *p = dynamic_cast<Point *>(primitive_tab[i]) ;
Segment *s = dynamic_cast<Segment *>(primitive_tab[i]) ;
Polygone *P = dynamic_cast<Polygone *>(primitive_tab[i]) ;
if(p != NULL) spewPoint(p,out) ;
if(s != NULL) spewSegment(s,out) ;
if(P != NULL) spewPolygone(P,out) ;
if(i%N == 0)
vparams.progress(i/(float)primitive_tab.size(),QGLViewer::tr("Exporting to file %1").arg(filename)) ;
}
writeFooter(out) ;
file.close();
}
void Exporter::setBoundingBox(float xmin,float ymin,float xmax,float ymax)
{
_xmin = xmin ;
_ymin = ymin ;
_xmax = xmax ;
_ymax = ymax ;
}
void Exporter::setClearColor(float r, float g, float b) { _clearR=r; _clearG=g; _clearB=b; }
void Exporter::setClearBackground(bool b) { _clearBG=b; }
void Exporter::setBlackAndWhite(bool b) { _blackAndWhite = b; }
| 3,427 | 30.449541 | 146 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Exporter.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_EXPORTER_H
#define _VRENDER_EXPORTER_H
// Set of classes for exporting in various formats, like EPS, XFig3.2, SVG.
#include "Primitive.h"
#include "../config.h"
#include <QTextStream>
#include <QString>
namespace vrender
{
class VRenderParams ;
class Exporter
{
public:
Exporter() ;
virtual ~Exporter() {};
virtual void exportToFile(const QString& filename,const std::vector<PtrPrimitive>&,VRenderParams&) ;
void setBoundingBox(float xmin,float ymin,float xmax,float ymax) ;
void setClearColor(float r,float g,float b) ;
void setClearBackground(bool b) ;
void setBlackAndWhite(bool b) ;
protected:
virtual void spewPoint(const Point *, QTextStream& out) = 0 ;
virtual void spewSegment(const Segment *, QTextStream& out) = 0 ;
virtual void spewPolygone(const Polygone *, QTextStream& out) = 0 ;
virtual void writeHeader(QTextStream& out) const = 0 ;
virtual void writeFooter(QTextStream& out) const = 0 ;
float _clearR,_clearG,_clearB ;
float _pointSize ;
float _lineWidth ;
GLfloat _xmin,_xmax,_ymin,_ymax,_zmin,_zmax ;
bool _clearBG,_blackAndWhite ;
};
// Exports to encapsulated postscript.
class EPSExporter: public Exporter
{
public:
EPSExporter() ;
virtual ~EPSExporter() {};
protected:
virtual void spewPoint(const Point *, QTextStream& out) ;
virtual void spewSegment(const Segment *, QTextStream& out) ;
virtual void spewPolygone(const Polygone *, QTextStream& out) ;
virtual void writeHeader(QTextStream& out) const ;
virtual void writeFooter(QTextStream& out) const ;
private:
void setColor(QTextStream& out,float,float,float) ;
static const double EPS_GOURAUD_THRESHOLD ;
static const char *GOURAUD_TRIANGLE_EPS[] ;
static const char *CREATOR ;
static float last_r ;
static float last_g ;
static float last_b ;
};
// Exports to postscript. The only difference is the filename extension and
// the showpage at the end.
class PSExporter: public EPSExporter
{
public:
virtual ~PSExporter() {};
protected:
virtual void writeFooter(QTextStream& out) const ;
};
class FIGExporter: public Exporter
{
public:
FIGExporter() ;
virtual ~FIGExporter() {};
protected:
virtual void spewPoint(const Point *, QTextStream& out) ;
virtual void spewSegment(const Segment *, QTextStream& out) ;
virtual void spewPolygone(const Polygone *, QTextStream& out) ;
virtual void writeHeader(QTextStream& out) const ;
virtual void writeFooter(QTextStream& out) const ;
private:
mutable int _sizeX ;
mutable int _sizeY ;
mutable int _depth ;
int FigCoordX(double) const ;
int FigCoordY(double) const ;
int FigGrayScaleIndex(float red, float green, float blue) const ;
};
#ifdef A_FAIRE
class SVGExporter: public Exporter
{
protected:
virtual void spewPoint(const Point *, QTextStream& out) ;
virtual void spewSegment(const Segment *, QTextStream& out) ;
virtual void spewPolygone(const Polygone *, QTextStream& out) ;
virtual void writeHeader(QTextStream& out) const ;
virtual void writeFooter(QTextStream& out) const ;
};
#endif
}
#endif
| 4,999 | 29.120482 | 103 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/FIGExporter.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "Exporter.h"
#include "math.h"
using namespace vrender ;
using namespace std ;
int FIGExporter::FigCoordX(double x) const
{
float MaxX = 12000 ;
float MaxY = MaxX * _sizeY/(float)_sizeX ;
if(MaxY > 7000)
{
MaxX *= 7000/(float)MaxY ;
MaxY = 7000 ;
}
return int(0.5f + x/_sizeX*MaxX) ;
}
int FIGExporter::FigCoordY(double y) const
{
float MaxX = 12000 ;
float MaxY = MaxX * _sizeY/(float)_sizeX ;
if(MaxY > 7000)
{
MaxX *= 7000/(float)MaxY ;
MaxY = 7000 ;
}
return int(0.5f + (1.0 - y/_sizeY)*MaxY) ;
}
int FIGExporter::FigGrayScaleIndex(float red, float green, float blue) const
{
float intensity = 0.3f*red+0.6f*green+0.1f*blue ;
return int(intensity * 20.0) ;
}
FIGExporter::FIGExporter()
{
}
void FIGExporter::writeHeader(QTextStream& out) const
{
out << "#FIG 3.2\nPortrait\nCenter\nInches\nLetter\n100.00\nSingle\n0\n1200 2\n";
_depth = 999 ;
_sizeX = int(0.5f + _xmax - _xmin) ;
_sizeY = int(0.5f + _ymax - _ymin) ;
}
void FIGExporter::writeFooter(QTextStream& out) const
{
Q_UNUSED(out);
}
void FIGExporter::spewPoint(const Point *P, QTextStream& out)
{
out << "2 1 0 5 0 7 " << (_depth--) << " 0 -1 0.000 0 1 -1 0 0 1\n";
out << "\t " << FigCoordX(P->vertex(0)[0]) << " " << FigCoordY(P->vertex(0)[1]) << "\n";
if(_depth > 0) _depth = 0 ;
}
void FIGExporter::spewSegment(const Segment *S, QTextStream& out)
{
const Feedback3DColor& P1 = Feedback3DColor(S->sommet3DColor(0)) ;
const Feedback3DColor& P2 = Feedback3DColor(S->sommet3DColor(1)) ;
GLdouble dx, dy;
GLfloat dr, dg, db, absR, absG, absB, colormax;
int steps;
GLdouble xstep, ystep;
GLfloat rstep, gstep, bstep;
GLdouble xnext, ynext, distance;
GLfloat rnext, gnext, bnext;
dr = P2.red() - P1.red();
dg = P2.green() - P1.green();
db = P2.blue() - P1.blue();
if (dr != 0 || dg != 0 || db != 0)
{
/* Smooth shaded line. */
dx = P2.x() - P1.x();
dy = P2.y() - P1.y();
distance = sqrt(dx * dx + dy * dy);
absR = fabs(dr);
absG = fabs(dg);
absB = fabs(db);
colormax = max(absR, max(absG, absB));
steps = int(0.5f + max(1.0, colormax * distance * EPS_SMOOTH_LINE_FACTOR));
xstep = dx / steps;
ystep = dy / steps;
rstep = dr / steps;
gstep = dg / steps;
bstep = db / steps;
xnext = P1.x();
ynext = P1.y();
rnext = P1.red();
gnext = P1.green();
bnext = P1.blue();
/* Back up half a step; we want the end points to be
exactly the their endpoint colors. */
xnext -= xstep / 2.0;
ynext -= ystep / 2.0;
rnext -= rstep / 2.0f;
gnext -= gstep / 2.0f;
bnext -= bstep / 2.0f;
}
else
{
/* Single color line. */
steps = 0;
}
out << "2 1 0 1 0 7 " << (_depth--) << " 0 -1 0.000 0 0 -1 0 0 2\n";
out << "\t " << FigCoordX(P1.x()) << " " << FigCoordY(P1.y());
out << " " << FigCoordX(P2.x()) << " " << FigCoordY(P2.y())<< "\n";
if(_depth > 0) _depth = 0 ;
}
void FIGExporter::spewPolygone(const Polygone *P, QTextStream& out)
{
int nvertices;
GLfloat red, green, blue;
nvertices = P->nbVertices() ;
Feedback3DColor vertex(P->sommet3DColor(0)) ;
if (nvertices > 0)
{
red = 0 ;
green = 0 ;
blue = 0 ;
for(int i = 0; i < nvertices; i++)
{
red += P->sommet3DColor(i).red() ;
green += P->sommet3DColor(i).green() ;
blue += P->sommet3DColor(i).blue() ;
}
red /= nvertices ;
green /= nvertices ;
blue /= nvertices ;
/* Flat shaded polygon; all vertex colors the same. */
if(_blackAndWhite)
out << "2 3 0 0 0 7 " << (_depth--) << " 0 20 0.000 0 0 -1 0 0 " << (nvertices+1) << "\n";
else
out << "2 3 0 0 0 7 " << (_depth--) << " 0 " << (FigGrayScaleIndex(red,green,blue)) << " 0.000 0 0 -1 0 0 " << (nvertices+1) << "\n";
/* Draw a filled triangle. */
out << "\t";
for (int j = 0; j < nvertices; j++)
out << " " << FigCoordX(P->sommet3DColor(j).x()) << " " << FigCoordY(P->sommet3DColor(j).y());
out << " " << FigCoordX(P->sommet3DColor(0).x()) << " " << FigCoordY(P->sommet3DColor(0).y()) << "\n";
}
if(_depth > 0) _depth = 0 ;
}
| 5,841 | 24.849558 | 136 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/NVector3.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "NVector3.h"
#include "Vector3.h"
using namespace vrender;
NVector3::NVector3(const Vector3 &u,bool normalization)
{
setXYZ(u[0],u[1],u[2],normalization);
}
/*
Vector3 operator+(const NVector3 &u,const Vector3 &v)
{
return Vector3(u[0]+v[0],u[1]+v[1],u[2]+v[2]);
}
Vector3 operator+(const Vector3 &u,const NVector3 &v)
{
return Vector3(u[0]+v[0],u[1]+v[1],u[2]+v[2]);
}
Vector3 operator+(const NVector3 &u,const NVector3 &v)
{
return Vector3(u[0]+v[0],u[1]+v[1],u[2]+v[2]);
}
Vector3 operator-(const NVector3 &u,const Vector3 &v)
{
return Vector3(u[0]-v[0],u[1]-v[1],u[2]-v[2]);
}
Vector3 operator-(const Vector3 &u,const NVector3 &v)
{
return Vector3(u[0]-v[0],u[1]-v[1],u[2]-v[2]);
}
Vector3 operator-(const NVector3 &u,const NVector3 &v)
{
return Vector3(u[0]-v[0],u[1]-v[1],u[2]-v[2]);
}
*/
double vrender::operator*(const NVector3 &u,const Vector3 &v)
{
return u[0]*v[0] + u[1]*v[1] + u[2]*v[2];
}
double vrender::operator*(const Vector3 &u,const NVector3 &v)
{
return u[0]*v[0] + u[1]*v[1] + u[2]*v[2];
}
/*
double operator*(const NVector3 &u,const NVector3 &v)
{
return u[0]*v[0] + u[1]*v[1] + u[2]*v[2];
}
Vector3 operator*(double r,const NVector3 &u)
{
return Vector3(r*u[0],r*u[1],r*u[2]);
}
Vector3 operator/(const NVector3 &u,double r)
{
return Vector3(u[0]/r,u[1]/r,u[2]/r);
}
Vector3 operator^(const NVector3 &u,const Vector3 &v)
{
return Vector3( u[1]*v[2]-u[2]*v[1],
u[2]*v[0]-u[0]*v[2],
u[0]*v[1]-u[1]*v[0]);
}
Vector3 operator^(const Vector3 &u,const NVector3 &v)
{
return Vector3( u[1]*v[2]-u[2]*v[1],
u[2]*v[0]-u[0]*v[2],
u[0]*v[1]-u[1]*v[0]);
}
Vector3 operator^(const NVector3 &u,const NVector3 &v)
{
return Vector3( u[1]*v[2]-u[2]*v[1],
u[2]*v[0]-u[0]*v[2],
u[0]*v[1]-u[1]*v[0]);
}
*/
// -----------------------------------------------------------------------------
//! Default constructor (the default normalized vector is (1,0,0))
NVector3::NVector3()
{
_n[0] = 1.0;
_n[1] = 0.0;
_n[2] = 0.0;
}
// -----------------------------------------------------------------------------
//! Copy constructor
NVector3::NVector3(const NVector3& u)
{
_n[0] = u._n[0] ;
_n[1] = u._n[1] ;
_n[2] = u._n[2] ;
}
// -----------------------------------------------------------------------------
//! Writing X,Y and Z coordinates
void NVector3::setXYZ(double x,double y,double z,bool normalization)
{
_n[0] = x;
_n[1] = y;
_n[2] = z;
if ( normalization ) normalize();
}
// -----------------------------------------------------------------------------
//! Assignment
NVector3& NVector3::operator=(const NVector3& u)
{
if ( &u != this )
{
_n[0] = u[0];
_n[1] = u[1];
_n[2] = u[2];
}
return *this;
}
// -----------------------------------------------------------------------------
//! Out stream override: prints the 3 normalized vector components
std::ostream& operator<<(std::ostream& out,const NVector3& u)
{
out << u[0] << " " << u[1] << " " << u[2];
return out;
}
// -----------------------------------------------------------------------------
//! Normalization
//! Private method to do normalization (using Norm() method of the Vector class)
//! when it is necessary (construction of a normalized vector for exemple).
void NVector3::normalize()
{
double n = _n[0]*_n[0]+_n[1]*_n[1]+_n[2]*_n[2] ;
if ( n > 0.0 )
{
_n[0] /= n;
_n[1] /= n;
_n[2] /= n;
}
else
throw std::runtime_error("Attempt to normalize a null 3D vector.") ;
}
| 5,317 | 25.994924 | 80 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/NVector3.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_NVECTOR3_H
#define _VRENDER_NVECTOR3_H
#include <iostream>
#include <stdexcept>
namespace vrender
{
class Vector3;
class NVector3
{
public:
NVector3();
NVector3(const NVector3& u);
inline NVector3(double x,double y,double z,bool normalization=true)
{
setXYZ(x,y,z,normalization);
}
NVector3(const Vector3 &u,bool normalization=true);
inline double x() const {return _n[0];}
inline double y() const {return _n[1];}
inline double z() const {return _n[2];}
void setXYZ(double x,double y,double z,bool normalization=true);
NVector3& operator=(const NVector3& u);
/*
inline friend bool operator==(const NVector3 &u,const Vector3 &v) {return u.isEqualTo(v);}
inline friend bool operator==(const Vector3 &u,const NVector3 &v) {return v.isEqualTo(u);}
inline friend bool operator==(const NVector3 &u,const NVector3 &v) {return u.isEqualTo(v);}
inline friend bool operator!=(const NVector3 &u,const Vector3 &v) {return !(u == v);}
inline friend bool operator!=(const Vector3 &u,const NVector3 &v) {return !(u == v);}
inline friend bool operator!=(const NVector3 &u,const NVector3 &v) {return !(u == v);}
*/
inline friend NVector3 operator-(const NVector3 &u) { return NVector3(-u[0],-u[1],-u[2],false); }
//inline friend Vector3 operator+(const NVector3 &u,const Vector3 &v);
//inline friend Vector3 operator+(const Vector3 &u,const NVector3 &v);
//inline friend Vector3 operator+(const NVector3 &u,const NVector3 &v);
//inline friend Vector3 operator-(const NVector3 &u,const Vector3 &v);
//inline friend Vector3 operator-(const Vector3 &u,const NVector3 &v);
//inline friend Vector3 operator-(const NVector3 &u,const NVector3 &v);
friend double operator*(const NVector3 &u,const Vector3 &v);
friend double operator*(const Vector3 &u,const NVector3 &v);
//inline friend double operator*(const NVector3 &u,const NVector3 &v);
//inline friend Vector3 operator*(double r,const NVector3 &u);
//inline friend Vector3 operator/(const NVector3 &u,double r);
//inline friend Vector3 operator^(const NVector3 &u,const Vector3 &v);
//inline friend Vector3 operator^(const Vector3 &u,const NVector3 &v);
//inline friend Vector3 operator^(const NVector3 &u,const NVector3 &v);
inline double norm() const {return 1.0;}
inline double squareNorm() const {return 1.0;}
friend std::ostream& operator<<(std::ostream &out,const NVector3 &u);
double operator[](int i) const
{
if((i < 0)||(i > 2))
throw std::runtime_error("Out of bounds in NVector3::operator[]") ;
return _n[i];
}
private:
void normalize();
double _n[3]; //!< normalized vector
}; // interface of NVector3
}
#endif // _NVECTOR3_H
| 4,665 | 37.561983 | 101 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Optimizer.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _OPTIMIZER_H
#define _OPTIMIZER_H
#include "Types.h"
namespace vrender
{
// Implements some global optimizations on the polygon sorting.
class VRenderParams ;
class Optimizer
{
public:
virtual void optimize(std::vector<PtrPrimitive>&,VRenderParams&) = 0 ;
virtual ~Optimizer() {} ;
};
// Optimizes visibility by culling primitives which do not appear in the
// rendered image. Computations are done analytically rather than using an item
// buffer.
class VisibilityOptimizer: public Optimizer
{
public:
virtual void optimize(std::vector<PtrPrimitive>&,VRenderParams&) ;
virtual ~VisibilityOptimizer() {} ;
};
// Optimizes by collapsing together primitives which can be, without
// perturbating the back to front painting algorithm.
class PrimitiveSplitOptimizer: public Optimizer
{
public:
virtual void optimize(std::vector<PtrPrimitive>&,VRenderParams&) {}
virtual ~PrimitiveSplitOptimizer() {} ;
};
class BackFaceCullingOptimizer: public Optimizer
{
public:
virtual void optimize(std::vector<PtrPrimitive>&,VRenderParams&) ;
virtual ~BackFaceCullingOptimizer() {} ;
};
}
#endif
| 2,989 | 31.5 | 80 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/ParserGL.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include "VRender.h"
#include "ParserGL.h"
using namespace vrender ;
using namespace std;
class ParserUtils
{
public:
static void NormalizeBufferCoordinates(GLint size, GLfloat * buffer, GLfloat MaxSize, GLfloat& zmin, GLfloat& zmax) ;
static PtrPrimitive checkPoint(Point *& P);
static PtrPrimitive checkSegment(Segment *& P);
static PtrPrimitive checkPolygon(Polygone *& P);
static void ComputeBufferBB(GLint size, GLfloat * buffer,
GLfloat & xmin, GLfloat & xmax,
GLfloat & ymin, GLfloat & ymax,
GLfloat & zmin, GLfloat & zmax) ;
private:
static void print3DcolorVertex(GLint size, GLint * count, GLfloat * buffer) ;
static void debug_printBuffer(GLint size, GLfloat *buffer) ;
static void NormalizePrimitiveCoordinates(GLfloat * & loc,GLfloat MaxSize,GLfloat zmin,GLfloat zmax) ;
static void ComputePrimitiveBB( GLfloat * & loc,
GLfloat & xmin,GLfloat & xmax,
GLfloat & ymin,GLfloat & ymax,
GLfloat & zmin,GLfloat & zmax);
static const char *nameOfToken(int token);
static const double EGALITY_EPS ;
};
const double ParserUtils::EGALITY_EPS = 0.00001 ;
void ParserGL::parseFeedbackBuffer( GLfloat *buffer,int size,
std::vector<PtrPrimitive>& primitive_tab,
VRenderParams& vparams)
{
int token;
int nvertices = 0 ;
nb_lines = 0 ;
nb_polys = 0 ;
nb_points = 0 ;
nb_degenerated_lines = 0 ;
nb_degenerated_polys = 0 ;
nb_degenerated_points = 0 ;
// pre-treatment of coordinates so as to get something more consistent
_xmin = FLT_MAX ;
_ymin = FLT_MAX ;
_zmin = FLT_MAX ;
_xmax = -FLT_MAX ;
_ymax = -FLT_MAX ;
_zmax = -FLT_MAX ;
ParserUtils::ComputeBufferBB(size, buffer, _xmin,_xmax,_ymin,_ymax,_zmin,_zmax) ;
#ifdef DEBUGEPSRENDER
printf("Buffer bounding box: %f %f %f %f %f %f\n",xmin,xmax,ymin,ymax,zmin,zmax) ;
#endif
float Zdepth = max(_ymax-_ymin,_xmax-_xmin) ;
ParserUtils::NormalizeBufferCoordinates(size,buffer,Zdepth,_zmin,_zmax) ;
// now, read buffer
GLfloat *end = buffer + size;
GLfloat *loc = buffer ;
int next_step = 0 ;
int N = size/200 + 1 ;
while (loc < end)
{
token = int(0.5f + *loc) ;
loc++;
if((end-loc)/N >= next_step)
vparams.progress((end-loc)/(float)size, QGLViewer::tr("Parsing feedback buffer.")), ++next_step ;
switch (token)
{
case GL_LINE_TOKEN:
case GL_LINE_RESET_TOKEN:
{
Segment *S = new Segment(Feedback3DColor(loc),Feedback3DColor(loc+Feedback3DColor::sizeInBuffer())) ;
primitive_tab.push_back(ParserUtils::checkSegment(S)) ;
if(S == NULL)
nb_degenerated_lines++ ;
nb_lines++ ;
loc += 2*Feedback3DColor::sizeInBuffer();
}
break;
case GL_POLYGON_TOKEN:
{
nvertices = int(0.5f + *loc) ;
loc++;
std::vector<Feedback3DColor> verts ;
for(int i=0;i<nvertices;++i)
verts.push_back(Feedback3DColor(loc)),loc+=Feedback3DColor::sizeInBuffer() ;
Polygone *P = new Polygone(verts) ;
primitive_tab.push_back(ParserUtils::checkPolygon(P)) ;
if(P == NULL)
nb_degenerated_polys++ ;
nb_polys++ ;
}
break ;
case GL_POINT_TOKEN:
{
Point *Pt = new Point(Feedback3DColor(loc)) ;
primitive_tab.push_back(Pt);//ParserUtils::checkPoint(Pt)) ;
if(Pt == NULL)
nb_degenerated_points++ ;
nb_points++ ;
loc += Feedback3DColor::sizeInBuffer();
}
break;
default:
break;
}
}
}
// Traitement des cas degeneres. Renvoie false si le polygone est degenere.
// Traitement des cas degeneres. Renvoie false si le segment est degenere.
PtrPrimitive ParserUtils::checkPoint(Point *& P)
{
return P ;
}
PtrPrimitive ParserUtils::checkSegment(Segment *& P)
{
if((P->vertex(0) - P->vertex(1)).infNorm() < EGALITY_EPS)
{
Point *pp = new Point(P->sommet3DColor(0)) ;
delete P ;
P = NULL ;
return checkPoint(pp) ;
}
return P ;
}
PtrPrimitive ParserUtils::checkPolygon(Polygone *& P)
{
if(P->nbVertices() != 3)
{
cout << "unexpected case: Polygon with " << P->nbVertices() << " vertices !" << endl ;
delete P ;
return NULL ;
}
if(P->FlatFactor() < FLAT_POLYGON_EPS)
{
// On ne traite que le cas du triangle plat, vu qu'on est sur d'avoir un triangle
size_t n = P->nbVertices() ;
for(size_t i=0;i<n;++i)
if( (P->vertex(i) - P->vertex((i+1)%n)).norm() > EGALITY_EPS)
{
Segment *pp = new Segment(P->sommet3DColor((i+1)%n),P->sommet3DColor((i+2)%n)) ;
delete P ;
P = NULL ;
return checkSegment(pp) ;
}
Point *pp = new Point(P->sommet3DColor(0)) ;
delete P ;
P = NULL ;
return checkPoint(pp) ;
}
// No problem detected.
return P ;
}
/* Write contents of one vertex to stdout. */
void ParserUtils::print3DcolorVertex(GLint size, GLint * count, GLfloat * buffer)
{
printf(" ");
for (size_t i = 0; i < Feedback3DColor::sizeInBuffer(); i++)
{
printf("%4.2f ", buffer[size - (*count)]);
*count = *count - 1;
}
printf("\n");
}
void ParserUtils::debug_printBuffer(GLint size, GLfloat * buffer)
{
GLint count;
int token, nvertices;
count = size;
while (count) {
token = int(buffer[size - count]);
count--;
switch (token)
{
case GL_PASS_THROUGH_TOKEN:
printf("GL_PASS_THROUGH_TOKEN\n");
printf(" %4.2f\n", buffer[size - count]);
count--;
break;
case GL_POINT_TOKEN:
printf("GL_POINT_TOKEN\n");
print3DcolorVertex(size, &count, buffer);
break;
case GL_LINE_TOKEN:
printf("GL_LINE_TOKEN\n");
print3DcolorVertex(size, &count, buffer);
print3DcolorVertex(size, &count, buffer);
break;
case GL_LINE_RESET_TOKEN:
printf("GL_LINE_RESET_TOKEN\n");
print3DcolorVertex(size, &count, buffer);
print3DcolorVertex(size, &count, buffer);
break;
case GL_POLYGON_TOKEN:
printf("GL_POLYGON_TOKEN\n");
nvertices = int(buffer[size - count]) ;
count--;
for (; nvertices > 0; nvertices--)
print3DcolorVertex(size, &count, buffer);
}
}
}
void ParserUtils::NormalizePrimitiveCoordinates(GLfloat * & loc,GLfloat MaxSize,GLfloat zmin,GLfloat zmax)
{
int token;
int nvertices, i;
token = int(*loc) ;
loc++;
int size = Feedback3DColor::sizeInBuffer() ;
switch (token)
{
case GL_LINE_RESET_TOKEN:
case GL_LINE_TOKEN:
{
for (i = 0; i < 2; i++)
(loc+size*i)[2] = ((loc+size*i)[2] - zmin)/(zmax-zmin)*MaxSize ;
loc += 2*size; /* Each vertex element in the feedback buffer is size GLfloats. */
break;
}
case GL_POLYGON_TOKEN:
{
nvertices = int(*loc) ;
loc++;
for (i = 0; i < nvertices; i++)
(loc+size*i)[2] = ((loc+size*i)[2] - zmin)/(zmax-zmin)*MaxSize ;
loc += nvertices * size; /* Each vertex element in the feedback buffer is size GLfloats. */
break;
}
case GL_POINT_TOKEN:
{
loc[2] = (loc[2] - zmin)/(zmax-zmin)*MaxSize ;
loc += size; /* Each vertex element in the feedback buffer is size GLfloats. */
break;
}
default:
/* XXX Left as an excersie to the reader. */
#ifdef DEBUGEPSRENDER
printf("%s (%d) not handled yet. Sorry.\n", ParserUtils::nameOfToken(token), token);
#endif
;
}
}
void ParserUtils::ComputePrimitiveBB(GLfloat * & loc,GLfloat & xmin,GLfloat & xmax,GLfloat & ymin,GLfloat & ymax, GLfloat & zmin,GLfloat & zmax)
{
int token;
int nvertices, i;
token = int(*loc) ;
loc++;
int size = Feedback3DColor::sizeInBuffer() ;
switch (token)
{
case GL_LINE_RESET_TOKEN:
case GL_LINE_TOKEN:
{
for (i = 0; i < 2; i++)
{
Feedback3DColor f(loc+size*i) ;
if(f.x() < xmin) xmin = GLfloat(f.x()) ;
if(f.y() < ymin) ymin = GLfloat(f.y()) ;
if(f.z() < zmin) zmin = GLfloat(f.z()) ;
if(f.x() > xmax) xmax = GLfloat(f.x()) ;
if(f.y() > ymax) ymax = GLfloat(f.y()) ;
if(f.z() > zmax) zmax = GLfloat(f.z()) ;
}
loc += 2*size; /* Each vertex element in the feedback
buffer is size GLfloats. */
break;
}
case GL_POLYGON_TOKEN:
{
nvertices = int(*loc) ;
loc++;
for (i = 0; i < nvertices; i++)
{
Feedback3DColor f(loc+size*i) ;
if(f.x() < xmin) xmin = GLfloat(f.x()) ;
if(f.y() < ymin) ymin = GLfloat(f.y()) ;
if(f.z() < zmin) zmin = GLfloat(f.z()) ;
if(f.x() > xmax) xmax = GLfloat(f.x()) ;
if(f.y() > ymax) ymax = GLfloat(f.y()) ;
if(f.z() > zmax) zmax = GLfloat(f.z()) ;
}
loc += nvertices * size; /* Each vertex element in the
feedback buffer is size GLfloats. */
break;
}
case GL_POINT_TOKEN:
{
Feedback3DColor f(loc) ;
if(f.x() < xmin) xmin = GLfloat(f.x()) ;
if(f.y() < ymin) ymin = GLfloat(f.y()) ;
if(f.z() < zmin) zmin = GLfloat(f.z()) ;
if(f.x() > xmax) xmax = GLfloat(f.x()) ;
if(f.y() > ymax) ymax = GLfloat(f.y()) ;
if(f.z() > zmax) zmax = GLfloat(f.z()) ;
loc += size; /* Each vertex element in the feedback
buffer is size GLfloats. */
break;
}
default:
/* XXX Left as an excersie to the reader. */
#ifdef DEBUGEPSRENDER
printf("Incomplete implementation. Unexpected token (%d).\n", token);
#endif
;
}
}
void ParserUtils::NormalizeBufferCoordinates(GLint size, GLfloat * buffer, GLfloat MaxSize, GLfloat& zmin,GLfloat& zmax)
{
GLfloat *loc, *end;
if(zmax == zmin)
{
#ifdef DEBUGEPSRENDER
printf("Warning: zmin = zmax in NormalizePrimitiveCoordinates\n") ;
#endif
return ;
}
loc = buffer;
end = buffer + size;
while (loc < end)
NormalizePrimitiveCoordinates(loc,MaxSize,zmin,zmax);
zmin = 0.0 ;
zmax = MaxSize ;
}
void ParserUtils::ComputeBufferBB(GLint size, GLfloat * buffer,
GLfloat & xmin, GLfloat & xmax,
GLfloat & ymin, GLfloat & ymax,
GLfloat & zmin, GLfloat & zmax)
{
GLfloat *loc, *end;
loc = buffer;
end = buffer + size;
while (loc < end)
ComputePrimitiveBB(loc,xmin,xmax,ymin,ymax,zmin,zmax);
}
typedef struct _DepthIndex {
GLfloat *ptr;
GLfloat depth;
} DepthIndex;
const char *ParserUtils::nameOfToken(int token)
{
switch(token)
{
case GL_PASS_THROUGH_TOKEN: return "GL_PASS_THROUGH_TOKEN" ;
case GL_POINT_TOKEN: return "GL_POINT_TOKEN" ;
case GL_LINE_TOKEN: return "GL_LINE_TOKEN" ;
case GL_POLYGON_TOKEN: return "GL_POLYGON_TOKEN" ;
case GL_BITMAP_TOKEN: return "GL_BITMAP_TOKEN" ;
case GL_DRAW_PIXEL_TOKEN: return "GL_DRAW_PIXEL_TOKEN" ;
case GL_COPY_PIXEL_TOKEN: return "GL_COPY_PIXEL_TOKEN" ;
case GL_LINE_RESET_TOKEN: return "GL_LINE_RESET_TOKEN" ;
default:
return "(Unidentified token)" ;
}
}
| 12,391 | 24.709544 | 144 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/ParserGL.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_PARSERGL_H
#define _VRENDER_PARSERGL_H
// This class implements the conversion from OpenGL feedback buffer into more
// usable data structures such as points, segments, and polygons (See Primitive.h)
#include <vector>
#include "Primitive.h"
namespace vrender
{
class ParserGL
{
public:
void parseFeedbackBuffer( GLfloat *,
int size,
std::vector<PtrPrimitive>& primitive_tab,
VRenderParams& vparams) ;
void printStats() const ;
inline GLfloat xmin() const { return _xmin ; }
inline GLfloat ymin() const { return _ymin ; }
inline GLfloat zmin() const { return _zmin ; }
inline GLfloat xmax() const { return _xmax ; }
inline GLfloat ymax() const { return _ymax ; }
inline GLfloat zmax() const { return _zmax ; }
private:
int nb_lines ;
int nb_polys ;
int nb_points ;
int nb_degenerated_lines ;
int nb_degenerated_polys ;
int nb_degenerated_points ;
GLfloat _xmin ;
GLfloat _ymin ;
GLfloat _zmin ;
GLfloat _xmax ;
GLfloat _ymax ;
GLfloat _zmax ;
};
}
#endif
| 2,920 | 31.820225 | 82 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Primitive.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <math.h>
#include <assert.h>
#include "Primitive.h"
#include "Types.h"
using namespace vrender ;
using namespace std ;
Point::Point(const Feedback3DColor& f)
: _position_and_color(f)
{
}
const Vector3& Point::vertex(size_t) const
{
return _position_and_color.pos() ;
}
const Feedback3DColor& Point::sommet3DColor(size_t) const
{
return _position_and_color ;
}
const Feedback3DColor& Segment::sommet3DColor(size_t i) const
{
return ( (i&1)==0 )?P1:P2 ;
}
AxisAlignedBox_xyz Point::bbox() const
{
return AxisAlignedBox_xyz(_position_and_color.pos(),_position_and_color.pos()) ;
}
const Vector3& Segment::vertex(size_t i) const
{
return ( (i&1)==0 )?P1.pos():P2.pos() ;
}
AxisAlignedBox_xyz Segment::bbox() const
{
AxisAlignedBox_xyz B(P1.pos());
B.include(P2.pos()) ;
return B ;
}
const Feedback3DColor& Polygone::sommet3DColor(size_t i) const
{
return _vertices[i % nbVertices()] ;
}
const Vector3& Polygone::vertex(size_t i) const
{
return _vertices[i % nbVertices()].pos() ;
}
Polygone::Polygone(const vector<Feedback3DColor>& fc)
: _vertices(fc)
{
initNormal() ;
for(size_t i=0;i<fc.size();i++)
_bbox.include(fc[i].pos()) ;
}
AxisAlignedBox_xyz Polygone::bbox() const
{
return _bbox ;
}
double Polygone::equation(const Vector3& v) const
{
return v * _normal - _c ;
}
void Polygone::initNormal()
{
FLOAT anglemax = 0.0 ;
Vector3 normalmax = Vector3(0.0,0.0,0.0) ;
FLOAT v12norm = (vertex(1)-vertex(0)).norm() ;
for(size_t i=0;i<nbVertices();i++)
{
Vector3 v1(vertex(i)) ;
Vector3 v2(vertex(i+1));
Vector3 v3(vertex(i+2)) ;
Vector3 normal_tmp((v3-v2)^(v1-v2)) ;
FLOAT v32norm = (v3-v2).norm() ;
if(normal_tmp.z() > 0)
normal_tmp *= -1.0 ;
if((v32norm > 0.0)&&(v12norm > 0.0))
{
double anglemaxtmp = normal_tmp.norm()/v32norm/v12norm ;
if(anglemaxtmp > anglemax)
{
anglemax = anglemaxtmp ;
normalmax = normal_tmp ;
}
}
v12norm = v32norm ;
if(anglemax > FLAT_POLYGON_EPS) // slight optimization
break ;
}
if(normalmax.infNorm() != 0.0)
_normal = NVector3(normalmax) ;
anglefactor = anglemax ;
_c = _normal*vertex(0) ;
}
std::ostream& vrender::operator<<(std::ostream& o,const Feedback3DColor& f)
{
o << "(" << f.pos() << ") + (" << f.red() << "," << f.green() << "," << f.blue() << "," << f.alpha() << ")" << endl ;
return o ;
}
| 4,192 | 23.377907 | 118 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Primitive.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _PRIMITIVE_H_
#define _PRIMITIVE_H_
#include <vector>
#include "AxisAlignedBox.h"
#include "Vector3.h"
#include "NVector3.h"
#include "Types.h"
#ifdef WIN32
# include <windows.h>
#endif
#ifdef __APPLE__
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif
namespace vrender
{
class Feedback3DColor ;
class Primitive ;
#define EPS_SMOOTH_LINE_FACTOR 0.06 /* Lower for better smooth lines. */
// A Feedback3DColor is a structure containing informations about a vertex projected into
// the frame buffer.
class Feedback3DColor
{
public:
Feedback3DColor(GLfloat *loc)
: _pos(loc[0],loc[1],loc[2]),
_red(loc[3]),_green(loc[4]),_blue(loc[5]),_alpha(loc[6]) {}
inline FLOAT x() const { return _pos[0] ; }
inline FLOAT y() const { return _pos[1] ; }
inline FLOAT z() const { return _pos[2] ; }
inline GLfloat red() const { return _red ; }
inline GLfloat green() const { return _green ; }
inline GLfloat blue() const { return _blue ; }
inline GLfloat alpha() const { return _alpha ; }
inline const Vector3& pos() const { return _pos ; }
inline Feedback3DColor operator+(const Feedback3DColor & v) const
{
return Feedback3DColor(x()+v.x(),y()+v.y(),z()+v.z(),red()+v.red(),green()+v.green(),blue()+v.blue(),alpha()+v.alpha()) ;
}
inline Feedback3DColor operator*(const GLFLOAT & f) const
{
return Feedback3DColor(x()*f,y()*f,z()*f,red()*GLfloat(f),green()*GLfloat(f),blue()*GLfloat(f),alpha()*GLfloat(f)) ;
}
friend inline Feedback3DColor operator*(const GLFLOAT & f,const Feedback3DColor& F)
{
return F*f ;
}
static size_t sizeInBuffer() { return 7 ; }
friend std::ostream& operator<<(std::ostream&,const Feedback3DColor&) ;
protected:
Feedback3DColor(FLOAT x, FLOAT y, FLOAT z, GLfloat r, GLfloat g, GLfloat b, GLfloat a)
:_pos(x,y,z), _red(r), _green(g), _blue(b), _alpha(a) {}
Vector3 _pos ;
GLfloat _red;
GLfloat _green;
GLfloat _blue;
GLfloat _alpha;
} ;
// A primitive is an entity
//
class Primitive
{
public:
virtual ~Primitive() {}
virtual const Feedback3DColor& sommet3DColor(size_t) const =0 ;
// Renvoie le ieme vertex modulo le nombre de vertex.
virtual const Vector3& vertex(size_t) const = 0 ;
#ifdef A_FAIRE
virtual FLOAT Get_I_EPS(Primitive *) const ;
Vect3 VerticalProjectPointOnSupportPlane(const Vector3 &) const ;
void IntersectPrimitiveWithSupportPlane(Primitive *,int[],FLOAT[],Vect3 *&,Vect3 *&) ;
inline FLOAT Equation(const Vect3& p) { return p*_normal-_C ; }
virtual void Split(Vect3,FLOAT,Primitive * &,Primitive * &) = 0 ;
void GetSigns(Primitive *,int * &,FLOAT * &,int &,int &,FLOAT) ;
FLOAT Const() const { return _C ; }
int depth() const { return _depth ; }
void setDepth(int d) const { _depth = d ; }
#endif
virtual AxisAlignedBox_xyz bbox() const = 0 ;
virtual size_t nbVertices() const = 0 ;
protected:
int _vibility ;
} ;
class Point: public Primitive
{
public:
Point(const Feedback3DColor& f);
virtual ~Point() {}
virtual const Vector3& vertex(size_t) const ;
virtual size_t nbVertices() const { return 1 ; }
virtual const Feedback3DColor& sommet3DColor(size_t) const ;
virtual AxisAlignedBox_xyz bbox() const ;
private:
Feedback3DColor _position_and_color ;
};
class Segment: public Primitive
{
public:
Segment(const Feedback3DColor & p1, const Feedback3DColor & p2): P1(p1), P2(p2) {}
virtual ~Segment() {}
virtual size_t nbVertices() const { return 2 ; }
virtual const Vector3& vertex(size_t) const ;
virtual const Feedback3DColor& sommet3DColor(size_t i) const ;
virtual AxisAlignedBox_xyz bbox() const ;
#ifdef A_FAIRE
virtual void Split(const Vector3&,FLOAT,Primitive * &,Primitive * &) ;
#endif
protected:
Feedback3DColor P1 ;
Feedback3DColor P2 ;
} ;
class Polygone: public Primitive
{
public:
Polygone(const std::vector<Feedback3DColor>&) ;
virtual ~Polygone() {}
#ifdef A_FAIRE
virtual int IsAPolygon() { return 1 ; }
virtual void Split(const Vector3&,FLOAT,Primitive * &,Primitive * &) ;
void InitEquation(double &,double &,double &,double &) ;
#endif
virtual const Feedback3DColor& sommet3DColor(size_t) const ;
virtual const Vector3& vertex(size_t) const ;
virtual size_t nbVertices() const { return _vertices.size() ; }
virtual AxisAlignedBox_xyz bbox() const ;
double equation(const Vector3& p) const ;
const NVector3& normal() const { return _normal ; }
double c() const { return _c ; }
FLOAT FlatFactor() const { return anglefactor ; }
protected:
virtual void initNormal() ;
void CheckInfoForPositionOperators() ;
AxisAlignedBox_xyz _bbox ;
std::vector<Feedback3DColor> _vertices ;
// std::vector<FLOAT> _sommetsProjetes ;
// Vector3 N,M,L ;
double anglefactor ; // Determine a quel point un polygone est plat.
// Comparer a FLAT_POLYGON_EPS
double _c ;
NVector3 _normal ;
} ;
}
#endif
| 6,735 | 29.618182 | 124 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/PrimitivePositioning.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "Primitive.h"
#include "AxisAlignedBox.h"
#include "PrimitivePositioning.h"
#include "math.h"
#include <algorithm>
#include "Vector2.h"
#include <algorithm>
using namespace vrender ;
using namespace std ;
#define DEBUG_TS
double PrimitivePositioning::_EPS = 0.00001 ;
// Computes relative position of the second primitive toward the first.
// As a general rule, the smaller the Z of a primitive, the Upper the primitive.
int PrimitivePositioning::computeRelativePosition(const Primitive *p1,const Primitive *p2)
{
AxisAlignedBox_xyz bb1(p1->bbox()) ;
AxisAlignedBox_xyz bb2(p2->bbox()) ;
// 1 - check if bounding boxes are disjoint. In such a case, a rapid answer is possible.
if( bb1.maxi().x() < bb2.mini().x() || bb1.mini().x() > bb2.maxi().x()) return Independent ;
if( bb1.maxi().y() < bb2.mini().y() || bb1.mini().y() > bb2.maxi().y()) return Independent ;
// 2 - call specific tests for each case.
if(p1->nbVertices() >= 3)
if(p2->nbVertices() >= 3)
return computeRelativePosition( dynamic_cast<const Polygone *>(p1),dynamic_cast<const Polygone *>(p2)) ;
else if(p2->nbVertices() == 2) // Case of a segment versus a polygon
return computeRelativePosition( dynamic_cast<const Polygone *>(p1),dynamic_cast<const Segment *>(p2)) ;
else
return computeRelativePosition( dynamic_cast<const Polygone *>(p1),dynamic_cast<const Point *>(p2)) ;
else if(p1->nbVertices() == 2)
if(p2->nbVertices() >= 3)
return inverseRP(computeRelativePosition( dynamic_cast<const Polygone *>(p2),dynamic_cast<const Segment *>(p1))) ;
else if(p2->nbVertices() == 2)
return computeRelativePosition( dynamic_cast<const Segment *>(p1),dynamic_cast<const Segment *>(p2)) ;
else
return Independent ; // segment vs point => independent
else
if(p2->nbVertices() >= 3)
return inverseRP(computeRelativePosition( dynamic_cast<const Polygone *>(p2),dynamic_cast<const Point *>(p1))) ;
else if(p2->nbVertices() == 2)
return Independent ; // point vs segment => independent
else
return Independent ; // point vs point => independent
}
// Computes the relative position of the point toward a *convex* polygon.
int PrimitivePositioning::computeRelativePosition(const Polygone *Q,const Point *P)
{
if(pointOutOfPolygon_XY(P->vertex(0),Q,(double)_EPS)) // On met un eps > 0, pour que les
return Independent ; // points du bords soient inclus dans le polygone.
// now compute the relative position of the point toward the polygon
if(Q->equation(P->vertex(0)) >= 0)
return Upper ;
else
return Lower ;
}
// Computes the relative position of the segment toward a *convex* polygon.
int PrimitivePositioning::computeRelativePosition(const Polygone *P,const Segment *S)
{
// Computes the intersection of the segment and the polygon in 2D, then
// project the extremities of the intersection onto the segment, and compare
// the points to the polygon.
// 1 - 2D-intersection of segment and polygon
vector<double> intersections ;
if(!pointOutOfPolygon_XY(S->vertex(0),P,_EPS)) intersections.push_back(0.0);
if(!pointOutOfPolygon_XY(S->vertex(1),P,_EPS)) intersections.push_back(1.0);
double t1,t2 ;
for(size_t i=0;i<P->nbVertices();++i)
if(intersectSegments_XY(Vector2(S->vertex(0)),Vector2(S->vertex(1)),Vector2(P->vertex(i)),Vector2(P->vertex(i+1)),_EPS,t1,t2))
intersections.push_back(t1) ;
// 2 - Checks wether the intersection segment is reduced to a point. In this case,
// both primitives are independent.
double tmin = FLT_MAX ;
double tmax = -FLT_MAX ;
for(unsigned int j=0;j<intersections.size();++j)
{
tmin = std::min(tmin,intersections[j]) ;
tmax = std::max(tmax,intersections[j]) ;
}
if(tmax - tmin < 2*_EPS)
return Independent ;
// 3 - The intersection segment is not reduced to a point. Compares 3D
// projections of the intersections with the plane of the polygon.
int res = Independent ;
for(unsigned int k=0;k<intersections.size();++k)
{
Vector3 v( (1-intersections[k])*S->vertex(0) + intersections[k]*S->vertex(1) ) ;
if(P->equation(v) < -_EPS) res |= Lower ;
if(P->equation(v) > _EPS) res |= Upper ;
}
if(intersections.size() > 1 && res == Independent) // case of segments tangent to the polygon
res = Upper ;
return res ;
}
// Computes the relative position of a polygon toward a convex polygon.
int PrimitivePositioning::computeRelativePosition(const Polygone *P1,const Polygone *P2)
{
// 1 - use gpc to conservatively check for intersection. This works fine because
// gpc produces a null intersection for polygons sharing an edge, which
// is exactly what we need.
gpc_polygon gpc_int ;
try
{
gpc_polygon gpc_p1 = createGPCPolygon_XY(P1) ;
gpc_polygon gpc_p2 = createGPCPolygon_XY(P2) ;
gpc_polygon_clip(GPC_INT,&gpc_p1,&gpc_p2,&gpc_int) ;
gpc_free_polygon(&gpc_p1) ;
gpc_free_polygon(&gpc_p2) ;
}
catch(exception&)
{
return Independent ; // no free, because we don't really now what happenned.
}
int res = Independent ;
if (gpc_int.num_contours != 1) // There is some numerical error in gpc. Let's skip.
{
gpc_free_polygon(&gpc_int) ;
return res ;
// throw runtime_error("Intersection with more than 1 contour ! Non convex polygons ?") ;
}
// 2 - polygons are not independent. Compute their relative position.
// For this, we project the vertices of the 2D intersection onto the
// support plane of each polygon. The epsilon-signs of each point toward
// both planes give the relative position of the polygons.
for(long i=0;i<gpc_int.contour[0].num_vertices && (res < (Upper | Lower));++i)
{
if(P1->normal().z() == 0.0) throw runtime_error("could not project point. Unexpected case !") ;
if(P2->normal().z() == 0.0) throw runtime_error("could not project point. Unexpected case !") ;
// project point onto support planes
double f1 = P1->normal().x() * gpc_int.contour[0].vertex[i].x + P1->normal().y() * gpc_int.contour[0].vertex[i].y - P1->c() ;
double f2 = P2->normal().x() * gpc_int.contour[0].vertex[i].x + P2->normal().y() * gpc_int.contour[0].vertex[i].y - P2->c() ;
Vector3 v1(gpc_int.contour[0].vertex[i].x,gpc_int.contour[0].vertex[i].y, -f1/P1->normal().z()) ;
Vector3 v2(gpc_int.contour[0].vertex[i].x,gpc_int.contour[0].vertex[i].y, -f2/P2->normal().z()) ;
if(P1->equation(v2) < -_EPS) res |= Lower ;
if(P1->equation(v2) > _EPS) res |= Upper ;
if(P2->equation(v1) < -_EPS) res |= Upper ;
if(P2->equation(v1) > _EPS) res |= Lower ;
}
gpc_free_polygon(&gpc_int) ;
return res ;
}
// Computes the relative position of a segment toward another segment.
int PrimitivePositioning::computeRelativePosition(const Segment *S1,const Segment *S2)
{
double t1,t2 ;
if(!intersectSegments_XY( Vector2(S1->vertex(0)),Vector2(S1->vertex(1)),
Vector2(S2->vertex(0)),Vector2(S2->vertex(1)),
-(double)_EPS,t1,t2 ))
return Independent ;
else
{
double z1 = (1.0 - t1)*S1->vertex(0).z() + t1*S1->vertex(1).z() ;
double z2 = (1.0 - t2)*S2->vertex(0).z() + t2*S2->vertex(1).z() ;
if(z1 <= z2)
return Lower ;
else
return Upper ;
}
}
// Teste si le point est exterieur au polygone (convexe). Plus I_EPS est grand
// plus il faut etre loin pour que ca soit vrai. EPS=0 correspond au polygone
// lui-meme bords inclus. Pour EPS<0, des points interieurs pres de la frontiere sont
// declares exterieurs. Plus I_EPS est grand, plus l'ensemble des points
// consideres comme interieur est dilate.
bool PrimitivePositioning::pointOutOfPolygon_XY(const Vector3& P,const Polygone *Q,double I_EPS)
{
size_t nq = Q->nbVertices() ;
Vector2 p = Vector2(P) ;
FLOAT MaxZ = -FLT_MAX ;
FLOAT MinZ = FLT_MAX ;
for(size_t j=0;j<nq;j++) // Regarde si P.(x,y) est a l'interieur
{ // ou a l'exterieur du polygone.
Vector2 q1 = Vector2(Q->vertex(j)) ;
Vector2 q2 = Vector2(Q->vertex(j+1)) ;
double Z = (q1-p)^(q2-p) ;
MinZ = std::min(Z,MinZ) ;
MaxZ = std::max(Z,MaxZ) ;
}
if((MaxZ <= -I_EPS*I_EPS)||(MinZ >= I_EPS*I_EPS)) // the point is inside the polygon
return false ;
else
return true ;
}
int PrimitivePositioning::inverseRP(int pos)
{
// Basically switch bits of Lower and Upper
switch(pos)
{
case Independent: return Independent ;
case Lower: return Upper ;
case Upper: return Lower ;
case Upper | Lower: return Upper | Lower ;
default:
throw runtime_error("Unexpected value.") ;
return pos ;
}
}
// Calcule l'intersection des segments [P1,Q1] et [P2,Q2]
// En retour, (1-t1,t1) et (1-t2,t2) sont les coordonnees
// barycentriques de l'intersection dans chaque segment.
bool PrimitivePositioning::intersectSegments_XY(const Vector2& P1,const Vector2& Q1,
const Vector2& P2,const Vector2& Q2,
double I_EPS,
double & t1,double & t2)
{
double P1x(P1.x()) ;
double P1y(P1.y()) ;
double P2x(P2.x()) ;
double P2y(P2.y()) ;
double Q1x(Q1.x()) ;
double Q1y(Q1.y()) ;
double Q2x(Q2.x()) ;
double Q2y(Q2.y()) ;
double a2 = -(Q2y - P2y) ;
double b2 = (Q2x - P2x) ;
double c2 = P2x*a2+P2y*b2 ;
double a1 = -(Q1y - P1y) ;
double b1 = (Q1x - P1x) ;
double c1 = P1x*a1+P1y*b1 ;
double d2 = a2*(Q1x-P1x)+b2*(Q1y-P1y) ;
double d1 = a1*(Q2x-P2x)+b1*(Q2y-P2y) ;
if((fabs(d2) <= fabs(I_EPS))||(fabs(d1) <= fabs(I_EPS))) // les segments sont paralleles
{
if(fabs(a2*P1x + b2*P1y - c2) >= I_EPS)
return false ;
double tP1,tQ1 ;
if(P1x != Q1x)
{
tP1 = (P2x-P1x)/(Q1x-P1x) ;
tQ1 = (Q2x-P1x)/(Q1x-P1x) ;
}
else if(P1y != Q1y)
{
tP1 = (P2y-P1y)/(Q1y-P1y) ;
tQ1 = (Q2y-P1y)/(Q1y-P1y) ;
}
else
{
#ifdef DEBUG_TS
printf("IntersectSegments2D:: Error ! One segment has length 0\n") ;
printf("This special case is not treated yet.\n") ;
#endif
return false ;
}
double tPQM = std::max(tP1,tQ1) ;
double tPQm = std::min(tP1,tQ1) ;
if(( tPQM < -I_EPS) || (tPQm > 1.0+I_EPS))
return false ;
if(tPQm > 0.0)
{
t1 = tPQm ;
t2 = 0.0 ;
}
else
{
t1 = 0.0 ;
if(P2x != Q2x)
t2 = (P1x-P2x)/(Q2x-P2x) ;
else if(P2y != Q2y)
t2 = (P1y-P2y)/(Q2y-P2y) ;
else
{
#ifdef DEBUG_TS
printf("IntersectSegments2D:: Error ! One segment has length 0\n") ;
printf("This special case is not treated yet.\n") ;
#endif
return false ;
}
}
return true ;
}
else
{
t2 = (c1 - a1*P2x - b1*P2y)/d1 ;
t1 = (c2 - a2*P1x - b2*P1y)/d2 ;
if((t2 > 1+I_EPS)||(t2 < -I_EPS)||(t1 > 1+I_EPS)||(t1 < -I_EPS))
return false ;
return true ;
}
}
gpc_polygon PrimitivePositioning::createGPCPolygon_XY(const Polygone *P)
{
gpc_polygon p ;
p.num_contours = 0 ;
p.hole = NULL ;
p.contour = NULL ;
gpc_vertex_list *gpc_p_verts = new gpc_vertex_list ;
gpc_p_verts->num_vertices = P->nbVertices() ;
gpc_p_verts->vertex = new gpc_vertex[P->nbVertices()] ;
for(size_t i=0;i<P->nbVertices();++i)
{
gpc_p_verts->vertex[i].x = P->vertex(i).x() ;
gpc_p_verts->vertex[i].y = P->vertex(i).y() ;
}
gpc_add_contour(&p,gpc_p_verts,false) ;
return p ;
}
void PrimitivePositioning::getsigns(const Primitive *P,const NVector3& v,double C,
vector<int>& signs,vector<double>& zvals,int& Smin,int& Smax,double I_EPS)
{
if(P == NULL)
throw runtime_error("Null primitive in getsigns !") ;
size_t n = P->nbVertices() ;
Smin = 1 ;
Smax = -1 ;
// On classe les sommets en fonction de leur signe
double zmax = -FLT_MAX ;
double zmin = FLT_MAX ;
zvals.resize(n) ;
for(size_t i=0;i<n;i++)
{
double Z = P->vertex(i) * v - C ;
if(Z > zmax) zmax = Z ;
if(Z < zmin) zmin = Z ;
zvals[i] = Z ;
}
signs.resize(n) ;
for(size_t j=0;j<n;j++)
{
if(zvals[j] < -I_EPS)
signs[j] = -1 ;
else if(zvals[j] > I_EPS)
signs[j] = 1 ;
else
signs[j] = 0 ;
if(Smin > signs[j]) Smin = signs[j] ;
if(Smax < signs[j]) Smax = signs[j] ;
}
}
void PrimitivePositioning::split(Polygone *P,const NVector3& v,double C,Primitive *& P_plus,Primitive *& P_moins)
{
vector<int> Signs ;
vector<double> Zvals ;
P_plus = NULL ;
P_moins = NULL ;
int Smin = 1 ;
int Smax = -1 ;
getsigns(P,v,C,Signs,Zvals,Smin,Smax,_EPS) ;
size_t n = P->nbVertices() ;
if((Smin == 0)&&(Smax == 0)){ P_moins = P ; P_plus = NULL ; return ; } // Polygone inclus dans le plan
if(Smin == 1) { P_plus = P ; P_moins = NULL ; return ; } // Polygone tout positif
if(Smax == -1) { P_plus = NULL ; P_moins = P ; return ; } // Polygone tout negatif
if((Smin == -1)&&(Smax == 0)) { P_plus = NULL ; P_moins = P ; return ; } // Polygone tout negatif ou null
if((Smin == 0)&&(Smax == 1)) { P_plus = P ; P_moins = NULL ; return ; } // Polygone tout positif ou null
// Reste le cas Smin = -1 et Smax = 1. Il faut couper
vector<Feedback3DColor> Ps ;
vector<Feedback3DColor> Ms ;
// On teste la coherence des signes.
int nZero = 0 ;
int nconsZero = 0 ;
for(size_t i=0;i<n;i++)
{
if(Signs[i] == 0)
{
nZero++ ;
if(Signs[(i+1)%n] == 0)
nconsZero++ ;
}
}
// Ils y a des imprecisions numeriques dues au fait que le poly estpres du plan.
if((nZero > 2)||(nconsZero > 0)) { P_moins = P ; P_plus = NULL ; return ; }
int dep=0 ; while(Signs[dep] == 0) dep++ ;
int prev_sign = Signs[dep] ;
for(size_t j=1;j<=n;j++)
{
int sign = Signs[(j+dep)%n] ;
if(sign == prev_sign)
{
if(sign == 1) Ps.push_back(P->sommet3DColor(j+dep)) ;
if(sign == -1) Ms.push_back(P->sommet3DColor(j+dep)) ;
}
else if(sign == -prev_sign)
{
// Il faut effectuer le calcul en utilisant les memes valeurs que pour le calcul des signes,
// sinon on risque des incoherences dues aux imprecisions numeriques.
double Z1 = Zvals[(j+dep-1)%n] ;
double Z2 = Zvals[(j+dep)%n] ;
double t = fabs(Z1/(Z2 - Z1)) ;
if((t < 0.0)||(t > 1.0))
{
if(t > 1.0) t = 1.0 ;
if(t < 0.0) t = 0.0 ;
}
Feedback3DColor newVertex((1-t)*P->sommet3DColor(j+dep-1) + t*P->sommet3DColor(j+dep)) ;
Ps.push_back(newVertex) ;
Ms.push_back(newVertex) ;
if(sign == 1)
Ps.push_back(P->sommet3DColor(j+dep)) ;
if(sign == -1)
Ms.push_back(P->sommet3DColor(j+dep)) ;
prev_sign = sign ;
} // prev_sign != 0 donc necessairement sign = 0. Le sommet tombe dans le plan
else
{
Feedback3DColor newVertex = P->sommet3DColor(j+dep) ;
Ps.push_back(newVertex) ;
Ms.push_back(newVertex) ;
prev_sign = -prev_sign ;
}
}
if(Ps.size() > 100 || Ms.size() > 100 )
printf("Primitive::split: Error. nPs = %d, nMs = %d.\n",int(Ps.size()),int(Ms.size())) ;
// on suppose pour l'instant que les polygones sont convexes
if(Ps.size() == 1)
P_plus = new Point(Ps[0]) ;
else if(Ps.size() == 2)
P_plus = new Segment(Ps[0],Ps[1]) ;
else
P_plus = new Polygone(Ps) ;
if(Ms.size() == 1)
P_moins = new Point(Ms[0]) ;
else if(Ms.size() == 2)
P_moins = new Segment(Ms[0],Ms[1]) ;
else
P_moins = new Polygone(Ms) ;
}
void PrimitivePositioning::split(Point *P,const NVector3& v,double C,Primitive * & P_plus,Primitive * & P_moins)
{
if(v*P->vertex(0)-C > -_EPS)
{
P_plus = P ;
P_moins = NULL ;
}
else
{
P_moins = P ;
P_plus = NULL ;
}
}
void PrimitivePositioning::split(Segment *S,const NVector3& v,double C,Primitive * & P_plus,Primitive * & P_moins)
{
vector<int> Signs ;
vector<double> Zvals ;
P_plus = NULL ;
P_moins = NULL ;
int Smin = 1 ;
int Smax = -1 ;
getsigns(S,v,C,Signs,Zvals,Smin,Smax,_EPS) ;
size_t n = S->nbVertices() ;
if((Smin == 0)&&(Smax == 0)) { P_moins = S ; P_plus = NULL ; return ; } // Polygone inclus dans le plan
if(Smin == 1) { P_plus = S ; P_moins = NULL ; return ; } // Polygone tout positif
if(Smax == -1) { P_plus = NULL ; P_moins = S ; return ; } // Polygone tout negatif
if((Smin == -1)&&(Smax == 0)) { P_plus = NULL ; P_moins = S ; return ; } // Polygone tout negatif ou null
if((Smin == 0)&&(Smax == 1)) { P_plus = S ; P_moins = NULL ; return ; } // Polygone tout positif ou null
// Reste le cas Smin = -1 et Smax = 1. Il faut couper
// On teste la coherence des signes.
int nZero = 0 ;
int nconsZero = 0 ;
for(size_t i=0;i<n;i++)
{
if(Signs[i] == 0)
{
nZero++ ;
if(Signs[(i+1)%n] == 0)
nconsZero++ ;
}
}
// Ils y a des imprecisions numeriques dues au fait que le poly estpres du plan.
if((nZero > 2)||(nconsZero > 0)) { P_moins = S ; P_plus = NULL ; return ; }
double Z1 = Zvals[0] ;
double Z2 = Zvals[1] ;
double t = fabs(Z1/(Z2 - Z1)) ;
if((t < 0.0)||(t > 1.0))
{
if(t > 1.0) t = 1.0 ;
if(t < 0.0) t = 0.0 ;
}
Feedback3DColor newVertex = S->sommet3DColor(0) * (1-t) + S->sommet3DColor(1) * t ;
if(Signs[0] < 0)
{
P_plus = new Segment(newVertex,S->sommet3DColor(1)) ;
P_moins = new Segment(S->sommet3DColor(0),newVertex) ;
}
else
{
P_plus = new Segment(S->sommet3DColor(0),newVertex) ;
P_moins = new Segment(newVertex,S->sommet3DColor(1)) ;
}
}
// splits primitive P by plane of equation v.X=c. The upper part is setup in a new primitive called prim_up and
// the lower part is in prim_lo.
void PrimitivePositioning::splitPrimitive(Primitive *P,const NVector3& v,double c, Primitive *& prim_up,Primitive *& prim_lo)
{
Polygone *p1 = dynamic_cast<Polygone *>(P) ; if(p1 != NULL) PrimitivePositioning::split(p1,v,c,prim_up,prim_lo) ;
Segment *p2 = dynamic_cast<Segment *>(P) ; if(p2 != NULL) PrimitivePositioning::split(p2,v,c,prim_up,prim_lo) ;
Point *p3 = dynamic_cast<Point *>(P) ; if(p3 != NULL) PrimitivePositioning::split(p3,v,c,prim_up,prim_lo) ;
}
| 19,309 | 27.735119 | 128 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/PrimitivePositioning.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _PRIMITIVEPOSITIONING_H
#define _PRIMITIVEPOSITIONING_H
#include <vector>
#include "gpc.h"
namespace vrender
{
class Primitive ;
// This class implements a static method for positioning two primitives relative to each other.
class PrimitivePositioning
{
public:
typedef enum { Independent = 0x0,
Upper = 0x1,
Lower = 0x2 } RelativePosition ;
static int computeRelativePosition(const Primitive *p1,const Primitive *p2) ;
static void splitPrimitive(Primitive *P,const NVector3& v,double c,Primitive *& prim_up,Primitive *& prim_lo) ;
static void split(Segment *S, const NVector3& v,double C,Primitive * & P_plus,Primitive * & P_moins) ;
static void split(Point *P, const NVector3& v,double C,Primitive * & P_plus,Primitive * & P_moins) ;
static void split(Polygone *P,const NVector3& v,double C,Primitive * & P_plus,Primitive * & P_moins) ;
private:
static void getsigns(const Primitive *P,const NVector3& v,
double C,std::vector<int>& signs,std::vector<double>& zvals,
int& Smin,int& Smax,double I_EPS) ;
static int computeRelativePosition(const Polygone *p1,const Polygone *p2) ;
static int computeRelativePosition(const Polygone *p1,const Segment *p2) ;
static int computeRelativePosition(const Polygone *p1,const Point *p2) ;
static int computeRelativePosition(const Segment *p1,const Segment *p2) ;
// 2D intersection/positioning methods. Parameter I_EPS may be positive of negative
// depending on the wanted degree of conservativeness of the result.
static bool pointOutOfPolygon_XY(const Vector3& P,const Polygone *Q,double I_EPS) ;
static bool intersectSegments_XY(const Vector2& P1,const Vector2& Q1,
const Vector2& P2,const Vector2& Q2,
double I_EPS,double & t1,double & t2) ;
static gpc_polygon createGPCPolygon_XY(const Polygone *P) ;
static int inverseRP(int) ;
// This value is *non negative*. It may be used with a negative sign
// in 2D methods such as pointOutOfPolygon() so as to rule the behaviour of
// the positionning.
static double _EPS ;
};
}
#endif
| 3,993 | 37.776699 | 114 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/SortMethod.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _SORTMETHOD_H
#define _SORTMETHOD_H
#include <vector>
#include "Types.h"
namespace vrender
{
// Class which implements the sorting of the primitives. An object of
class VRenderParams ;
class SortMethod
{
public:
SortMethod() {}
virtual ~SortMethod() {}
virtual void sortPrimitives(std::vector<PtrPrimitive>&,VRenderParams&) = 0 ;
void SetZDepth(FLOAT s) { zSize = s ; }
FLOAT ZDepth() const { return zSize ; }
protected:
FLOAT zSize ;
};
class DontSortMethod: public SortMethod
{
public:
DontSortMethod() {}
virtual ~DontSortMethod() {}
virtual void sortPrimitives(std::vector<PtrPrimitive>&,VRenderParams&) {}
};
class BSPSortMethod: public SortMethod
{
public:
BSPSortMethod() {} ;
virtual ~BSPSortMethod() {}
virtual void sortPrimitives(std::vector<PtrPrimitive>&,VRenderParams&) ;
};
class TopologicalSortMethod: public SortMethod
{
public:
TopologicalSortMethod() ;
virtual ~TopologicalSortMethod() {}
virtual void sortPrimitives(std::vector<PtrPrimitive>&,VRenderParams&) ;
void setBreakCycles(bool b) { _break_cycles = b ; }
private:
bool _break_cycles ;
};
}
#endif
| 3,011 | 28.242718 | 79 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/TopologicalSortMethod.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <assert.h>
#include <climits>
#include "VRender.h"
#include "Primitive.h"
#include "PrimitivePositioning.h"
#include "AxisAlignedBox.h"
#include "SortMethod.h"
#include "Vector2.h"
using namespace std ;
using namespace vrender ;
// #define DEBUG_TS
namespace vrender
{
class TopologicalSortUtils
{
public:
static void buildPrecedenceGraph(vector<PtrPrimitive>& primitive_tab, vector< vector<size_t> >& precedence_graph) ;
static void recursFindNeighbors( const vector<PtrPrimitive>& primitive_tab,
const vector<size_t>& pindices,
vector< vector<size_t> >& precedence_graph,
const AxisAlignedBox_xy&,int) ;
static void checkAndAddEdgeToGraph(size_t a,size_t b,vector< vector<size_t> >& precedence_graph) ;
static void suppressPrecedence(size_t a,size_t b,vector< vector<size_t> >& precedence_graph) ;
static void recursTopologicalSort(vector< vector<size_t> >& precedence_graph,
vector<PtrPrimitive>& primitive_tab,
vector<bool>& alread_rendered,
vector<bool>& alread_visited,
vector<PtrPrimitive>&,size_t,size_t&,
VRenderParams& vparams,
size_t info_cnt,size_t& nbrendered) ;
static void recursTopologicalSort(vector< vector<size_t> >& precedence_graph,
vector<PtrPrimitive>& primitive_tab,
vector<bool>& alread_rendered,
vector<bool>& alread_visited,
vector<PtrPrimitive>&,size_t,
vector<size_t>& ancestors,
size_t&, size_t&,
VRenderParams& vparams,
size_t info_cnt,size_t& nbrendered) ;
static void topologicalSort( vector< vector<size_t> >& precedence_graph,
vector<PtrPrimitive>& primitive_tab,
VRenderParams&) ;
static void topologicalSortBreakCycles(vector< vector<size_t> >& precedence_graph,
vector<PtrPrimitive>& primitive_tab,
VRenderParams&) ;
#ifdef DEBUG_TS
static void printPrecedenceGraph(const vector< vector<size_t> >& precedence_graph,
const vector<PtrPrimitive>& primitive_tab) ;
#endif
};
TopologicalSortMethod::TopologicalSortMethod()
{
_break_cycles = false ;
}
void TopologicalSortMethod::sortPrimitives(vector<PtrPrimitive>& primitive_tab,VRenderParams& vparams)
{
// 1 - build a precedence graph
#ifdef DEBUG_TS
cout << "Computing precedence graph." << endl ;
cout << "Old order: " ;
for(size_t i=0;i<primitive_tab.size();++i) cout << (void *)(primitive_tab[i]) << " " ;
cout << endl ;
#endif
vector< vector<size_t> > precedence_graph(primitive_tab.size());
TopologicalSortUtils::buildPrecedenceGraph(primitive_tab,precedence_graph) ;
#ifdef DEBUG_TS
TopologicalSortUtils::printPrecedenceGraph(precedence_graph,primitive_tab) ;
#endif
// 2 - perform a topological sorting of the graph
#ifdef DEBUG_TS
cout << "Sorting." << endl ;
#endif
if(_break_cycles)
TopologicalSortUtils::topologicalSortBreakCycles(precedence_graph, primitive_tab,vparams) ;
else
TopologicalSortUtils::topologicalSort(precedence_graph, primitive_tab,vparams) ;
#ifdef DEBUG_TS
cout << "New order: " ;
for(size_t i=0;i<primitive_tab.size();++i) cout << (void *)(primitive_tab[i]) << " " ;
cout << endl ;
#endif
}
#ifdef DEBUG_TS
void TopologicalSortUtils::printPrecedenceGraph(const vector< vector<size_t> >& precedence_graph,
const vector<PtrPrimitive>& primitive_tab)
{
for(size_t i=0;i<precedence_graph.size();++i)
{
cout << i << " (" << primitive_tab[i]->nbVertices() << ") : " ;
for(size_t j=0;j<precedence_graph[i].size();++j)
cout << precedence_graph[i][j] << " " ;
cout << endl ;
}
}
#endif
void TopologicalSortUtils::buildPrecedenceGraph(vector<PtrPrimitive>& primitive_tab,
vector< vector<size_t> >& precedence_graph)
{
// The precedence graph is constructed by first conservatively determining which
// primitives can possibly intersect using a quadtree. Candidate pairs of
// primitives are then carefully checked to compute their exact relative positionning.
//
// Because of the conservativeness of the quadtree, some pairs of primitives may be checked
// multiple times for intersection. Using a buffer of already computed results may proove
// very efficient.
// 0 - compute bounding box of the set of primitives.
AxisAlignedBox_xy BBox ;
for(size_t i=0;i<primitive_tab.size();++i)
{
BBox.include(Vector2(primitive_tab[i]->bbox().mini().x(),primitive_tab[i]->bbox().mini().y())) ;
BBox.include(Vector2(primitive_tab[i]->bbox().maxi().x(),primitive_tab[i]->bbox().maxi().y())) ;
}
// 1 - recursively find pairs.
vector<size_t> pindices(primitive_tab.size()) ;
for(size_t j=0;j<pindices.size();++j)
pindices[j] = j ;
recursFindNeighbors(primitive_tab, pindices, precedence_graph, BBox,0) ;
}
void TopologicalSortUtils::recursFindNeighbors(const vector<PtrPrimitive>& primitive_tab,
const vector<size_t>& pindices,
vector< vector<size_t> >& precedence_graph,
const AxisAlignedBox_xy& bbox,
int depth)
{
static const size_t MAX_PRIMITIVES_IN_CELL = 5 ;
// Refinment: first decide which sub-cell each primitive meets, then call
// algorithm recursively.
if(primitive_tab.size() > MAX_PRIMITIVES_IN_CELL)
{
vector<size_t> p_indices_min_min ;
vector<size_t> p_indices_min_max ;
vector<size_t> p_indices_max_min ;
vector<size_t> p_indices_max_max ;
double xmin = bbox.mini().x() ;
double ymin = bbox.mini().y() ;
double xmax = bbox.maxi().x() ;
double ymax = bbox.maxi().y() ;
double xMean = 0.5*(xmin+xmax) ;
double yMean = 0.5*(ymin+ymax) ;
for(size_t i=0;i<pindices.size();++i)
{
bool left = primitive_tab[pindices[i]]->bbox().mini().x() <= xMean ;
bool right = primitive_tab[pindices[i]]->bbox().maxi().x() >= xMean ;
bool down = primitive_tab[pindices[i]]->bbox().mini().y() <= yMean ;
bool up = primitive_tab[pindices[i]]->bbox().maxi().y() >= yMean ;
if(left && down) p_indices_min_min.push_back(pindices[i]) ;
if(right && down) p_indices_max_min.push_back(pindices[i]) ;
if(left && up ) p_indices_min_max.push_back(pindices[i]) ;
if(right && up ) p_indices_max_max.push_back(pindices[i]) ;
}
// checks if refining is not too much stupid
if(p_indices_min_min.size() < pindices.size() && p_indices_max_min.size() < pindices.size()
&& p_indices_min_max.size() < pindices.size() && p_indices_max_max.size() < pindices.size())
{
recursFindNeighbors(primitive_tab,p_indices_min_min,precedence_graph,AxisAlignedBox_xy(Vector2(xmin,xMean),Vector2(ymin,yMean)),depth+1) ;
recursFindNeighbors(primitive_tab,p_indices_min_max,precedence_graph,AxisAlignedBox_xy(Vector2(xmin,xMean),Vector2(yMean,ymax)),depth+1) ;
recursFindNeighbors(primitive_tab,p_indices_max_min,precedence_graph,AxisAlignedBox_xy(Vector2(xMean,xmax),Vector2(ymin,yMean)),depth+1) ;
recursFindNeighbors(primitive_tab,p_indices_max_max,precedence_graph,AxisAlignedBox_xy(Vector2(xMean,xmax),Vector2(yMean,ymax)),depth+1) ;
return ;
}
}
// No refinment either because it could not be possible, or because the number of primitives is below
// the predefined limit.
for(size_t i=0;i<pindices.size();++i)
for(size_t j=i+1;j<pindices.size();++j)
{
// Compute the position of j as regard to i
int prp = PrimitivePositioning::computeRelativePosition( primitive_tab[pindices[i]], primitive_tab[pindices[j]]) ;
if(prp & PrimitivePositioning::Upper) checkAndAddEdgeToGraph(pindices[j],pindices[i],precedence_graph) ;
if(prp & PrimitivePositioning::Lower) checkAndAddEdgeToGraph(pindices[i],pindices[j],precedence_graph) ;
}
}
void TopologicalSortUtils::checkAndAddEdgeToGraph(size_t a,size_t b,vector< vector<size_t> >& precedence_graph)
{
#ifdef DEBUG_TS
cout << "Trying to add " << a << " -> " << b << " " ;
#endif
bool found = false ;
for(size_t k=0;k<precedence_graph[a].size() && !found;++k)
if(precedence_graph[a][k] == b)
found = true ;
#ifdef DEBUG_TS
if(found)
cout << "already" << endl ;
else
cout << "ok" << endl ;
#endif
if(!found)
precedence_graph[a].push_back(b) ;
}
void TopologicalSortUtils::suppressPrecedence(size_t a,size_t b,vector< vector<size_t> >& precedence_graph)
{
vector<size_t> prec_tab = vector<size_t>(precedence_graph[a]) ;
bool trouve = false ;
for(size_t k=0;k<prec_tab.size();++k)
if(prec_tab[k] == b)
{
prec_tab[k] = prec_tab[prec_tab.size()-1] ;
prec_tab.pop_back() ;
}
if(!trouve)
throw runtime_error("Unexpected error in suppressPrecedence") ;
}
void TopologicalSortUtils::topologicalSort(vector< vector<size_t> >& precedence_graph,
vector<PtrPrimitive>& primitive_tab,
VRenderParams& vparams)
{
vector<PtrPrimitive> new_pr_tab ;
vector<bool> already_visited(primitive_tab.size(),false) ;
vector<bool> already_rendered(primitive_tab.size(),false) ;
size_t nb_skews = 0 ;
size_t info_cnt = primitive_tab.size()/200 + 1 ;
size_t nbrendered = 0 ;
// 1 - sorts primitives by rendering order
for(size_t i=0;i<primitive_tab.size();++i)
if(!already_rendered[i])
recursTopologicalSort(precedence_graph,primitive_tab,already_rendered,already_visited,new_pr_tab,i,nb_skews,vparams,info_cnt,nbrendered);
#ifdef DEBUG_TS
if(nb_skews > 0)
cout << nb_skews << " cycles found." << endl ;
else
cout << "No cycles found." << endl ;
#endif
primitive_tab = new_pr_tab ;
}
void TopologicalSortUtils::topologicalSortBreakCycles(vector< vector<size_t> >& precedence_graph,
vector<PtrPrimitive>& primitive_tab,
VRenderParams& vparams)
{
vector<PtrPrimitive> new_pr_tab ;
vector<bool> already_visited(primitive_tab.size(),false) ;
vector<bool> already_rendered(primitive_tab.size(),false) ;
vector<size_t> ancestors ;
size_t nb_skews = 0 ;
size_t ancestors_backward_index ;
size_t info_cnt = primitive_tab.size()/200 + 1 ;
size_t nbrendered = 0 ;
// 1 - sorts primitives by rendering order
for(size_t i=0;i<primitive_tab.size();++i)
if(!already_rendered[i])
recursTopologicalSort(precedence_graph,primitive_tab,already_rendered,already_visited,
new_pr_tab,i,ancestors,ancestors_backward_index,nb_skews,vparams,info_cnt,nbrendered) ;
#ifdef DEBUG_TS
if(nb_skews > 0)
cout << nb_skews << " cycles found." << endl ;
else
cout << "No cycles found." << endl ;
#endif
primitive_tab = new_pr_tab ;
}
void TopologicalSortUtils::recursTopologicalSort( vector< vector<size_t> >& precedence_graph,
vector<PtrPrimitive>& primitive_tab,
vector<bool>& already_rendered,
vector<bool>& already_visited,
vector<PtrPrimitive>& new_pr_tab,
size_t indx,
size_t& nb_cycles,
VRenderParams& vparams,
size_t info_cnt,size_t& nbrendered)
{
// One must first render the primitives indicated by the precedence graph,
// then render the current primitive. Skews are detected, but and treated.
already_visited[indx] = true ;
for(size_t j=0;j<precedence_graph[indx].size();++j)
{
// Both tests are important. If we ommit the second one, the recursion is
// always performed down to the next cycle, although this is useless if
// the current primitive was rendered already.
if(!already_visited[precedence_graph[indx][j]])
{
if(!already_rendered[precedence_graph[indx][j]])
recursTopologicalSort( precedence_graph,primitive_tab,already_rendered,already_visited,
new_pr_tab,precedence_graph[indx][j],nb_cycles,vparams,info_cnt,nbrendered) ;
}
else // A cycle is detected, but in this version, it is not broken.
++nb_cycles ;
}
if(!already_rendered[indx])
{
new_pr_tab.push_back(primitive_tab[indx]) ;
if((++nbrendered)%info_cnt==0)
vparams.progress(nbrendered/(float)primitive_tab.size(), QGLViewer::tr("Topological sort")) ;
}
already_rendered[indx] = true ;
already_visited[indx] = false ;
}
void TopologicalSortUtils::recursTopologicalSort( vector< vector<size_t> >& precedence_graph,
vector<PtrPrimitive>& primitive_tab,
vector<bool>& already_rendered,
vector<bool>& already_visited,
vector<PtrPrimitive>& new_pr_tab,
size_t indx,
vector<size_t>& ancestors,
size_t& ancestors_backward_index,
size_t& nb_cycles,
VRenderParams& vparams,
size_t info_cnt,size_t& nbrendered)
{
// One must first render the primitives indicated by the precedence graph,
// then render the current primitive. Skews are detected, but and treated.
already_visited[indx] = true ;
ancestors.push_back(indx) ;
for(size_t j=0;j<precedence_graph[indx].size();++j)
{
// Both tests are important. If we ommit the second one, the recursion is
// always performed down to the next cycle, although this is useless if
// the current primitive was rendered already.
if(!already_visited[precedence_graph[indx][j]])
{
if(!already_rendered[precedence_graph[indx][j]])
{
recursTopologicalSort( precedence_graph,primitive_tab,already_rendered,already_visited,
new_pr_tab,precedence_graph[indx][j],ancestors,ancestors_backward_index,nb_cycles,vparams,info_cnt,nbrendered) ;
if(ancestors_backward_index != INT_MAX && ancestors.size() > (size_t)(ancestors_backward_index+1))
{
#ifdef DEBUG_TS
cout << "Returning early" << endl ;
#endif
already_visited[indx] = false ;
ancestors.pop_back() ;
return;
}
if(ancestors_backward_index != INT_MAX) // we are returning from emergency. j must be re-tried
--j ;
}
}
else
{
// A cycle is detected. It must be broken. The algorithm is the following: primitives of the cycle
// are successively split by a chosen splitting plane and the precendence graph is updated
// at the same time by re-computing primitive precedence. As soon as the cycle is broken,
// the algorithm stops and calls recursively calls on the new precedence graph. This necessarily
// happens because of the BSP-node nature of the current set of primitives.
// 0 - stats
++nb_cycles ;
// 0.5 - determine cycle beginning
long cycle_beginning_index = -1 ;
for(size_t i=ancestors.size()-1; long(i) >= 0 && cycle_beginning_index < 0;--i)
if(ancestors[i] == precedence_graph[indx][j])
cycle_beginning_index = (long)i ;
#ifdef DEBUG_TS
cout << "Unbreaking cycle : " ;
for(size_t i=0;i<ancestors.size();++i)
cout << ancestors[i] << " " ;
cout << precedence_graph[indx][j] << endl ;
#endif
#ifdef DEBUG_TS
assert(cycle_beginning_index >= 0) ;
#endif
// 1 - determine splitting plane
long split_prim_ancestor_indx = -1 ;
long split_prim_indx = -1 ;
// Go down ancestors tab, starting from the skewing primitive, and stopping at it.
for(size_t i2=(size_t)cycle_beginning_index;i2<ancestors.size() && split_prim_ancestor_indx < 0;++i2)
if(primitive_tab[ancestors[i2]]->nbVertices() > 2)
{
split_prim_ancestor_indx = (long)i2 ;
split_prim_indx = (long)ancestors[i2] ;
}
#ifdef DEBUG_TS
cout << "Split primitive index = " << split_prim_ancestor_indx << "(primitive = " << split_prim_indx << ")" << endl ;
#endif
if(split_prim_indx < 0) // no need to unskew cycles between segments and points
continue ;
// 2 - split all necessary primitives
const Polygone *P = dynamic_cast<const Polygone *>(primitive_tab[(size_t)split_prim_indx]) ;
const NVector3& normal = NVector3(P->normal()) ;
double c(P->c()) ;
ancestors.push_back(precedence_graph[indx][j]) ; // sentinel
ancestors.push_back(ancestors[(size_t)cycle_beginning_index+1]) ; // sentinel
bool cycle_broken = false ;
for(size_t i3=(size_t)cycle_beginning_index+1;i3<ancestors.size()-1 && !cycle_broken;++i3)
if(ancestors[i3] != (size_t)split_prim_indx)
{
bool prim_lower_ante_contains_im1 = false ;
bool prim_upper_ante_contains_im1 = false ;
bool prim_lower_prec_contains_ip1 = false ;
bool prim_upper_prec_contains_ip1 = false ;
Primitive *prim_upper = NULL ;
Primitive *prim_lower = NULL ;
PrimitivePositioning::splitPrimitive(primitive_tab[ancestors[i3]],normal,c,prim_upper,prim_lower) ;
if(prim_upper == NULL || prim_lower == NULL)
continue ;
#ifdef DEBUG_TS
cout << "Splitted primitive " << ancestors[i3] << endl ;
#endif
vector<size_t> prim_upper_prec ;
vector<size_t> prim_lower_prec ;
vector<size_t> old_prec = vector<size_t>(precedence_graph[ancestors[i3]]) ;
size_t upper_indx = precedence_graph.size() ;
size_t lower_indx = ancestors[i3] ;
// Updates the precedence graph downwards.
for(size_t k=0;k<old_prec.size();++k)
{
int prp1 = PrimitivePositioning::computeRelativePosition(prim_upper,primitive_tab[old_prec[k]]) ;
#ifdef DEBUG_TS
cout << "Compariing " << upper_indx << " and " << old_prec[k] << ": " ;
#endif
// It can not be Upper, because it was lower from the original primitive, but it is not
// necessary lower any longer because of the split.
if(prp1 & PrimitivePositioning::Lower)
{
#ifdef DEBUG_TS
cout << " > " << endl ;
#endif
prim_upper_prec.push_back(old_prec[k]) ;
if(old_prec[k] == ancestors[i3+1])
prim_upper_prec_contains_ip1 = true ;
}
#ifdef DEBUG_TS
else
cout << " I " << endl ;
#endif
int prp2 = PrimitivePositioning::computeRelativePosition(prim_lower,primitive_tab[old_prec[k]]) ;
#ifdef DEBUG_TS
cout << "Compariing " << lower_indx << " and " << old_prec[k] << ": " ;
#endif
if(prp2 & PrimitivePositioning::Lower)
{
#ifdef DEBUG_TS
cout << " > " << endl ;
#endif
prim_lower_prec.push_back(old_prec[k]) ;
if(old_prec[k] == ancestors[i3+1])
prim_lower_prec_contains_ip1 = true ;
}
#ifdef DEBUG_TS
else
cout << " I " << endl ;
#endif
}
// We also have to update the primitives which are upper to the
// current one, because some of them may not be upper anymore.
// This would requires either a O(n^2) algorithm, or to store an
// dual precedence graph. For now it's O(n^2). This test can not
// be skipped because upper can still be lower to ancestors[i-1].
for(size_t l=0;l<precedence_graph.size();++l)
if(l != (size_t)lower_indx)
for(size_t k=0;k<precedence_graph[l].size();++k)
if(precedence_graph[l][k] == ancestors[i3])
{
int prp1 = PrimitivePositioning::computeRelativePosition(prim_upper,primitive_tab[l]) ;
// It can not be Lower, because it was upper from the original primitive, but it is not
// necessary upper any longer because of the split.
if(prp1 & PrimitivePositioning::Upper)
{
// Still upper. Add the new index at end of the array
precedence_graph[l].push_back(upper_indx) ;
if(l == (size_t)ancestors[i3-1])
prim_upper_ante_contains_im1 = true ;
}
// If the primitive is not upper anymore there is
// nothing to change since the index has changed.
int prp2 = PrimitivePositioning::computeRelativePosition(prim_lower,primitive_tab[l]) ;
#ifdef DEBUG_TS
cout << "Compariing " << l << " and " << lower_indx << ": " ;
#endif
if(prp2 & PrimitivePositioning::Upper)
{
#ifdef DEBUG_TS
cout << " > " << endl ;
#endif
if(l == (size_t)ancestors[i3-1]) // The index is the same => nothing to change.
prim_lower_ante_contains_im1 = true ;
}
else
{
#ifdef DEBUG_TS
cout << " I " << endl ;
#endif
// Not upper anymore. We have to suppress this entry from the tab.
precedence_graph[l][k] = precedence_graph[l][precedence_graph[l].size()-1] ;
precedence_graph[l].pop_back() ;
--k ;
}
break ; // each entry is present only once.
}
// setup recorded new info
primitive_tab.push_back(prim_upper) ;
delete primitive_tab[lower_indx] ;
primitive_tab[lower_indx] = prim_lower ;
// Adds the info to the precedence graph
precedence_graph.push_back(prim_upper_prec) ;
precedence_graph[lower_indx] = prim_lower_prec ;
// Adds new entries to the 'already_rendered' and 'already_visited' vectors
already_visited.push_back(false) ;
already_rendered.push_back(false) ;
#ifdef DEBUG_TS
cout << "New precedence graph: " << endl ;
printPrecedenceGraph(precedence_graph,primitive_tab) ;
#endif
// Checks if the cycle is broken. Because the graph is only
// updated downwards, we check wether lower (which still is
// lower to ancestors[i-1]) is upper to ancestors[i+1], or
// if upper is still .
if(( !(prim_lower_ante_contains_im1 && prim_lower_prec_contains_ip1))
&&(!(prim_upper_ante_contains_im1 && prim_upper_prec_contains_ip1)))
cycle_broken = true ;
}
ancestors.pop_back() ;
ancestors.pop_back() ;
// 3 - recurs call
if(cycle_broken)
{
ancestors_backward_index = (size_t)cycle_beginning_index ;
#ifdef DEBUG_TS
cout << "Cycle broken. Jumping back to rank " << ancestors_backward_index << endl ;
#endif
already_visited[indx] = false ;
ancestors.pop_back() ;
return;
}
#ifdef DEBUG_TS
else
cout << "Cycle could not be broken !!" << endl ;
#endif
}
}
if(!already_rendered[indx])
{
#ifdef DEBUG_TS
cout << "Returning ok. Rendered primitive " << indx << endl ;
#endif
new_pr_tab.push_back(primitive_tab[indx]) ;
if((++nbrendered)%info_cnt==0)
vparams.progress(nbrendered/(float)primitive_tab.size(), QGLViewer::tr("Advanced topological sort")) ;
}
already_rendered[indx] = true ;
ancestors_backward_index = INT_MAX ;
already_visited[indx] = false ;
ancestors.pop_back() ;
}
} // namespace
| 23,964 | 33.782293 | 141 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Types.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_TYPES_H
#define _VRENDER_TYPES_H
#ifdef WIN32
# include <windows.h>
#endif
#ifdef __APPLE__
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif
namespace vrender
{
typedef double FLOAT ;
typedef GLdouble GLFLOAT ;
#ifdef A_VOIR
typedef T_Vect3<double> DVector3 ;
typedef T_Vect2<double> Vector2 ;
#endif
class Primitive ;
typedef Primitive *PtrPrimitive ;
const float FLAT_POLYGON_EPS = 1e-5f ;
}
#endif
| 2,279 | 29.4 | 78 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/VRender.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifdef WIN32
# include <windows.h>
#endif
#ifdef __APPLE__
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <string.h>
#include "VRender.h"
#include "ParserGL.h"
#include "Exporter.h"
#include "SortMethod.h"
#include "Optimizer.h"
using namespace vrender ;
using namespace std ;
void vrender::VectorialRender(RenderCB render_callback, void *callback_params, VRenderParams& vparams)
{
GLfloat *feedbackBuffer = NULL ;
SortMethod *sort_method = NULL ;
Exporter *exporter = NULL ;
try
{
GLint returned = -1 ;
vparams.error() = 0 ;
int nb_renders = 0 ;
vparams.progress(0.0, QGLViewer::tr("Rendering...")) ;
while(returned < 0)
{
if(feedbackBuffer != NULL)
delete[] feedbackBuffer ;
feedbackBuffer = new GLfloat[vparams.size()] ;
if(feedbackBuffer == NULL)
throw std::runtime_error("Out of memory during feedback buffer allocation.") ;
glFeedbackBuffer(vparams.size(), GL_3D_COLOR, feedbackBuffer);
glRenderMode(GL_FEEDBACK);
render_callback(callback_params);
returned = glRenderMode(GL_RENDER);
nb_renders++ ;
if(returned < 0)
vparams.size() *= 2 ;
}
#ifdef A_VOIR
if(SortMethod != EPS_DONT_SORT)
{
GLint depth_bits ;
glGetIntegerv(GL_DEPTH_BITS, &depth_bits) ;
EGALITY_EPS = 2.0/(1 << depth_bits) ;
LINE_EGALITY_EPS = 2.0/(1 << depth_bits) ;
}
#endif
if (returned > vparams.size())
vparams.size() = returned;
#ifdef _VRENDER_DEBUG
cout << "Size = " << vparams.size() << ", returned=" << returned << endl ;
#endif
// On a un beau feedback buffer tout plein de saloperies. Faut aller
// defricher tout ca. Ouaiiiis !
vector<PtrPrimitive> primitive_tab ;
ParserGL parserGL ;
parserGL.parseFeedbackBuffer(feedbackBuffer,returned,primitive_tab,vparams) ;
if(feedbackBuffer != NULL)
{
delete[] feedbackBuffer ;
feedbackBuffer = NULL ;
}
if(vparams.isEnabled(VRenderParams::OptimizeBackFaceCulling))
{
BackFaceCullingOptimizer bfopt ;
bfopt.optimize(primitive_tab,vparams) ;
}
// Lance la methode de sorting
switch(vparams.sortMethod())
{
case VRenderParams::AdvancedTopologicalSort:
case VRenderParams::TopologicalSort: {
TopologicalSortMethod *tsm = new TopologicalSortMethod() ;
tsm->setBreakCycles(vparams.sortMethod() == VRenderParams::AdvancedTopologicalSort) ;
sort_method = tsm ;
}
break ;
case VRenderParams::BSPSort: sort_method = new BSPSortMethod() ;
break ;
case VRenderParams::NoSorting: sort_method = new DontSortMethod() ;
break ;
default:
throw std::runtime_error("Unknown sorting method.") ;
}
sort_method->sortPrimitives(primitive_tab,vparams) ;
// Lance les optimisations. L'ordre est important.
if(vparams.isEnabled(VRenderParams::CullHiddenFaces))
{
VisibilityOptimizer vopt ;
vopt.optimize(primitive_tab,vparams) ;
}
#ifdef A_FAIRE
if(vparams.isEnabled(VRenderParams::OptimizePrimitiveSplit))
{
PrimitiveSplitOptimizer psopt ;
psopt.optimize(primitive_tab) ;
}
#endif
// Ecrit le fichier
switch(vparams.format())
{
case VRenderParams::EPS: exporter = new EPSExporter() ;
break ;
case VRenderParams::PS: exporter = new PSExporter() ;
break ;
case VRenderParams::XFIG:exporter = new FIGExporter() ;
break ;
#ifdef A_FAIRE
case VRenderParams::SVG: exporter = new SVGExporter() ;
break ;
#endif
default:
throw std::runtime_error("Sorry, this output format is not handled now. Only EPS and PS are currently supported.") ;
}
// sets background and black & white options
GLfloat viewport[4],clearColor[4],lineWidth,pointSize ;
glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor);
glGetFloatv(GL_LINE_WIDTH, &lineWidth);
glGetFloatv(GL_POINT_SIZE, &pointSize);
glGetFloatv(GL_VIEWPORT, viewport);
lineWidth /= (float)max(viewport[2] - viewport[0],viewport[3]-viewport[1]) ;
// Sets which bounding box to use.
if(vparams.isEnabled(VRenderParams::TightenBoundingBox))
exporter->setBoundingBox(parserGL.xmin(),parserGL.ymin(),parserGL.xmax(),parserGL.ymax()) ;
else
exporter->setBoundingBox(viewport[0],viewport[1],viewport[0]+viewport[2],viewport[1]+viewport[3]) ;
exporter->setBlackAndWhite(vparams.isEnabled(VRenderParams::RenderBlackAndWhite)) ;
exporter->setClearBackground(vparams.isEnabled(VRenderParams::AddBackground)) ;
exporter->setClearColor(clearColor[0],clearColor[1],clearColor[2]) ;
exporter->exportToFile(vparams.filename(),primitive_tab,vparams) ;
// deletes primitives
for(unsigned int i=0;i<primitive_tab.size();++i)
delete primitive_tab[i] ;
if(exporter != NULL) delete exporter ;
if(sort_method != NULL) delete sort_method ;
}
catch(exception& e)
{
cout << "Render aborted: " << e.what() << endl ;
if(exporter != NULL) delete exporter ;
if(sort_method != NULL) delete sort_method ;
if(feedbackBuffer != NULL) delete[] feedbackBuffer ;
throw e ;
}
}
VRenderParams::VRenderParams()
{
_options = 0 ;
_format = EPS ;
_filename = "" ;
_progress_function = NULL ;
_sortMethod = BSPSort ;
}
VRenderParams::~VRenderParams()
{}
void VRenderParams::progress(float f, const QString& progress_string)
{
_progress_function(f,progress_string) ;
}
void VRenderParams::setFilename(const QString& filename)
{
_filename = filename;
}
void VRenderParams::setOption(VRenderOption opt,bool b)
{
if(b)
_options |= opt ;
else
_options &= ~opt ;
}
bool VRenderParams::isEnabled(VRenderOption opt)
{
return (_options & opt) > 0 ;
}
| 7,413 | 25.765343 | 119 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/VRender.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_H_
#define _VRENDER_H_
#include "../config.h"
#include <QTextStream>
#include <QString>
#include "../qglviewer.h"
namespace vrender
{
class VRenderParams ;
typedef void (*RenderCB)(void *) ;
typedef void (*ProgressFunction)(float,const QString&) ;
void VectorialRender(RenderCB DrawFunc, void *callback_params, VRenderParams& render_params) ;
class VRenderParams
{
public:
VRenderParams() ;
~VRenderParams() ;
enum VRenderSortMethod { NoSorting, BSPSort, TopologicalSort, AdvancedTopologicalSort };
enum VRenderFormat { EPS, PS, XFIG, SVG };
enum VRenderOption { CullHiddenFaces = 0x1,
OptimizeBackFaceCulling = 0x4,
RenderBlackAndWhite = 0x8,
AddBackground = 0x10,
TightenBoundingBox = 0x20 } ;
int sortMethod() { return _sortMethod; }
void setSortMethod(VRenderParams::VRenderSortMethod s) { _sortMethod = s ; }
int format() { return _format; }
void setFormat(VRenderFormat f) { _format = f; }
const QString filename() { return _filename ; }
void setFilename(const QString& filename) ;
void setOption(VRenderOption,bool) ;
bool isEnabled(VRenderOption) ;
void setProgressFunction(ProgressFunction pf) { _progress_function = pf ; }
private:
int _error;
VRenderSortMethod _sortMethod;
VRenderFormat _format ;
ProgressFunction _progress_function ;
unsigned int _options; // _DrawMode; _ClearBG; _TightenBB;
QString _filename;
friend void VectorialRender( RenderCB render_callback,
void *callback_params,
VRenderParams& vparams);
friend class ParserGL ;
friend class Exporter ;
friend class BSPSortMethod ;
friend class VisibilityOptimizer ;
friend class TopologicalSortMethod ;
friend class TopologicalSortUtils ;
int& error() { return _error ; }
int& size() { static int size=1000000; return size ; }
void progress(float,const QString&) ;
};
}
#endif
| 3,811 | 31.033613 | 95 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Vector2.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "Vector2.h"
#include "Vector3.h"
#include <math.h>
#include <algorithm>
#ifdef WIN32
# include <windows.h>
#endif
using namespace vrender;
using namespace std;
const Vector2 Vector2::inf(FLT_MAX, FLT_MAX);
//! Default constructor
Vector2::Vector2 ()
{
_xyz[0] = 0.0;
_xyz[1] = 0.0;
}
// -----------------------------------------------------------------------------
//! Default destructor
Vector2::~Vector2 ()
{
}
// -----------------------------------------------------------------------------
//! Copy constructor
Vector2::Vector2 (const Vector2& u)
{
setXY(u[0],u[1]);
}
// -----------------------------------------------------------------------------
//! Create a vector from real values
Vector2::Vector2 (double x,double y)
{
setXY(x,y);
}
Vector2::Vector2 (const Vector3& u)
{
_xyz[0] = u[0];
_xyz[1] = u[1];
}
// -----------------------------------------------------------------------------
//! Inverse
Vector2 vrender::operator- (const Vector2& u)
{
return Vector2(-u[0], -u[1]) ;
}
// -----------------------------------------------------------------------------
//! Left multiplication by a real value
Vector2 operator* (double r,const Vector2& u)
{
return Vector2(r*u[0], r*u[1]) ;
}
// -----------------------------------------------------------------------------
//! Norm
double Vector2::norm () const
{
return sqrt( _xyz[0]*_xyz[0] + _xyz[1]*_xyz[1] );
}
// -----------------------------------------------------------------------------
//! Square norm (self dot product)
double Vector2::squareNorm () const
{
return _xyz[0]*_xyz[0] + _xyz[1]*_xyz[1] ;
}
// -----------------------------------------------------------------------------
//! Infinite norm
double Vector2::infNorm() const
{
return max(fabs(_xyz[0]),fabs(_xyz[1])) ;
}
// -----------------------------------------------------------------------------
//! Out stream override: prints the 3 vector components
std::ostream& operator<< (std::ostream& out,const Vector2& u)
{
out << u[0] << " " << u[1] ;
return ( out );
}
Vector2 Vector2::mini(const Vector2& v1,const Vector2& v2)
{
return Vector2(std::min(v1[0],v2[0]),std::min(v1[1],v2[1])) ;
}
Vector2 Vector2::maxi(const Vector2& v1,const Vector2& v2)
{
return Vector2(std::max(v1[0],v2[0]),std::max(v1[1],v2[1])) ;
}
| 4,140 | 26.97973 | 80 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Vector2.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_VECTOR2_H
#define _VRENDER_VECTOR2_H
#include <stdexcept>
#include <iostream>
namespace vrender
{
class Vector3;
class Vector2
{
public:
// ---------------------------------------------------------------------------
//! @name Constant
//@{
static const Vector2 inf;
//@}
// ---------------------------------------------------------------------------
//! @name Constructor(s) and destructor
//@{
Vector2 ();
~Vector2 ();
Vector2 (const Vector2&);
Vector2 (const Vector3& u);
Vector2 (double,double);
//@}
// ---------------------------------------------------------------------------
//! @name Access methods
//@{
inline double x() const { return _xyz[0]; }
inline double y() const { return _xyz[1]; }
inline void setX(double r) { _xyz[0] = r; }
inline void setY(double r) { _xyz[1] = r; }
inline void setXY (double x,double y) { _xyz[0] = x; _xyz[1] = y; }
//@}
// ---------------------------------------------------------------------------
//! @name Assignment
//@{
inline Vector2& operator= (const Vector2& u) { _xyz[0] = u._xyz[0]; _xyz[1] = u._xyz[1]; return *this; }
//@}
// ---------------------------------------------------------------------------
//! @name Comparisons
//@{
friend bool operator== (const Vector2&,const Vector2&);
friend bool operator!= (const Vector2&,const Vector2&);
//@}
// ---------------------------------------------------------------------------
//! @name Algebraic operations
//@{
inline Vector2& operator+= (const Vector2& v)
{
_xyz[0] += v._xyz[0];
_xyz[1] += v._xyz[1];
return *this;
}
inline Vector2& operator-= (const Vector2& v)
{
_xyz[0] -= v._xyz[0];
_xyz[1] -= v._xyz[1];
return *this;
}
inline Vector2& operator*= (double f) { _xyz[0] *= f; _xyz[1] *= f; return *this;}
inline Vector2& operator/= (double f) { _xyz[0] /= f; _xyz[1] /= f; return *this;}
friend Vector2 operator- (const Vector2&);
static Vector2 mini(const Vector2&,const Vector2&) ;
static Vector2 maxi(const Vector2&,const Vector2&) ;
inline Vector2 operator+(const Vector2& u) const
{
return Vector2(_xyz[0]+u._xyz[0],_xyz[1]+u._xyz[1]);
}
inline Vector2 operator-(const Vector2& u) const
{
return Vector2(_xyz[0]-u._xyz[0],_xyz[1]-u._xyz[1]);
}
inline double operator*(const Vector2& u) const
{
return _xyz[0]*u._xyz[0] + _xyz[1]*u._xyz[1] ;
}
inline double operator^(const Vector2& v) const
{
return _xyz[0]*v._xyz[1] - _xyz[1]*v._xyz[0] ;
}
Vector2 operator/ (double v) { return Vector2(_xyz[0]/v,_xyz[1]/v); }
Vector2 operator* (double v) { return Vector2(_xyz[0]*v,_xyz[1]*v); }
friend Vector2 operator* (double,const Vector2&);
//@}
// ---------------------------------------------------------------------------
//! @name Metrics
//@{
double norm () const;
double squareNorm () const;
double infNorm () const; /// Should be used for most comparisons, for efficiency reasons.
//@}
// ---------------------------------------------------------------------------
//! @name Stream overrides
//@{
friend std::ostream& operator<< (std::ostream&,const Vector2&);
//@}
double operator[] (int i) const
{
if((i < 0)||(i > 1))
throw std::runtime_error("Out of bounds in Vector2::operator[]") ;
return _xyz[i];
}
double& operator[] (int i)
{
if((i < 0)||(i > 1))
throw std::runtime_error("Out of bounds in Vector2::operator[]") ;
return _xyz[i];
}
private:
double _xyz[2]; //!< The 3 vector components
}; // interface of Vector2
}
#endif // _VECTOR2_H
| 5,582 | 29.675824 | 108 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Vector3.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <iostream>
#include "Vector3.h"
#include "NVector3.h"
#include <math.h>
#include <algorithm>
#ifdef WIN32
# include <windows.h>
#endif
using namespace vrender;
using namespace std;
const Vector3 Vector3::inf(FLT_MAX, FLT_MAX, FLT_MAX);
Vector3::Vector3 ()
{
_xyz[0] = 0.0;
_xyz[1] = 0.0;
_xyz[2] = 0.0;
}
// -----------------------------------------------------------------------------
//! Default destructor
Vector3::~Vector3 ()
{
}
// -----------------------------------------------------------------------------
//! Copy constructor
Vector3::Vector3 (const Vector3& u)
{
setXYZ(u[0],u[1],u[2]);
}
// -----------------------------------------------------------------------------
//! Copy constructor from a normalized vector
Vector3::Vector3 (const NVector3& u)
{
setXYZ(u[0],u[1],u[2]);
}
// -----------------------------------------------------------------------------
//! Create a vector from real values
Vector3::Vector3 (double x,double y,double z)
{
setXYZ(x,y,z);
}
// -----------------------------------------------------------------------------
//! Assignment with a normalized vector
Vector3& Vector3::operator= (const NVector3& u)
{
_xyz[0] = u[0];
_xyz[1] = u[1];
_xyz[2] = u[2];
return ( *this );
}
// -----------------------------------------------------------------------------
//! Self addition with a normalized vector
Vector3& Vector3::operator+= (const NVector3& u)
{
_xyz[0] += u[0];
_xyz[1] += u[1];
_xyz[2] += u[2];
return ( *this );
}
// -----------------------------------------------------------------------------
//! Self substraction with a normalized vector
Vector3& Vector3::operator-= (const NVector3& u)
{
_xyz[0] -= u[0];
_xyz[1] -= u[1];
_xyz[2] -= u[2];
return ( *this );
}
// -----------------------------------------------------------------------------
//! Left multiplication by a real value
Vector3 vrender::operator* (double r,const Vector3& u)
{
return ( Vector3(r*u[0], r*u[1], r*u[2]) );
}
// -----------------------------------------------------------------------------
//! Norm
double Vector3::norm () const
{
return sqrt( _xyz[0]*_xyz[0] + _xyz[1]*_xyz[1] + _xyz[2]*_xyz[2] );
}
// -----------------------------------------------------------------------------
//! Square norm (self dot product)
double Vector3::squareNorm () const
{
return _xyz[0]*_xyz[0] + _xyz[1]*_xyz[1] + _xyz[2]*_xyz[2];
}
// -----------------------------------------------------------------------------
//! Infinite norm
double Vector3::infNorm() const
{
return std::max(std::max(fabs(_xyz[0]),fabs(_xyz[1])),fabs(_xyz[2])) ;
}
// -----------------------------------------------------------------------------
//! Out stream override: prints the 3 vector components
std::ostream& vrender::operator<< (std::ostream& out,const Vector3& u)
{
out << u[0] << " " << u[1] << " " << u[2];
return ( out );
}
Vector3 Vector3::mini(const Vector3& v1,const Vector3& v2)
{
return Vector3(std::min(v1[0],v2[0]),std::min(v1[1],v2[1]),std::min(v1[2],v2[2])) ;
}
Vector3 Vector3::maxi(const Vector3& v1,const Vector3& v2)
{
return Vector3(std::max(v1[0],v2[0]),std::max(v1[1],v2[1]),std::max(v1[2],v2[2])) ;
}
| 5,034 | 28.444444 | 85 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/Vector3.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_VECTOR3_H
#define _VRENDER_VECTOR3_H
#include <stdexcept>
#ifndef FLT_MAX
# define FLT_MAX 9.99E20f
#endif
namespace vrender
{
class NVector3;
class Vector3
{
public:
// ---------------------------------------------------------------------------
//! @name Constant
//@{
static const Vector3 inf;
//@}
// ---------------------------------------------------------------------------
//! @name Constructor(s) and destructor
//@{
Vector3 ();
~Vector3 ();
Vector3 (const Vector3&);
Vector3 (const NVector3&);
Vector3 (double, double, double);
//@}
// ---------------------------------------------------------------------------
//! @name Access methods
//@{
inline double x() const { return _xyz[0]; }
inline double y() const { return _xyz[1]; }
inline double z() const { return _xyz[2]; }
inline void setX(double r) { _xyz[0] = r; }
inline void setY(double r) { _xyz[1] = r; }
inline void setZ(double r) { _xyz[2] = r; }
inline void setXYZ (double x,double y,double z) { _xyz[0] = x; _xyz[1] = y; _xyz[2] = z; }
//@}
// ---------------------------------------------------------------------------
//! @name Assignment
//@{
inline Vector3& operator= (const Vector3& u) { _xyz[0] = u._xyz[0]; _xyz[1] = u._xyz[1]; _xyz[2] = u._xyz[2]; return *this; }
Vector3& operator= (const NVector3& u);
//@}
// ---------------------------------------------------------------------------
//! @name Comparisons
//@{
friend bool operator== (const Vector3&,const Vector3&);
friend bool operator!= (const Vector3&,const Vector3&);
//@}
// ---------------------------------------------------------------------------
//! @name Algebraic operations
//@{
inline Vector3& operator+= (const Vector3& v)
{
_xyz[0] += v._xyz[0];
_xyz[1] += v._xyz[1];
_xyz[2] += v._xyz[2];
return *this;
}
inline Vector3& operator-= (const Vector3& v)
{
_xyz[0] -= v._xyz[0];
_xyz[1] -= v._xyz[1];
_xyz[2] -= v._xyz[2];
return *this;
}
inline Vector3& operator*= (double f) { _xyz[0] *= f; _xyz[1] *= f; _xyz[2] *= f; return *this;}
inline Vector3& operator/= (double f) { _xyz[0] /= f; _xyz[1] /= f; _xyz[2] /= f; return *this;}
static Vector3 mini(const Vector3&,const Vector3&) ;
static Vector3 maxi(const Vector3&,const Vector3&) ;
Vector3& operator-= (const NVector3&);
Vector3& operator+= (const NVector3&);
friend Vector3 operator- (const Vector3& u) { return Vector3(-u[0], -u[1], -u[2]); }
inline Vector3 operator+(const Vector3& u) const
{
return Vector3(_xyz[0]+u._xyz[0],_xyz[1]+u._xyz[1],_xyz[2]+u._xyz[2]);
}
inline Vector3 operator-(const Vector3& u) const
{
return Vector3(_xyz[0]-u._xyz[0],_xyz[1]-u._xyz[1],_xyz[2]-u._xyz[2]);
}
inline double operator*(const Vector3& u) const
{
return _xyz[0]*u._xyz[0] + _xyz[1]*u._xyz[1] + _xyz[2]*u._xyz[2];
}
inline Vector3 operator^(const Vector3& v) const
{
return Vector3( _xyz[1]*v._xyz[2] - _xyz[2]*v._xyz[1],
_xyz[2]*v._xyz[0] - _xyz[0]*v._xyz[2],
_xyz[0]*v._xyz[1] - _xyz[1]*v._xyz[0]);
}
Vector3 operator/ (double v) { return Vector3(_xyz[0]/v,_xyz[1]/v,_xyz[2]/v); }
Vector3 operator* (double v) { return Vector3(_xyz[0]*v,_xyz[1]*v,_xyz[2]*v); }
friend Vector3 operator* (double,const Vector3&);
//@}
// ---------------------------------------------------------------------------
//! @name Metrics
//@{
double norm () const;
double squareNorm () const;
double infNorm () const; /// Should be used for most comparisons, for efficiency reasons.
//@}
// ---------------------------------------------------------------------------
//! @name Stream overrides
//@{
friend std::ostream& operator<< (std::ostream&,const Vector3&);
//@}
double operator[] (int i) const
{
if((i < 0)||(i > 2))
throw std::runtime_error("Out of bounds in Vector3::operator[]") ;
return _xyz[i];
}
double& operator[] (int i)
{
if((i < 0)||(i > 2))
throw std::runtime_error("Out of bounds in Vector3::operator[]") ;
return _xyz[i];
}
private:
double _xyz[3]; //!< The 3 vector components
}; // interface of Vector3
}
#endif // _VECTOR3_H
| 6,196 | 30.617347 | 129 | h |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/VisibilityOptimizer.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <vector>
#include "VRender.h"
#include "Optimizer.h"
#include "Primitive.h"
#include "gpc.h"
#include "math.h"
using namespace vrender ;
using namespace std ;
#ifdef A_FAIRE
void VisibilityOptimizer::optimize(vector<PtrPrimitive>& primitives,float& percentage_finished,string& message)
#else
void VisibilityOptimizer::optimize(vector<PtrPrimitive>& primitives,VRenderParams& vparams)
#endif
{
#ifdef DEBUG_VO
cout << "Optimizing visibility." << endl ;
#endif
unsigned long N = primitives.size()/200 + 1 ;
#ifdef DEBUG_EPSRENDER__SHOW1
// cout << "Showing viewer." << endl ;
// myViewer viewer ;
// viewer.show();
double minx = FLT_MAX ;
double miny = FLT_MAX ;
double maxx = -FLT_MAX ;
double maxy = -FLT_MAX ;
for(unsigned int i=0;i<primitives.size();++i)
for(int j=0;j<primitives[i]->nbVertices();++j)
{
if(maxx < primitives[i]->vertex(j).x()) maxx = primitives[i]->vertex(j).x() ;
if(maxy < primitives[i]->vertex(j).y()) maxy = primitives[i]->vertex(j).y() ;
if(minx > primitives[i]->vertex(j).x()) minx = primitives[i]->vertex(j).x() ;
if(miny > primitives[i]->vertex(j).y()) miny = primitives[i]->vertex(j).y() ;
}
glMatrixMode(GL_PROJECTION) ;
glLoadIdentity() ;
glOrtho(minx,maxx,miny,maxy,-1,1) ;
glMatrixMode(GL_MODELVIEW) ;
glLoadIdentity() ;
cout << "Window set to " << minx << " " << maxx << " " << miny << " " << maxy << endl ;
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) ;
glLineWidth(3.0) ;
#endif
int nb_culled = 0 ;
// Ca serait pas mal mieux avec une interface c++...
gpc_polygon cumulated_union ;
cumulated_union.num_contours = 0 ;
cumulated_union.hole = NULL ;
cumulated_union.contour = NULL ;
size_t nboptimised = 0 ;
for(size_t pindex = primitives.size() - 1; long(pindex) >= 0;--pindex,++nboptimised)
if(primitives[pindex] != NULL)
{
#ifdef A_FAIRE
percentage_finished = pindex / (float)primitives.size() ;
#endif
if(primitives[pindex]->nbVertices() > 1)
{
#ifdef DEBUG_VO
if(pindex%50==0)
{
char buff[500] ;
sprintf(buff,"Left: % 6ld - Culled: % 6ld", pindex,(long)nb_culled) ;
fprintf(stdout,buff);
for(unsigned int j=0;j<strlen(buff);++j)
fprintf(stdout,"\b") ;
fflush(stdout) ;
}
#endif
try
{
PtrPrimitive p(primitives[pindex]) ;
gpc_polygon difference ;
gpc_polygon new_poly ;
gpc_polygon new_poly_reduced ;
new_poly.num_contours = 0 ;
new_poly.hole = NULL ;
new_poly.contour = NULL ;
new_poly_reduced.num_contours = 0 ;
new_poly_reduced.hole = NULL ;
new_poly_reduced.contour = NULL ;
// 1 - creates a gpc_polygon corresponding to the current primitive
gpc_vertex_list *new_poly_verts = new gpc_vertex_list ;
gpc_vertex_list *new_poly_reduced_verts = new gpc_vertex_list ;
double mx = 0.0 ;
double my = 0.0 ;
if(p->nbVertices() == 2)
{
new_poly_verts->num_vertices = 4 ;
new_poly_verts->vertex = new gpc_vertex[4] ;
new_poly_reduced_verts->num_vertices = 4 ;
new_poly_reduced_verts->vertex = new gpc_vertex[4] ;
double deps = 0.001 ;
double du = p->vertex(1).y()-p->vertex(0).y() ;
double dv = p->vertex(1).x()-p->vertex(0).x() ;
double n = sqrt(du*du+dv*dv) ;
du *= deps/n ;
dv *= deps/n ;
new_poly_verts->vertex[0].x = p->vertex(0).x() + du ;
new_poly_verts->vertex[0].y = p->vertex(0).y() + dv ;
new_poly_verts->vertex[1].x = p->vertex(1).x() + du ;
new_poly_verts->vertex[1].y = p->vertex(1).y() + dv ;
new_poly_verts->vertex[2].x = p->vertex(1).x() - du ;
new_poly_verts->vertex[2].y = p->vertex(1).y() - dv ;
new_poly_verts->vertex[3].x = p->vertex(0).x() - du ;
new_poly_verts->vertex[3].y = p->vertex(0).y() - dv ;
new_poly_reduced_verts->vertex[0].x = p->vertex(0).x() + du ;
new_poly_reduced_verts->vertex[0].y = p->vertex(0).y() + dv ;
new_poly_reduced_verts->vertex[1].x = p->vertex(1).x() + du ;
new_poly_reduced_verts->vertex[1].y = p->vertex(1).y() + dv ;
new_poly_reduced_verts->vertex[2].x = p->vertex(1).x() - du ;
new_poly_reduced_verts->vertex[2].y = p->vertex(1).y() - dv ;
new_poly_reduced_verts->vertex[3].x = p->vertex(0).x() - du ;
new_poly_reduced_verts->vertex[3].y = p->vertex(0).y() - dv ;
}
else
{
new_poly_verts->num_vertices = p->nbVertices() ;
new_poly_verts->vertex = new gpc_vertex[p->nbVertices()] ;
for(size_t i=0;i<p->nbVertices();++i)
{
new_poly_verts->vertex[i].x = p->vertex(i).x() ;
new_poly_verts->vertex[i].y = p->vertex(i).y() ;
mx += p->vertex(i).x() ;
my += p->vertex(i).y() ;
}
mx /= p->nbVertices() ;
my /= p->nbVertices() ;
new_poly_reduced_verts->num_vertices = p->nbVertices() ;
new_poly_reduced_verts->vertex = new gpc_vertex[p->nbVertices()] ;
for(size_t j=0;j<p->nbVertices();++j)
{
new_poly_reduced_verts->vertex[j].x = mx + (p->vertex(j).x() - mx)*0.999 ;
new_poly_reduced_verts->vertex[j].y = my + (p->vertex(j).y() - my)*0.999 ;
}
}
gpc_add_contour(&new_poly,new_poly_verts,false) ;
gpc_add_contour(&new_poly_reduced,new_poly_reduced_verts,false) ;
// 2 - computes the difference between this polygon, and the union of the
// preceeding ones.
gpc_polygon_clip(GPC_DIFF,&new_poly_reduced,&cumulated_union,&difference) ;
// 3 - checks the difference. If void, the primitive is not visible: skip it
// and go to next primitive.
if(difference.num_contours == 0)
{
++nb_culled ;
delete p ;
primitives[pindex] = NULL ;
continue ;
}
// 4 - The primitive is visible. Let's add it to the cumulated union of
// primitives.
if(p->nbVertices() > 2)
{
gpc_polygon cumulated_union_tmp ;
cumulated_union_tmp.num_contours = 0 ;
cumulated_union_tmp.hole = NULL ;
cumulated_union_tmp.contour = NULL ;
gpc_polygon_clip(GPC_UNION,&new_poly,&cumulated_union,&cumulated_union_tmp) ;
gpc_free_polygon(&cumulated_union) ;
cumulated_union = cumulated_union_tmp ;
}
gpc_free_polygon(&new_poly) ;
gpc_free_polygon(&new_poly_reduced) ;
gpc_free_polygon(&difference) ;
#ifdef DEBUG_EPSRENDER__SHOW1
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) ;
glColor3f(1.0,0.0,0.0) ;
for(unsigned long i=0;i<cumulated_union.num_contours;++i)
{
glBegin(GL_LINE_LOOP) ;
for(unsigned long j=0;j<cumulated_union.contour[i].num_vertices;++j)
glVertex2f(cumulated_union.contour[i].vertex[j].x,cumulated_union.contour[i].vertex[j].y) ;
glEnd() ;
}
glFlush() ;
glXSwapBuffers(glXGetCurrentDisplay(),glXGetCurrentDrawable()) ;
#endif
}
catch(exception& )
{
; // std::cout << "Could not treat primitive " << pindex << ": internal gpc error." << endl ;
}
}
if(nboptimised%N==0)
vparams.progress(nboptimised/(float)primitives.size(), QGLViewer::tr("Visibility optimization")) ;
}
#ifdef DEBUG_VO
cout << nb_culled << " primitives culled over " << primitives.size() << "." << endl ;
#endif
gpc_free_polygon(&cumulated_union) ;
}
| 14,215 | 50.507246 | 147 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/gpc.cpp | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
/*
===========================================================================
Project: Generic Polygon Clipper
A new algorithm for calculating the difference, intersection,
exclusive-or or union of arbitrary polygon sets.
File: gpc.c
Author: Alan Murta (email: [email protected])
Version: 2.32
Date: 17th December 2004
Copyright: (C) 1997-2004, Advanced Interfaces Group,
University of Manchester.
This software is free for non-commercial use. It may be copied,
modified, and redistributed provided that this copyright notice
is preserved on all copies. The intellectual property rights of
the algorithms used reside with the University of Manchester
Advanced Interfaces Group.
You may not use this software, in whole or in part, in support
of any commercial product without the express consent of the
author.
There is no warranty or other guarantee of fitness of this
software for any purpose. It is provided solely "as is".
===========================================================================
*/
/*
===========================================================================
Includes
===========================================================================
*/
#include <stdexcept>
#include "gpc.h"
#include <stdlib.h>
#include <float.h>
#include <math.h>
using namespace std ;
/*
===========================================================================
Constants
===========================================================================
*/
#ifndef TRUE
#define FALSE 0
#define TRUE 1
#endif
#define LEFT 0
#define RIGHT 1
#define ABOVE 0
#define BELOW 1
#define CLIP 0
#define SUBJ 1
#define INVERT_TRISTRIPS FALSE
/*
===========================================================================
Macros
===========================================================================
*/
#define EQ(a, b) (fabs((a) - (b)) <= GPC_EPSILON)
#define PREV_INDEX(i, n) ((i - 1 + n) % n)
#define NEXT_INDEX(i, n) ((i + 1 ) % n)
#define OPTIMAL(v, i, n) ((v[PREV_INDEX(i, n)].y != v[i].y) || \
(v[NEXT_INDEX(i, n)].y != v[i].y))
#define FWD_MIN(v, i, n) ((v[PREV_INDEX(i, n)].vertex.y >= v[i].vertex.y) \
&& (v[NEXT_INDEX(i, n)].vertex.y > v[i].vertex.y))
#define NOT_FMAX(v, i, n) (v[NEXT_INDEX(i, n)].vertex.y > v[i].vertex.y)
#define REV_MIN(v, i, n) ((v[PREV_INDEX(i, n)].vertex.y > v[i].vertex.y) \
&& (v[NEXT_INDEX(i, n)].vertex.y >= v[i].vertex.y))
#define NOT_RMAX(v, i, n) (v[PREV_INDEX(i, n)].vertex.y > v[i].vertex.y)
#define VERTEX(e,p,s,x,y) {add_vertex(&((e)->outp[(p)]->v[(s)]), x, y); \
(e)->outp[(p)]->active++;}
#define P_EDGE(d,e,p,i,j) {(d)= (e); \
do {(d)= (d)->prev;} while (!(d)->outp[(p)]); \
(i)= (d)->bot.x + (d)->dx * ((j)-(d)->bot.y);}
#define N_EDGE(d,e,p,i,j) {(d)= (e); \
do {(d)= (d)->next;} while (!(d)->outp[(p)]); \
(i)= (d)->bot.x + (d)->dx * ((j)-(d)->bot.y);}
#define MALLOC(p, b, s, t) {if ((b) > 0) { \
p= (t*)malloc(b); if (!(p)) { \
fprintf(stderr, "gpc malloc failure: %s\n", s); \
exit(0);}} else p= NULL;}
#define FREE(p) {if (p) {free(p); (p)= NULL;}}
/*
===========================================================================
Private Data Types
===========================================================================
*/
typedef enum /* Edge intersection classes */
{
NUL, /* Empty non-intersection */
EMX, /* External maximum */
ELI, /* External left intermediate */
TED, /* Top edge */
ERI, /* External right intermediate */
RED, /* Right edge */
IMM, /* Internal maximum and minimum */
IMN, /* Internal minimum */
EMN, /* External minimum */
EMM, /* External maximum and minimum */
LED, /* Left edge */
ILI, /* Internal left intermediate */
BED, /* Bottom edge */
IRI, /* Internal right intermediate */
IMX, /* Internal maximum */
FUL /* Full non-intersection */
} vertex_type;
typedef enum /* Horizontal edge states */
{
NH, /* No horizontal edge */
BH, /* Bottom horizontal edge */
TH /* Top horizontal edge */
} h_state;
typedef enum /* Edge bundle state */
{
UNBUNDLED, /* Isolated edge not within a bundle */
BUNDLE_HEAD, /* Bundle head node */
BUNDLE_TAIL /* Passive bundle tail node */
} bundle_state;
typedef struct v_shape /* Internal vertex list datatype */
{
double x; /* X coordinate component */
double y; /* Y coordinate component */
struct v_shape *next; /* Pointer to next vertex in list */
} vertex_node;
class polygon_node /* Internal contour / tristrip type */
{
public:
polygon_node(): next(0),proxy(0) { v[0]=0; v[1]=0; }
int active; /* Active flag / vertex count */
int hole; /* Hole / external contour flag */
vertex_node *v[2]; /* Left and right vertex list ptrs */
polygon_node *next; /* Pointer to next polygon contour */
polygon_node *proxy; /* Pointer to actual structure used */
} ;
class edge_node
{
public:
edge_node()
: prev(0),next(0),pred(0),succ(0),next_bound(0)
{
outp[0] = 0 ;
outp[1] = 0 ;
}
gpc_vertex vertex; /* Piggy-backed contour vertex data */
gpc_vertex bot; /* Edge lower (x, y) coordinate */
gpc_vertex top; /* Edge upper (x, y) coordinate */
double xb; /* Scanbeam bottom x coordinate */
double xt; /* Scanbeam top x coordinate */
double dx; /* Change in x for a unit y increase */
int type; /* Clip / subject edge flag */
int bundle[2][2]; /* Bundle edge flags */
int bside[2]; /* Bundle left / right indicators */
bundle_state bstate[2]; /* Edge bundle state */
polygon_node *outp[2]; /* Output polygon / tristrip pointer */
edge_node *prev; /* Previous edge in the AET */
edge_node *next; /* Next edge in the AET */
edge_node *pred; /* Edge connected at the lower end */
edge_node *succ; /* Edge connected at the upper end */
edge_node *next_bound; /* Pointer to next bound in LMT */
} ;
class lmt_node /* Local minima table */
{
public:
lmt_node() : first_bound(0),next(0) {}
double y; /* Y coordinate at local minimum */
edge_node *first_bound; /* Pointer to bound list */
lmt_node *next; /* Pointer to next local minimum */
} ;
typedef struct sbt_t_shape /* Scanbeam tree */
{
double y; /* Scanbeam node y value */
struct sbt_t_shape *less; /* Pointer to nodes with lower y */
struct sbt_t_shape *more; /* Pointer to nodes with higher y */
} sb_tree;
typedef struct it_shape /* Intersection table */
{
edge_node *ie[2]; /* Intersecting edge (bundle) pair */
gpc_vertex point; /* Point of intersection */
struct it_shape *next; /* The next intersection table node */
} it_node;
typedef struct st_shape /* Sorted edge table */
{
edge_node *edge; /* Pointer to AET edge */
double xb; /* Scanbeam bottom x coordinate */
double xt; /* Scanbeam top x coordinate */
double dx; /* Change in x for a unit y increase */
struct st_shape *prev; /* Previous edge in sorted list */
} st_node;
typedef struct bbox_shape /* Contour axis-aligned bounding box */
{
double xmin; /* Minimum x coordinate */
double ymin; /* Minimum y coordinate */
double xmax; /* Maximum x coordinate */
double ymax; /* Maximum y coordinate */
} bbox;
/*
===========================================================================
Global Data
===========================================================================
*/
/* Horizontal edge state transitions within scanbeam boundary */
const h_state next_h_state[3][6]=
{
/* ABOVE BELOW CROSS */
/* L R L R L R */
/* NH */ {BH, TH, TH, BH, NH, NH},
/* BH */ {NH, NH, NH, NH, TH, TH},
/* TH */ {NH, NH, NH, NH, BH, BH}
};
/*
===========================================================================
Private Functions
===========================================================================
*/
static void reset_it(it_node **it)
{
it_node *itn;
while (*it)
{
itn= (*it)->next;
FREE(*it);
*it= itn;
}
}
static void reset_lmt(lmt_node **lmt)
{
lmt_node *lmtn;
while (*lmt)
{
lmtn= (*lmt)->next;
FREE(*lmt);
*lmt= lmtn;
}
}
static void insert_bound(edge_node **b, edge_node *e)
{
edge_node *existing_bound;
if (!*b)
{
/* Link node e to the tail of the list */
*b= e;
}
else
{
/* Do primary sort on the x field */
if (e[0].bot.x < (*b)[0].bot.x)
{
/* Insert a new node mid-list */
existing_bound= *b;
*b= e;
(*b)->next_bound= existing_bound;
}
else
{
if (e[0].bot.x == (*b)[0].bot.x)
{
/* Do secondary sort on the dx field */
if (e[0].dx < (*b)[0].dx)
{
/* Insert a new node mid-list */
existing_bound= *b;
*b= e;
(*b)->next_bound= existing_bound;
}
else
{
/* Head further down the list */
insert_bound(&((*b)->next_bound), e);
}
}
else
{
/* Head further down the list */
insert_bound(&((*b)->next_bound), e);
}
}
}
}
static edge_node **bound_list(lmt_node **lmt, double y)
{
lmt_node *existing_node;
if (!*lmt)
{
/* Add node onto the tail end of the LMT */
MALLOC(*lmt, sizeof(lmt_node), "LMT insertion", lmt_node);
(*lmt)->y= y;
(*lmt)->first_bound= NULL;
(*lmt)->next= NULL;
return &((*lmt)->first_bound);
}
else
if (y < (*lmt)->y)
{
/* Insert a new LMT node before the current node */
existing_node= *lmt;
MALLOC(*lmt, sizeof(lmt_node), "LMT insertion", lmt_node);
(*lmt)->y= y;
(*lmt)->first_bound= NULL;
(*lmt)->next= existing_node;
return &((*lmt)->first_bound);
}
else
if (y > (*lmt)->y)
/* Head further up the LMT */
return bound_list(&((*lmt)->next), y);
else
/* Use this existing LMT node */
return &((*lmt)->first_bound);
}
static void add_to_sbtree(int *entries, sb_tree **sbtree, double y)
{
if (!*sbtree)
{
/* Add a new tree node here */
MALLOC(*sbtree, sizeof(sb_tree), "scanbeam tree insertion", sb_tree);
(*sbtree)->y= y;
(*sbtree)->less= NULL;
(*sbtree)->more= NULL;
(*entries)++;
}
else
{
if ((*sbtree)->y > y)
{
/* Head into the 'less' sub-tree */
add_to_sbtree(entries, &((*sbtree)->less), y);
}
else
{
if ((*sbtree)->y < y)
{
/* Head into the 'more' sub-tree */
add_to_sbtree(entries, &((*sbtree)->more), y);
}
}
}
}
static void build_sbt(int *entries, double *sbt, sb_tree *sbtree)
{
if (sbtree->less)
build_sbt(entries, sbt, sbtree->less);
sbt[*entries]= sbtree->y;
(*entries)++;
if (sbtree->more)
build_sbt(entries, sbt, sbtree->more);
}
static void free_sbtree(sb_tree **sbtree)
{
if (*sbtree)
{
free_sbtree(&((*sbtree)->less));
free_sbtree(&((*sbtree)->more));
FREE(*sbtree);
}
}
static int count_optimal_vertices(gpc_vertex_list c)
{
int result= 0;
/* Ignore non-contributing contours */
if (c.num_vertices > 0)
{
for (long i= 0; i < c.num_vertices; i++)
/* Ignore superfluous vertices embedded in horizontal edges */
if (OPTIMAL(c.vertex, i, c.num_vertices))
result++;
}
return result;
}
static edge_node *build_lmt(lmt_node **lmt, sb_tree **sbtree,
int *sbt_entries, gpc_polygon *p, int type,
gpc_op op)
{
int i, min, max, num_edges, v, num_vertices;
int total_vertices= 0, e_index=0;
edge_node *e, *edge_table;
for (size_t c= 0; c < p->num_contours; c++)
total_vertices+= count_optimal_vertices(p->contour[c]);
/* Create the entire input polygon edge table in one go */
MALLOC(edge_table, total_vertices * sizeof(edge_node), "edge table creation", edge_node);
for(int k=0;k<total_vertices;++k)
edge_table[k] = edge_node() ;
for (size_t c= 0; c < p->num_contours; c++)
{
if (p->contour[c].num_vertices < 0)
{
/* Ignore the non-contributing contour and repair the vertex count */
p->contour[c].num_vertices= -p->contour[c].num_vertices;
}
else
{
/* Perform contour optimisation */
num_vertices= 0;
for (i= 0; i < p->contour[c].num_vertices; i++)
if (OPTIMAL(p->contour[c].vertex, i, p->contour[c].num_vertices))
{
edge_table[num_vertices].vertex.x= p->contour[c].vertex[i].x;
edge_table[num_vertices].vertex.y= p->contour[c].vertex[i].y;
/* Record vertex in the scanbeam table */
add_to_sbtree(sbt_entries, sbtree,
edge_table[num_vertices].vertex.y);
num_vertices++;
}
/* Do the contour forward pass */
for (min= 0; min < num_vertices; min++)
{
/* If a forward local minimum... */
if (FWD_MIN(edge_table, min, num_vertices))
{
/* Search for the next local maximum... */
num_edges= 1;
max= NEXT_INDEX(min, num_vertices);
while (NOT_FMAX(edge_table, max, num_vertices))
{
num_edges++;
max= NEXT_INDEX(max, num_vertices);
}
/* Build the next edge list */
e= &edge_table[e_index];
e_index+= num_edges;
v= min;
e[0].bstate[BELOW]= UNBUNDLED;
e[0].bundle[BELOW][CLIP]= FALSE;
e[0].bundle[BELOW][SUBJ]= FALSE;
for (i= 0; i < num_edges; i++)
{
e[i].xb= edge_table[v].vertex.x;
e[i].bot.x= edge_table[v].vertex.x;
e[i].bot.y= edge_table[v].vertex.y;
v= NEXT_INDEX(v, num_vertices);
e[i].top.x= edge_table[v].vertex.x;
e[i].top.y= edge_table[v].vertex.y;
e[i].dx= (edge_table[v].vertex.x - e[i].bot.x) /
(e[i].top.y - e[i].bot.y);
e[i].type= type;
e[i].outp[ABOVE]= NULL;
e[i].outp[BELOW]= NULL;
e[i].next= NULL;
e[i].prev= NULL;
e[i].succ= ((num_edges > 1) && (i < (num_edges - 1))) ?
&(e[i + 1]) : NULL;
e[i].pred= ((num_edges > 1) && (i > 0)) ? &(e[i - 1]) : NULL;
e[i].next_bound= NULL;
e[i].bside[CLIP]= (op == GPC_DIFF) ? RIGHT : LEFT;
e[i].bside[SUBJ]= LEFT;
}
insert_bound(bound_list(lmt, edge_table[min].vertex.y), e);
}
}
/* Do the contour reverse pass */
for (min= 0; min < num_vertices; min++)
{
/* If a reverse local minimum... */
if (REV_MIN(edge_table, min, num_vertices))
{
/* Search for the previous local maximum... */
num_edges= 1;
max= PREV_INDEX(min, num_vertices);
while (NOT_RMAX(edge_table, max, num_vertices))
{
num_edges++;
max= PREV_INDEX(max, num_vertices);
}
/* Build the previous edge list */
e= &edge_table[e_index];
e_index+= num_edges;
v= min;
e[0].bstate[BELOW]= UNBUNDLED;
e[0].bundle[BELOW][CLIP]= FALSE;
e[0].bundle[BELOW][SUBJ]= FALSE;
for (i= 0; i < num_edges; i++)
{
e[i].xb= edge_table[v].vertex.x;
e[i].bot.x= edge_table[v].vertex.x;
e[i].bot.y= edge_table[v].vertex.y;
v= PREV_INDEX(v, num_vertices);
e[i].top.x= edge_table[v].vertex.x;
e[i].top.y= edge_table[v].vertex.y;
e[i].dx= (edge_table[v].vertex.x - e[i].bot.x) /
(e[i].top.y - e[i].bot.y);
e[i].type= type;
e[i].outp[ABOVE]= NULL;
e[i].outp[BELOW]= NULL;
e[i].next= NULL;
e[i].prev= NULL;
e[i].succ= ((num_edges > 1) && (i < (num_edges - 1))) ?
&(e[i + 1]) : NULL;
e[i].pred= ((num_edges > 1) && (i > 0)) ? &(e[i - 1]) : NULL;
e[i].next_bound= NULL;
e[i].bside[CLIP]= (op == GPC_DIFF) ? RIGHT : LEFT;
e[i].bside[SUBJ]= LEFT;
}
insert_bound(bound_list(lmt, edge_table[min].vertex.y), e);
}
}
}
}
return edge_table;
}
static void add_edge_to_aet(edge_node **aet, edge_node *edge, edge_node *prev)
{
if (!*aet)
{
/* Append edge onto the tail end of the AET */
*aet= edge;
edge->prev= prev;
edge->next= NULL;
}
else
{
/* Do primary sort on the xb field */
if (edge->xb < (*aet)->xb)
{
/* Insert edge here (before the AET edge) */
edge->prev= prev;
edge->next= *aet;
(*aet)->prev= edge;
*aet= edge;
}
else
{
if (edge->xb == (*aet)->xb)
{
/* Do secondary sort on the dx field */
if (edge->dx < (*aet)->dx)
{
/* Insert edge here (before the AET edge) */
edge->prev= prev;
edge->next= *aet;
(*aet)->prev= edge;
*aet= edge;
}
else
{
/* Head further into the AET */
add_edge_to_aet(&((*aet)->next), edge, *aet);
}
}
else
{
/* Head further into the AET */
add_edge_to_aet(&((*aet)->next), edge, *aet);
}
}
}
}
static void add_intersection(it_node **it, edge_node *edge0, edge_node *edge1,
double x, double y)
{
it_node *existing_node;
if (!*it)
{
/* Append a new node to the tail of the list */
MALLOC(*it, sizeof(it_node), "IT insertion", it_node);
(*it)->ie[0]= edge0;
(*it)->ie[1]= edge1;
(*it)->point.x= x;
(*it)->point.y= y;
(*it)->next= NULL;
}
else
{
if ((*it)->point.y > y)
{
/* Insert a new node mid-list */
existing_node= *it;
MALLOC(*it, sizeof(it_node), "IT insertion", it_node);
(*it)->ie[0]= edge0;
(*it)->ie[1]= edge1;
(*it)->point.x= x;
(*it)->point.y= y;
(*it)->next= existing_node;
}
else
/* Head further down the list */
add_intersection(&((*it)->next), edge0, edge1, x, y);
}
}
static void add_st_edge(st_node **st, it_node **it, edge_node *edge,
double dy)
{
st_node *existing_node;
double den, r, x, y;
if (!*st)
{
/* Append edge onto the tail end of the ST */
MALLOC(*st, sizeof(st_node), "ST insertion", st_node);
(*st)->edge= edge;
(*st)->xb= edge->xb;
(*st)->xt= edge->xt;
(*st)->dx= edge->dx;
(*st)->prev= NULL;
}
else
{
den= ((*st)->xt - (*st)->xb) - (edge->xt - edge->xb);
/* If new edge and ST edge don't cross */
if ((edge->xt >= (*st)->xt) || (edge->dx == (*st)->dx) ||
(fabs(den) <= DBL_EPSILON))
{
/* No intersection - insert edge here (before the ST edge) */
existing_node= *st;
MALLOC(*st, sizeof(st_node), "ST insertion", st_node);
(*st)->edge= edge;
(*st)->xb= edge->xb;
(*st)->xt= edge->xt;
(*st)->dx= edge->dx;
(*st)->prev= existing_node;
}
else
{
/* Compute intersection between new edge and ST edge */
r= (edge->xb - (*st)->xb) / den;
x= (*st)->xb + r * ((*st)->xt - (*st)->xb);
y= r * dy;
/* Insert the edge pointers and the intersection point in the IT */
add_intersection(it, (*st)->edge, edge, x, y);
/* Head further into the ST */
add_st_edge(&((*st)->prev), it, edge, dy);
}
}
}
static void build_intersection_table(it_node **it, edge_node *aet, double dy)
{
st_node *st, *stp;
edge_node *edge;
/* Build intersection table for the current scanbeam */
reset_it(it);
st= NULL;
/* Process each AET edge */
for (edge= aet; edge; edge= edge->next)
{
if ((edge->bstate[ABOVE] == BUNDLE_HEAD) ||
edge->bundle[ABOVE][CLIP] || edge->bundle[ABOVE][SUBJ])
add_st_edge(&st, it, edge, dy);
}
/* Free the sorted edge table */
while (st)
{
stp= st->prev;
FREE(st);
st= stp;
}
}
static int count_contours(polygon_node *polygon)
{
int nc, nv;
vertex_node *v, *nextv;
for (nc= 0; polygon; polygon= polygon->next)
if (polygon->active)
{
/* Count the vertices in the current contour */
nv= 0;
for (v= polygon->proxy->v[LEFT]; v; v= v->next)
nv++;
/* Record valid vertex counts in the active field */
if (nv > 2)
{
polygon->active= nv;
nc++;
}
else
{
/* Invalid contour: just free the heap */
for (v= polygon->proxy->v[LEFT]; v; v= nextv)
{
nextv= v->next;
FREE(v);
}
polygon->active= 0;
}
}
return nc;
}
static void add_left(polygon_node *p, double x, double y)
{
vertex_node *nv;
if(p == NULL) throw runtime_error("GPC: Something's wrong.") ;
/* Create a new vertex node and set its fields */
MALLOC(nv, sizeof(vertex_node), "vertex node creation", vertex_node);
nv->x= x;
nv->y= y;
/* Add vertex nv to the left end of the polygon's vertex list */
nv->next= p->proxy->v[LEFT];
/* Update proxy->[LEFT] to point to nv */
p->proxy->v[LEFT]= nv;
}
static void merge_left(polygon_node *p, polygon_node *q, polygon_node *list)
{
polygon_node *target;
if(p == NULL) throw runtime_error("GPC: Something's wrong.") ;
if(q == NULL) throw runtime_error("GPC: Something's wrong.") ;
/* Label contour as a hole */
q->proxy->hole= TRUE;
if (p->proxy != q->proxy)
{
/* Assign p's vertex list to the left end of q's list */
p->proxy->v[RIGHT]->next= q->proxy->v[LEFT];
q->proxy->v[LEFT]= p->proxy->v[LEFT];
/* Redirect any p->proxy references to q->proxy */
for (target= p->proxy; list; list= list->next)
{
if (list->proxy == target)
{
list->active= FALSE;
list->proxy= q->proxy;
}
}
}
}
static void add_right(polygon_node *p, double x, double y)
{
vertex_node *nv = 0;
if(p == NULL) throw runtime_error("GPC: Something's wrong.") ;
/* Create a new vertex node and set its fields */
MALLOC(nv, sizeof(vertex_node), "vertex node creation", vertex_node);
nv->x= x;
nv->y= y;
nv->next= NULL;
/* Add vertex nv to the right end of the polygon's vertex list */
p->proxy->v[RIGHT]->next= nv;
/* Update proxy->v[RIGHT] to point to nv */
p->proxy->v[RIGHT]= nv;
}
static void merge_right(polygon_node *p, polygon_node *q, polygon_node *list)
{
polygon_node *target = 0;
if(p == NULL) throw runtime_error("GPC: Something's wrong.") ;
if(q == NULL) throw runtime_error("GPC: Something's wrong.") ;
/* Label contour as external */
q->proxy->hole= FALSE;
if (p->proxy != q->proxy)
{
/* Assign p's vertex list to the right end of q's list */
q->proxy->v[RIGHT]->next= p->proxy->v[LEFT];
q->proxy->v[RIGHT]= p->proxy->v[RIGHT];
/* Redirect any p->proxy references to q->proxy */
for (target= p->proxy; list; list= list->next)
{
if (list->proxy == target)
{
list->active= FALSE;
list->proxy= q->proxy;
}
}
}
}
static void add_local_min(polygon_node **p, edge_node *edge,
double x, double y)
{
polygon_node *existing_min = 0;
vertex_node *nv;
existing_min= *p;
MALLOC(*p, sizeof(polygon_node), "polygon node creation", polygon_node);
**p = polygon_node() ;
/* Create a new vertex node and set its fields */
MALLOC(nv, sizeof(vertex_node), "vertex node creation", vertex_node);
*nv = vertex_node() ;
nv->x= x;
nv->y= y;
nv->next= NULL;
/* Initialise proxy to point to p itself */
(*p)->proxy= (*p);
(*p)->active= TRUE;
(*p)->next= existing_min;
/* Make v[LEFT] and v[RIGHT] point to new vertex nv */
(*p)->v[LEFT]= nv;
(*p)->v[RIGHT]= nv;
/* Assign polygon p to the edge */
edge->outp[ABOVE]= *p;
}
static int count_tristrips(polygon_node *tn)
{
int total;
for (total= 0; tn; tn= tn->next)
if (tn->active > 2)
total++;
return total;
}
static void add_vertex(vertex_node **t, double x, double y)
{
if (!(*t))
{
MALLOC(*t, sizeof(vertex_node), "tristrip vertex creation", vertex_node);
(*t)->x= x;
(*t)->y= y;
(*t)->next= NULL;
}
else
/* Head further down the list */
add_vertex(&((*t)->next), x, y);
}
static void new_tristrip(polygon_node **tn, edge_node *edge,
double x, double y)
{
if (!(*tn))
{
MALLOC(*tn, sizeof(polygon_node), "tristrip node creation", polygon_node);
**tn = polygon_node() ;
(*tn)->next= NULL;
(*tn)->v[LEFT]= NULL;
(*tn)->v[RIGHT]= NULL;
(*tn)->active= 1;
add_vertex(&((*tn)->v[LEFT]), x, y);
edge->outp[ABOVE]= *tn;
}
else
/* Head further down the list */
new_tristrip(&((*tn)->next), edge, x, y);
}
static bbox *create_contour_bboxes(gpc_polygon *p)
{
bbox *box;
int v;
MALLOC(box, p->num_contours * sizeof(bbox), "Bounding box creation", bbox);
/* Construct contour bounding boxes */
for (size_t c= 0; c < p->num_contours; c++)
{
/* Initialise bounding box extent */
box[c].xmin= DBL_MAX;
box[c].ymin= DBL_MAX;
box[c].xmax= -DBL_MAX;
box[c].ymax= -DBL_MAX;
for (v= 0; v < p->contour[c].num_vertices; v++)
{
/* Adjust bounding box */
if (p->contour[c].vertex[v].x < box[c].xmin)
box[c].xmin= p->contour[c].vertex[v].x;
if (p->contour[c].vertex[v].y < box[c].ymin)
box[c].ymin= p->contour[c].vertex[v].y;
if (p->contour[c].vertex[v].x > box[c].xmax)
box[c].xmax= p->contour[c].vertex[v].x;
if (p->contour[c].vertex[v].y > box[c].ymax)
box[c].ymax= p->contour[c].vertex[v].y;
}
}
return box;
}
static void minimax_test(gpc_polygon *subj, gpc_polygon *clip, gpc_op op)
{
bbox *s_bbox, *c_bbox;
int *o_table, overlap;
s_bbox= create_contour_bboxes(subj);
c_bbox= create_contour_bboxes(clip);
MALLOC(o_table, subj->num_contours * clip->num_contours * sizeof(int),
"overlap table creation", int);
/* Check all subject contour bounding boxes against clip boxes */
for (size_t s= 0; s < subj->num_contours; s++)
for (size_t c= 0; c < clip->num_contours; c++)
o_table[c * subj->num_contours + s]=
(!((s_bbox[s].xmax < c_bbox[c].xmin) ||
(s_bbox[s].xmin > c_bbox[c].xmax))) &&
(!((s_bbox[s].ymax < c_bbox[c].ymin) ||
(s_bbox[s].ymin > c_bbox[c].ymax)));
/* For each clip contour, search for any subject contour overlaps */
for (size_t c= 0; c < clip->num_contours; c++)
{
overlap= 0;
for (size_t s= 0; (!overlap) && (s < subj->num_contours); s++)
overlap= o_table[c * subj->num_contours + s];
if (!overlap)
/* Flag non contributing status by negating vertex count */
clip->contour[c].num_vertices = -clip->contour[c].num_vertices;
}
if (op == GPC_INT)
{
/* For each subject contour, search for any clip contour overlaps */
for (size_t s= 0; s < subj->num_contours; s++)
{
overlap= 0;
for (size_t c= 0; (!overlap) && (c < clip->num_contours); c++)
overlap= o_table[c * subj->num_contours + s];
if (!overlap)
/* Flag non contributing status by negating vertex count */
subj->contour[s].num_vertices = -subj->contour[s].num_vertices;
}
}
FREE(s_bbox);
FREE(c_bbox);
FREE(o_table);
}
/*
===========================================================================
Public Functions
===========================================================================
*/
void gpc_free_polygon(gpc_polygon *p)
{
for (size_t c= 0; c < p->num_contours; c++)
FREE(p->contour[c].vertex);
FREE(p->hole);
FREE(p->contour);
p->num_contours= 0;
}
/* Unused and fscanf creates compilation warnings
void gpc_read_polygon(FILE *fp, int read_hole_flags, gpc_polygon *p)
{
int c, v;
fscanf(fp, "%d", &(p->num_contours));
MALLOC(p->hole, p->num_contours * sizeof(int),
"hole flag array creation", int);
MALLOC(p->contour, p->num_contours
* sizeof(gpc_vertex_list), "contour creation", gpc_vertex_list);
for (c= 0; c < p->num_contours; c++)
{
fscanf(fp, "%d", &(p->contour[c].num_vertices));
if (read_hole_flags)
fscanf(fp, "%d", &(p->hole[c]));
else
p->hole[c]= FALSE; // Assume all contours to be external
MALLOC(p->contour[c].vertex, p->contour[c].num_vertices
* sizeof(gpc_vertex), "vertex creation", gpc_vertex);
for (v= 0; v < p->contour[c].num_vertices; v++)
fscanf(fp, "%lf %lf", &(p->contour[c].vertex[v].x),
&(p->contour[c].vertex[v].y));
}
}
*/
void gpc_write_polygon(FILE *fp, int write_hole_flags, gpc_polygon *p)
{
fprintf(fp, "%lu\n", p->num_contours);
for (size_t c= 0; c < p->num_contours; c++)
{
fprintf(fp, "%lu\n", p->contour[c].num_vertices);
if (write_hole_flags)
fprintf(fp, "%d\n", p->hole[c]);
for (long v= 0; v < p->contour[c].num_vertices; v++)
fprintf(fp, "% .*lf % .*lf\n",
DBL_DIG, p->contour[c].vertex[v].x,
DBL_DIG, p->contour[c].vertex[v].y);
}
}
void gpc_add_contour(gpc_polygon *p, gpc_vertex_list *new_contour, int hole)
{
int *extended_hole;
size_t c;
gpc_vertex_list *extended_contour;
/* Create an extended hole array */
MALLOC(extended_hole, (p->num_contours + 1)
* sizeof(int), "contour hole addition", int);
/* Create an extended contour array */
MALLOC(extended_contour, (p->num_contours + 1)
* sizeof(gpc_vertex_list), "contour addition", gpc_vertex_list);
/* Copy the old contour and hole data into the extended arrays */
for (c= 0; c < p->num_contours; c++)
{
extended_hole[c]= p->hole[c];
extended_contour[c]= p->contour[c];
}
/* Copy the new contour and hole onto the end of the extended arrays */
c= p->num_contours;
extended_hole[c]= hole;
extended_contour[c].num_vertices= new_contour->num_vertices;
MALLOC(extended_contour[c].vertex, new_contour->num_vertices
* sizeof(gpc_vertex), "contour addition", gpc_vertex);
for (long v= 0; v < new_contour->num_vertices; v++)
extended_contour[c].vertex[v]= new_contour->vertex[v];
/* Dispose of the old contour */
FREE(p->contour);
FREE(p->hole);
/* Update the polygon information */
p->num_contours++;
p->hole= extended_hole;
p->contour= extended_contour;
}
void gpc_polygon_clip(gpc_op op, gpc_polygon *subj, gpc_polygon *clip,
gpc_polygon *result)
{
sb_tree *sbtree= NULL;
it_node *it= NULL, *intersect=0;
edge_node *edge=0, *prev_edge=0, *next_edge=0, *succ_edge=0, *e0=0, *e1=0;
edge_node *aet= NULL, *c_heap= NULL, *s_heap= NULL;
lmt_node *lmt= NULL, *local_min=0;
polygon_node *out_poly= NULL, *p=0, *q=0, *poly=0, *npoly=0, *cf= NULL;
vertex_node *vtx=0, *nv=0;
h_state horiz[2];
int in[2], exists[2], parity[2]= {LEFT, LEFT};
int c, v, contributing=0, search, scanbeam= 0, sbt_entries= 0;
int vclass=0, bl=0, br=0, tl=0, tr=0;
double *sbt= NULL, xb, px, yb, yt=0.0, dy=0.0, ix, iy;
/* Test for trivial NULL result cases */
if (((subj->num_contours == 0) && (clip->num_contours == 0))
|| ((subj->num_contours == 0) && ((op == GPC_INT) || (op == GPC_DIFF)))
|| ((clip->num_contours == 0) && (op == GPC_INT)))
{
result->num_contours= 0;
result->hole= NULL;
result->contour= NULL;
return;
}
/* Identify potentialy contributing contours */
if (((op == GPC_INT) || (op == GPC_DIFF))
&& (subj->num_contours > 0) && (clip->num_contours > 0))
minimax_test(subj, clip, op);
/* Build LMT */
if (subj->num_contours > 0)
s_heap= build_lmt(&lmt, &sbtree, &sbt_entries, subj, SUBJ, op);
if (clip->num_contours > 0)
c_heap= build_lmt(&lmt, &sbtree, &sbt_entries, clip, CLIP, op);
/* Return a NULL result if no contours contribute */
if (lmt == NULL)
{
result->num_contours= 0;
result->hole= NULL;
result->contour= NULL;
reset_lmt(&lmt);
FREE(s_heap);
FREE(c_heap);
return;
}
/* Build scanbeam table from scanbeam tree */
MALLOC(sbt, sbt_entries * sizeof(double), "sbt creation", double);
build_sbt(&scanbeam, sbt, sbtree);
scanbeam= 0;
free_sbtree(&sbtree);
/* Allow pointer re-use without causing memory leak */
if (subj == result)
gpc_free_polygon(subj);
if (clip == result)
gpc_free_polygon(clip);
/* Invert clip polygon for difference operation */
if (op == GPC_DIFF)
parity[CLIP]= RIGHT;
local_min= lmt;
/* Process each scanbeam */
while (scanbeam < sbt_entries)
{
/* Set yb and yt to the bottom and top of the scanbeam */
yb= sbt[scanbeam++];
if (scanbeam < sbt_entries)
{
yt= sbt[scanbeam];
dy= yt - yb;
}
/* === SCANBEAM BOUNDARY PROCESSING ================================ */
/* If LMT node corresponding to yb exists */
if (local_min)
{
if (local_min->y == yb)
{
/* Add edges starting at this local minimum to the AET */
for (edge= local_min->first_bound; edge; edge= edge->next_bound)
add_edge_to_aet(&aet, edge, NULL);
local_min= local_min->next;
}
}
/* Set dummy previous x value */
px= -DBL_MAX;
/* Create bundles within AET */
e0= aet;
e1= aet;
/* Set up bundle fields of first edge */
aet->bundle[ABOVE][ aet->type]= (aet->top.y != yb);
aet->bundle[ABOVE][!aet->type]= FALSE;
aet->bstate[ABOVE]= UNBUNDLED;
for (next_edge= aet->next; next_edge; next_edge= next_edge->next)
{
/* Set up bundle fields of next edge */
next_edge->bundle[ABOVE][ next_edge->type]= (next_edge->top.y != yb);
next_edge->bundle[ABOVE][!next_edge->type]= FALSE;
next_edge->bstate[ABOVE]= UNBUNDLED;
/* Bundle edges above the scanbeam boundary if they coincide */
if (next_edge->bundle[ABOVE][next_edge->type])
{
if (EQ(e0->xb, next_edge->xb) && EQ(e0->dx, next_edge->dx)
&& (e0->top.y != yb))
{
next_edge->bundle[ABOVE][ next_edge->type]^=
e0->bundle[ABOVE][ next_edge->type];
next_edge->bundle[ABOVE][!next_edge->type]=
e0->bundle[ABOVE][!next_edge->type];
next_edge->bstate[ABOVE]= BUNDLE_HEAD;
e0->bundle[ABOVE][CLIP]= FALSE;
e0->bundle[ABOVE][SUBJ]= FALSE;
e0->bstate[ABOVE]= BUNDLE_TAIL;
}
e0= next_edge;
}
}
horiz[CLIP]= NH;
horiz[SUBJ]= NH;
/* Process each edge at this scanbeam boundary */
for (edge= aet; edge; edge= edge->next)
{
exists[CLIP]= edge->bundle[ABOVE][CLIP] +
(edge->bundle[BELOW][CLIP] << 1);
exists[SUBJ]= edge->bundle[ABOVE][SUBJ] +
(edge->bundle[BELOW][SUBJ] << 1);
if (exists[CLIP] || exists[SUBJ])
{
/* Set bundle side */
edge->bside[CLIP]= parity[CLIP];
edge->bside[SUBJ]= parity[SUBJ];
/* Determine contributing status and quadrant occupancies */
switch (op)
{
case GPC_DIFF:
case GPC_INT:
contributing= (exists[CLIP] && (parity[SUBJ] || horiz[SUBJ]))
|| (exists[SUBJ] && (parity[CLIP] || horiz[CLIP]))
|| (exists[CLIP] && exists[SUBJ]
&& (parity[CLIP] == parity[SUBJ]));
br= (parity[CLIP])
&& (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
&& (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
&& (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
&& (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
case GPC_XOR:
contributing= exists[CLIP] || exists[SUBJ];
br= (parity[CLIP])
^ (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
^ (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
^ (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
^ (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
case GPC_UNION:
contributing= (exists[CLIP] && (!parity[SUBJ] || horiz[SUBJ]))
|| (exists[SUBJ] && (!parity[CLIP] || horiz[CLIP]))
|| (exists[CLIP] && exists[SUBJ]
&& (parity[CLIP] == parity[SUBJ]));
br= (parity[CLIP])
|| (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
|| (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
|| (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
|| (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
}
/* Update parity */
parity[CLIP]^= edge->bundle[ABOVE][CLIP];
parity[SUBJ]^= edge->bundle[ABOVE][SUBJ];
/* Update horizontal state */
if (exists[CLIP])
horiz[CLIP]=
next_h_state[horiz[CLIP]]
[((exists[CLIP] - 1) << 1) + parity[CLIP]];
if (exists[SUBJ])
horiz[SUBJ]=
next_h_state[horiz[SUBJ]]
[((exists[SUBJ] - 1) << 1) + parity[SUBJ]];
vclass= tr + (tl << 1) + (br << 2) + (bl << 3);
if (contributing)
{
xb= edge->xb;
switch (vclass)
{
case EMN:
case IMN:
add_local_min(&out_poly, edge, xb, yb);
px= xb;
cf= edge->outp[ABOVE];
break;
case ERI:
if (xb != px)
{
add_right(cf, xb, yb);
px= xb;
}
edge->outp[ABOVE]= cf;
cf= NULL;
break;
case ELI:
add_left(edge->outp[BELOW], xb, yb);
px= xb;
cf= edge->outp[BELOW];
break;
case EMX:
if (xb != px)
{
add_left(cf, xb, yb);
px= xb;
}
merge_right(cf, edge->outp[BELOW], out_poly);
cf= NULL;
break;
case ILI:
if (xb != px)
{
add_left(cf, xb, yb);
px= xb;
}
edge->outp[ABOVE]= cf;
cf= NULL;
break;
case IRI:
add_right(edge->outp[BELOW], xb, yb);
px= xb;
cf= edge->outp[BELOW];
edge->outp[BELOW]= NULL;
break;
case IMX:
if (xb != px)
{
add_right(cf, xb, yb);
px= xb;
}
merge_left(cf, edge->outp[BELOW], out_poly);
cf= NULL;
edge->outp[BELOW]= NULL;
break;
case IMM:
if (xb != px)
{
add_right(cf, xb, yb);
px= xb;
}
merge_left(cf, edge->outp[BELOW], out_poly);
edge->outp[BELOW]= NULL;
add_local_min(&out_poly, edge, xb, yb);
cf= edge->outp[ABOVE];
break;
case EMM:
if (xb != px)
{
add_left(cf, xb, yb);
px= xb;
}
merge_right(cf, edge->outp[BELOW], out_poly);
edge->outp[BELOW]= NULL;
add_local_min(&out_poly, edge, xb, yb);
cf= edge->outp[ABOVE];
break;
case LED:
if (edge->bot.y == yb)
add_left(edge->outp[BELOW], xb, yb);
edge->outp[ABOVE]= edge->outp[BELOW];
px= xb;
break;
case RED:
if (edge->bot.y == yb)
add_right(edge->outp[BELOW], xb, yb);
edge->outp[ABOVE]= edge->outp[BELOW];
px= xb;
break;
default:
break;
} /* End of switch */
} /* End of contributing conditional */
} /* End of edge exists conditional */
} /* End of AET loop */
/* Delete terminating edges from the AET, otherwise compute xt */
for (edge= aet; edge; edge= edge->next)
{
if (edge->top.y == yb)
{
prev_edge= edge->prev;
next_edge= edge->next;
if (prev_edge)
prev_edge->next= next_edge;
else
aet= next_edge;
if (next_edge)
next_edge->prev= prev_edge;
/* Copy bundle head state to the adjacent tail edge if required */
if ((edge->bstate[BELOW] == BUNDLE_HEAD) && prev_edge)
{
if (prev_edge->bstate[BELOW] == BUNDLE_TAIL)
{
prev_edge->outp[BELOW]= edge->outp[BELOW];
prev_edge->bstate[BELOW]= UNBUNDLED;
if (prev_edge->prev)
if (prev_edge->prev->bstate[BELOW] == BUNDLE_TAIL)
prev_edge->bstate[BELOW]= BUNDLE_HEAD;
}
}
}
else
{
if (edge->top.y == yt)
edge->xt= edge->top.x;
else
edge->xt= edge->bot.x + edge->dx * (yt - edge->bot.y);
}
}
if (scanbeam < sbt_entries)
{
/* === SCANBEAM INTERIOR PROCESSING ============================== */
build_intersection_table(&it, aet, dy);
/* Process each node in the intersection table */
for (intersect= it; intersect; intersect= intersect->next)
{
e0= intersect->ie[0];
e1= intersect->ie[1];
/* Only generate output for contributing intersections */
if ((e0->bundle[ABOVE][CLIP] || e0->bundle[ABOVE][SUBJ])
&& (e1->bundle[ABOVE][CLIP] || e1->bundle[ABOVE][SUBJ]))
{
p= e0->outp[ABOVE];
q= e1->outp[ABOVE];
ix= intersect->point.x;
iy= intersect->point.y + yb;
in[CLIP]= ( e0->bundle[ABOVE][CLIP] && !e0->bside[CLIP])
|| ( e1->bundle[ABOVE][CLIP] && e1->bside[CLIP])
|| (!e0->bundle[ABOVE][CLIP] && !e1->bundle[ABOVE][CLIP]
&& e0->bside[CLIP] && e1->bside[CLIP]);
in[SUBJ]= ( e0->bundle[ABOVE][SUBJ] && !e0->bside[SUBJ])
|| ( e1->bundle[ABOVE][SUBJ] && e1->bside[SUBJ])
|| (!e0->bundle[ABOVE][SUBJ] && !e1->bundle[ABOVE][SUBJ]
&& e0->bside[SUBJ] && e1->bside[SUBJ]);
/* Determine quadrant occupancies */
switch (op)
{
case GPC_DIFF:
case GPC_INT:
tr= (in[CLIP])
&& (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
case GPC_XOR:
tr= (in[CLIP])
^ (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
case GPC_UNION:
tr= (in[CLIP])
|| (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
}
vclass= tr + (tl << 1) + (br << 2) + (bl << 3);
switch (vclass)
{
case EMN:
add_local_min(&out_poly, e0, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
break;
case ERI:
if (p)
{
add_right(p, ix, iy);
e1->outp[ABOVE]= p;
e0->outp[ABOVE]= NULL;
}
break;
case ELI:
if (q)
{
add_left(q, ix, iy);
e0->outp[ABOVE]= q;
e1->outp[ABOVE]= NULL;
}
break;
case EMX:
if (p && q)
{
add_left(p, ix, iy);
merge_right(p, q, out_poly);
e0->outp[ABOVE]= NULL;
e1->outp[ABOVE]= NULL;
}
break;
case IMN:
add_local_min(&out_poly, e0, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
break;
case ILI:
if (p)
{
add_left(p, ix, iy);
e1->outp[ABOVE]= p;
e0->outp[ABOVE]= NULL;
}
break;
case IRI:
if (q)
{
add_right(q, ix, iy);
e0->outp[ABOVE]= q;
e1->outp[ABOVE]= NULL;
}
break;
case IMX:
if (p && q)
{
add_right(p, ix, iy);
merge_left(p, q, out_poly);
e0->outp[ABOVE]= NULL;
e1->outp[ABOVE]= NULL;
}
break;
case IMM:
if (p && q)
{
add_right(p, ix, iy);
merge_left(p, q, out_poly);
add_local_min(&out_poly, e0, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
}
break;
case EMM:
if (p && q)
{
add_left(p, ix, iy);
merge_right(p, q, out_poly);
add_local_min(&out_poly, e0, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
}
break;
default:
break;
} /* End of switch */
} /* End of contributing intersection conditional */
/* Swap bundle sides in response to edge crossing */
if (e0->bundle[ABOVE][CLIP])
e1->bside[CLIP]= !e1->bside[CLIP];
if (e1->bundle[ABOVE][CLIP])
e0->bside[CLIP]= !e0->bside[CLIP];
if (e0->bundle[ABOVE][SUBJ])
e1->bside[SUBJ]= !e1->bside[SUBJ];
if (e1->bundle[ABOVE][SUBJ])
e0->bside[SUBJ]= !e0->bside[SUBJ];
/* Swap e0 and e1 bundles in the AET */
prev_edge= e0->prev;
next_edge= e1->next;
if (next_edge)
next_edge->prev= e0;
if (e0->bstate[ABOVE] == BUNDLE_HEAD)
{
search= TRUE;
while (search)
{
prev_edge= prev_edge->prev;
if (prev_edge)
{
if (prev_edge->bstate[ABOVE] != BUNDLE_TAIL)
search= FALSE;
}
else
search= FALSE;
}
}
if (!prev_edge)
{
aet->prev= e1;
e1->next= aet;
aet= e0->next;
}
else
{
prev_edge->next->prev= e1;
e1->next= prev_edge->next;
prev_edge->next= e0->next;
}
if(e0->next == NULL) throw runtime_error("GPC internal error.") ;
if(e1->next == NULL) throw runtime_error("GPC internal error.") ;
e0->next->prev= prev_edge;
e1->next->prev= e1;
e0->next= next_edge;
} /* End of IT loop*/
/* Prepare for next scanbeam */
for (edge= aet; edge; edge= next_edge)
{
next_edge= edge->next;
succ_edge= edge->succ;
if ((edge->top.y == yt) && succ_edge)
{
/* Replace AET edge by its successor */
succ_edge->outp[BELOW]= edge->outp[ABOVE];
succ_edge->bstate[BELOW]= edge->bstate[ABOVE];
succ_edge->bundle[BELOW][CLIP]= edge->bundle[ABOVE][CLIP];
succ_edge->bundle[BELOW][SUBJ]= edge->bundle[ABOVE][SUBJ];
prev_edge= edge->prev;
if (prev_edge)
prev_edge->next= succ_edge;
else
aet= succ_edge;
if (next_edge)
next_edge->prev= succ_edge;
succ_edge->prev= prev_edge;
succ_edge->next= next_edge;
}
else
{
/* Update this edge */
edge->outp[BELOW]= edge->outp[ABOVE];
edge->bstate[BELOW]= edge->bstate[ABOVE];
edge->bundle[BELOW][CLIP]= edge->bundle[ABOVE][CLIP];
edge->bundle[BELOW][SUBJ]= edge->bundle[ABOVE][SUBJ];
edge->xb= edge->xt;
}
edge->outp[ABOVE]= NULL;
}
}
} /* === END OF SCANBEAM PROCESSING ================================== */
/* Generate result polygon from out_poly */
result->contour= NULL;
result->hole= NULL;
result->num_contours= count_contours(out_poly);
if (result->num_contours > 0)
{
MALLOC(result->hole, result->num_contours
* sizeof(int), "hole flag table creation", int);
MALLOC(result->contour, result->num_contours
* sizeof(gpc_vertex_list), "contour creation", gpc_vertex_list);
c= 0;
for (poly= out_poly; poly; poly= npoly)
{
npoly= poly->next;
if (poly->active)
{
result->hole[c]= poly->proxy->hole;
result->contour[c].num_vertices= poly->active;
MALLOC(result->contour[c].vertex,
result->contour[c].num_vertices * sizeof(gpc_vertex),
"vertex creation", gpc_vertex);
v= result->contour[c].num_vertices - 1;
for (vtx= poly->proxy->v[LEFT]; vtx; vtx= nv)
{
nv= vtx->next;
result->contour[c].vertex[v].x= vtx->x;
result->contour[c].vertex[v].y= vtx->y;
FREE(vtx);
v--;
}
c++;
}
FREE(poly);
}
}
else
{
for (poly= out_poly; poly; poly= npoly)
{
npoly= poly->next;
FREE(poly);
}
}
/* Tidy up */
reset_it(&it);
reset_lmt(&lmt);
FREE(c_heap);
FREE(s_heap);
FREE(sbt);
}
void gpc_free_tristrip(gpc_tristrip *t)
{
for (size_t s= 0; s < t->num_strips; s++)
FREE(t->strip[s].vertex);
FREE(t->strip);
t->num_strips= 0;
}
void gpc_polygon_to_tristrip(gpc_polygon *s, gpc_tristrip *t)
{
gpc_polygon c;
c.num_contours= 0;
c.hole= NULL;
c.contour= NULL;
gpc_tristrip_clip(GPC_DIFF, s, &c, t);
}
void gpc_tristrip_clip(gpc_op op, gpc_polygon *subj, gpc_polygon *clip,
gpc_tristrip *result)
{
sb_tree *sbtree= NULL;
it_node *it= NULL, *intersect;
edge_node *edge=0, *prev_edge=0, *next_edge=0, *succ_edge=0, *e0=0, *e1=0;
edge_node *aet= NULL, *c_heap= NULL, *s_heap= NULL, *cf=0;
lmt_node *lmt= NULL, *local_min;
polygon_node *tlist= NULL, *tn, *tnn, *p, *q;
vertex_node *lt, *ltn, *rt, *rtn;
h_state horiz[2];
vertex_type cft = NUL;
int in[2], exists[2], parity[2]= {LEFT, LEFT};
int s, v, contributing=0, search, scanbeam= 0, sbt_entries= 0;
int vclass=0, bl=0, br=0, tl=0, tr=0;
double *sbt= NULL, xb, px, nx, yb, yt=0.0, dy=0.0, ix, iy;
/* Test for trivial NULL result cases */
if (((subj->num_contours == 0) && (clip->num_contours == 0))
|| ((subj->num_contours == 0) && ((op == GPC_INT) || (op == GPC_DIFF)))
|| ((clip->num_contours == 0) && (op == GPC_INT)))
{
result->num_strips= 0;
result->strip= NULL;
return;
}
/* Identify potentialy contributing contours */
if (((op == GPC_INT) || (op == GPC_DIFF))
&& (subj->num_contours > 0) && (clip->num_contours > 0))
minimax_test(subj, clip, op);
/* Build LMT */
if (subj->num_contours > 0)
s_heap= build_lmt(&lmt, &sbtree, &sbt_entries, subj, SUBJ, op);
if (clip->num_contours > 0)
c_heap= build_lmt(&lmt, &sbtree, &sbt_entries, clip, CLIP, op);
/* Return a NULL result if no contours contribute */
if (lmt == NULL)
{
result->num_strips= 0;
result->strip= NULL;
reset_lmt(&lmt);
FREE(s_heap);
FREE(c_heap);
return;
}
/* Build scanbeam table from scanbeam tree */
MALLOC(sbt, sbt_entries * sizeof(double), "sbt creation", double);
build_sbt(&scanbeam, sbt, sbtree);
scanbeam= 0;
free_sbtree(&sbtree);
/* Invert clip polygon for difference operation */
if (op == GPC_DIFF)
parity[CLIP]= RIGHT;
local_min= lmt;
/* Process each scanbeam */
while (scanbeam < sbt_entries)
{
/* Set yb and yt to the bottom and top of the scanbeam */
yb= sbt[scanbeam++];
if (scanbeam < sbt_entries)
{
yt= sbt[scanbeam];
dy= yt - yb;
}
/* === SCANBEAM BOUNDARY PROCESSING ================================ */
/* If LMT node corresponding to yb exists */
if (local_min)
{
if (local_min->y == yb)
{
/* Add edges starting at this local minimum to the AET */
for (edge= local_min->first_bound; edge; edge= edge->next_bound)
add_edge_to_aet(&aet, edge, NULL);
local_min= local_min->next;
}
}
/* Set dummy previous x value */
px= -DBL_MAX;
/* Create bundles within AET */
e0= aet;
e1= aet;
/* Set up bundle fields of first edge */
aet->bundle[ABOVE][ aet->type]= (aet->top.y != yb);
aet->bundle[ABOVE][!aet->type]= FALSE;
aet->bstate[ABOVE]= UNBUNDLED;
for (next_edge= aet->next; next_edge; next_edge= next_edge->next)
{
/* Set up bundle fields of next edge */
next_edge->bundle[ABOVE][ next_edge->type]= (next_edge->top.y != yb);
next_edge->bundle[ABOVE][!next_edge->type]= FALSE;
next_edge->bstate[ABOVE]= UNBUNDLED;
/* Bundle edges above the scanbeam boundary if they coincide */
if (next_edge->bundle[ABOVE][next_edge->type])
{
if (EQ(e0->xb, next_edge->xb) && EQ(e0->dx, next_edge->dx)
&& (e0->top.y != yb))
{
next_edge->bundle[ABOVE][ next_edge->type]^=
e0->bundle[ABOVE][ next_edge->type];
next_edge->bundle[ABOVE][!next_edge->type]=
e0->bundle[ABOVE][!next_edge->type];
next_edge->bstate[ABOVE]= BUNDLE_HEAD;
e0->bundle[ABOVE][CLIP]= FALSE;
e0->bundle[ABOVE][SUBJ]= FALSE;
e0->bstate[ABOVE]= BUNDLE_TAIL;
}
e0= next_edge;
}
}
horiz[CLIP]= NH;
horiz[SUBJ]= NH;
/* Process each edge at this scanbeam boundary */
for (edge= aet; edge; edge= edge->next)
{
exists[CLIP]= edge->bundle[ABOVE][CLIP] +
(edge->bundle[BELOW][CLIP] << 1);
exists[SUBJ]= edge->bundle[ABOVE][SUBJ] +
(edge->bundle[BELOW][SUBJ] << 1);
if (exists[CLIP] || exists[SUBJ])
{
/* Set bundle side */
edge->bside[CLIP]= parity[CLIP];
edge->bside[SUBJ]= parity[SUBJ];
/* Determine contributing status and quadrant occupancies */
switch (op)
{
case GPC_DIFF:
case GPC_INT:
contributing= (exists[CLIP] && (parity[SUBJ] || horiz[SUBJ]))
|| (exists[SUBJ] && (parity[CLIP] || horiz[CLIP]))
|| (exists[CLIP] && exists[SUBJ]
&& (parity[CLIP] == parity[SUBJ]));
br= (parity[CLIP])
&& (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
&& (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
&& (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
&& (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
case GPC_XOR:
contributing= exists[CLIP] || exists[SUBJ];
br= (parity[CLIP])
^ (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
^ (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
^ (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
^ (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
case GPC_UNION:
contributing= (exists[CLIP] && (!parity[SUBJ] || horiz[SUBJ]))
|| (exists[SUBJ] && (!parity[CLIP] || horiz[CLIP]))
|| (exists[CLIP] && exists[SUBJ]
&& (parity[CLIP] == parity[SUBJ]));
br= (parity[CLIP])
|| (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
|| (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
|| (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
|| (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
}
/* Update parity */
parity[CLIP]^= edge->bundle[ABOVE][CLIP];
parity[SUBJ]^= edge->bundle[ABOVE][SUBJ];
/* Update horizontal state */
if (exists[CLIP])
horiz[CLIP]=
next_h_state[horiz[CLIP]]
[((exists[CLIP] - 1) << 1) + parity[CLIP]];
if (exists[SUBJ])
horiz[SUBJ]=
next_h_state[horiz[SUBJ]]
[((exists[SUBJ] - 1) << 1) + parity[SUBJ]];
vclass= tr + (tl << 1) + (br << 2) + (bl << 3);
if (contributing)
{
xb= edge->xb;
switch (vclass)
{
case EMN:
new_tristrip(&tlist, edge, xb, yb);
cf= edge;
break;
case ERI:
edge->outp[ABOVE]= cf->outp[ABOVE];
if (xb != cf->xb)
VERTEX(edge, ABOVE, RIGHT, xb, yb);
cf= NULL;
break;
case ELI:
VERTEX(edge, BELOW, LEFT, xb, yb);
edge->outp[ABOVE]= NULL;
cf= edge;
break;
case EMX:
if (xb != cf->xb)
VERTEX(edge, BELOW, RIGHT, xb, yb);
edge->outp[ABOVE]= NULL;
cf= NULL;
break;
case IMN:
if (cft == LED)
{
if (cf->bot.y != yb)
VERTEX(cf, BELOW, LEFT, cf->xb, yb);
new_tristrip(&tlist, cf, cf->xb, yb);
}
edge->outp[ABOVE]= cf->outp[ABOVE];
VERTEX(edge, ABOVE, RIGHT, xb, yb);
break;
case ILI:
new_tristrip(&tlist, edge, xb, yb);
cf= edge;
cft= ILI;
break;
case IRI:
if (cft == LED)
{
if (cf->bot.y != yb)
VERTEX(cf, BELOW, LEFT, cf->xb, yb);
new_tristrip(&tlist, cf, cf->xb, yb);
}
VERTEX(edge, BELOW, RIGHT, xb, yb);
edge->outp[ABOVE]= NULL;
break;
case IMX:
VERTEX(edge, BELOW, LEFT, xb, yb);
edge->outp[ABOVE]= NULL;
cft= IMX;
break;
case IMM:
VERTEX(edge, BELOW, LEFT, xb, yb);
edge->outp[ABOVE]= cf->outp[ABOVE];
if (xb != cf->xb)
VERTEX(cf, ABOVE, RIGHT, xb, yb);
cf= edge;
break;
case EMM:
VERTEX(edge, BELOW, RIGHT, xb, yb);
edge->outp[ABOVE]= NULL;
new_tristrip(&tlist, edge, xb, yb);
cf= edge;
break;
case LED:
if (edge->bot.y == yb)
VERTEX(edge, BELOW, LEFT, xb, yb);
edge->outp[ABOVE]= edge->outp[BELOW];
cf= edge;
cft= LED;
break;
case RED:
edge->outp[ABOVE]= cf->outp[ABOVE];
if (cft == LED)
{
if (cf->bot.y == yb)
{
VERTEX(edge, BELOW, RIGHT, xb, yb);
}
else
{
if (edge->bot.y == yb)
{
VERTEX(cf, BELOW, LEFT, cf->xb, yb);
VERTEX(edge, BELOW, RIGHT, xb, yb);
}
}
}
else
{
VERTEX(edge, BELOW, RIGHT, xb, yb);
VERTEX(edge, ABOVE, RIGHT, xb, yb);
}
cf= NULL;
break;
default:
break;
} /* End of switch */
} /* End of contributing conditional */
} /* End of edge exists conditional */
} /* End of AET loop */
/* Delete terminating edges from the AET, otherwise compute xt */
for (edge= aet; edge; edge= edge->next)
{
if (edge->top.y == yb)
{
prev_edge= edge->prev;
next_edge= edge->next;
if (prev_edge)
prev_edge->next= next_edge;
else
aet= next_edge;
if (next_edge)
next_edge->prev= prev_edge;
/* Copy bundle head state to the adjacent tail edge if required */
if ((edge->bstate[BELOW] == BUNDLE_HEAD) && prev_edge)
{
if (prev_edge->bstate[BELOW] == BUNDLE_TAIL)
{
prev_edge->outp[BELOW]= edge->outp[BELOW];
prev_edge->bstate[BELOW]= UNBUNDLED;
if (prev_edge->prev)
if (prev_edge->prev->bstate[BELOW] == BUNDLE_TAIL)
prev_edge->bstate[BELOW]= BUNDLE_HEAD;
}
}
}
else
{
if (edge->top.y == yt)
edge->xt= edge->top.x;
else
edge->xt= edge->bot.x + edge->dx * (yt - edge->bot.y);
}
}
if (scanbeam < sbt_entries)
{
/* === SCANBEAM INTERIOR PROCESSING ============================== */
build_intersection_table(&it, aet, dy);
/* Process each node in the intersection table */
for (intersect= it; intersect; intersect= intersect->next)
{
e0= intersect->ie[0];
e1= intersect->ie[1];
/* Only generate output for contributing intersections */
if ((e0->bundle[ABOVE][CLIP] || e0->bundle[ABOVE][SUBJ])
&& (e1->bundle[ABOVE][CLIP] || e1->bundle[ABOVE][SUBJ]))
{
p= e0->outp[ABOVE];
q= e1->outp[ABOVE];
ix= intersect->point.x;
iy= intersect->point.y + yb;
in[CLIP]= ( e0->bundle[ABOVE][CLIP] && !e0->bside[CLIP])
|| ( e1->bundle[ABOVE][CLIP] && e1->bside[CLIP])
|| (!e0->bundle[ABOVE][CLIP] && !e1->bundle[ABOVE][CLIP]
&& e0->bside[CLIP] && e1->bside[CLIP]);
in[SUBJ]= ( e0->bundle[ABOVE][SUBJ] && !e0->bside[SUBJ])
|| ( e1->bundle[ABOVE][SUBJ] && e1->bside[SUBJ])
|| (!e0->bundle[ABOVE][SUBJ] && !e1->bundle[ABOVE][SUBJ]
&& e0->bside[SUBJ] && e1->bside[SUBJ]);
/* Determine quadrant occupancies */
switch (op)
{
case GPC_DIFF:
case GPC_INT:
tr= (in[CLIP])
&& (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
case GPC_XOR:
tr= (in[CLIP])
^ (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
case GPC_UNION:
tr= (in[CLIP])
|| (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
}
vclass= tr + (tl << 1) + (br << 2) + (bl << 3);
switch (vclass)
{
case EMN:
new_tristrip(&tlist, e1, ix, iy);
e0->outp[ABOVE]= e1->outp[ABOVE];
break;
case ERI:
if (p)
{
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
VERTEX(e0, ABOVE, RIGHT, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
e0->outp[ABOVE]= NULL;
}
break;
case ELI:
if (q)
{
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(e1, ABOVE, LEFT, ix, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
e0->outp[ABOVE]= e1->outp[ABOVE];
e1->outp[ABOVE]= NULL;
}
break;
case EMX:
if (p && q)
{
VERTEX(e0, ABOVE, LEFT, ix, iy);
e0->outp[ABOVE]= NULL;
e1->outp[ABOVE]= NULL;
}
break;
case IMN:
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
new_tristrip(&tlist, prev_edge, px, iy);
e1->outp[ABOVE]= prev_edge->outp[ABOVE];
VERTEX(e1, ABOVE, RIGHT, ix, iy);
new_tristrip(&tlist, e0, ix, iy);
next_edge->outp[ABOVE]= e0->outp[ABOVE];
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
break;
case ILI:
if (p)
{
VERTEX(e0, ABOVE, LEFT, ix, iy);
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
e0->outp[ABOVE]= NULL;
}
break;
case IRI:
if (q)
{
VERTEX(e1, ABOVE, RIGHT, ix, iy);
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
e0->outp[ABOVE]= e1->outp[ABOVE];
e1->outp[ABOVE]= NULL;
}
break;
case IMX:
if (p && q)
{
VERTEX(e0, ABOVE, RIGHT, ix, iy);
VERTEX(e1, ABOVE, LEFT, ix, iy);
e0->outp[ABOVE]= NULL;
e1->outp[ABOVE]= NULL;
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
new_tristrip(&tlist, prev_edge, px, iy);
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
next_edge->outp[ABOVE]= prev_edge->outp[ABOVE];
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
}
break;
case IMM:
if (p && q)
{
VERTEX(e0, ABOVE, RIGHT, ix, iy);
VERTEX(e1, ABOVE, LEFT, ix, iy);
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
new_tristrip(&tlist, prev_edge, px, iy);
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
e1->outp[ABOVE]= prev_edge->outp[ABOVE];
VERTEX(e1, ABOVE, RIGHT, ix, iy);
new_tristrip(&tlist, e0, ix, iy);
next_edge->outp[ABOVE]= e0->outp[ABOVE];
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
}
break;
case EMM:
if (p && q)
{
VERTEX(e0, ABOVE, LEFT, ix, iy);
new_tristrip(&tlist, e1, ix, iy);
e0->outp[ABOVE]= e1->outp[ABOVE];
}
break;
default:
break;
} /* End of switch */
} /* End of contributing intersection conditional */
/* Swap bundle sides in response to edge crossing */
if (e0->bundle[ABOVE][CLIP])
e1->bside[CLIP]= !e1->bside[CLIP];
if (e1->bundle[ABOVE][CLIP])
e0->bside[CLIP]= !e0->bside[CLIP];
if (e0->bundle[ABOVE][SUBJ])
e1->bside[SUBJ]= !e1->bside[SUBJ];
if (e1->bundle[ABOVE][SUBJ])
e0->bside[SUBJ]= !e0->bside[SUBJ];
/* Swap e0 and e1 bundles in the AET */
prev_edge= e0->prev;
next_edge= e1->next;
if (e1->next)
e1->next->prev= e0;
if (e0->bstate[ABOVE] == BUNDLE_HEAD)
{
search= TRUE;
while (search)
{
prev_edge= prev_edge->prev;
if (prev_edge)
{
if (prev_edge->bundle[ABOVE][CLIP]
|| prev_edge->bundle[ABOVE][SUBJ]
|| (prev_edge->bstate[ABOVE] == BUNDLE_HEAD))
search= FALSE;
}
else
search= FALSE;
}
}
if (!prev_edge)
{
e1->next= aet;
aet= e0->next;
}
else
{
e1->next= prev_edge->next;
prev_edge->next= e0->next;
}
e0->next->prev= prev_edge;
e1->next->prev= e1;
e0->next= next_edge;
} /* End of IT loop*/
/* Prepare for next scanbeam */
for (edge= aet; edge; edge= next_edge)
{
next_edge= edge->next;
succ_edge= edge->succ;
if ((edge->top.y == yt) && succ_edge)
{
/* Replace AET edge by its successor */
succ_edge->outp[BELOW]= edge->outp[ABOVE];
succ_edge->bstate[BELOW]= edge->bstate[ABOVE];
succ_edge->bundle[BELOW][CLIP]= edge->bundle[ABOVE][CLIP];
succ_edge->bundle[BELOW][SUBJ]= edge->bundle[ABOVE][SUBJ];
prev_edge= edge->prev;
if (prev_edge)
prev_edge->next= succ_edge;
else
aet= succ_edge;
if (next_edge)
next_edge->prev= succ_edge;
succ_edge->prev= prev_edge;
succ_edge->next= next_edge;
}
else
{
/* Update this edge */
edge->outp[BELOW]= edge->outp[ABOVE];
edge->bstate[BELOW]= edge->bstate[ABOVE];
edge->bundle[BELOW][CLIP]= edge->bundle[ABOVE][CLIP];
edge->bundle[BELOW][SUBJ]= edge->bundle[ABOVE][SUBJ];
edge->xb= edge->xt;
}
edge->outp[ABOVE]= NULL;
}
}
} /* === END OF SCANBEAM PROCESSING ================================== */
/* Generate result tristrip from tlist */
result->strip= NULL;
result->num_strips= count_tristrips(tlist);
if (result->num_strips > 0)
{
MALLOC(result->strip, result->num_strips * sizeof(gpc_vertex_list),
"tristrip list creation", gpc_vertex_list);
s= 0;
for (tn= tlist; tn; tn= tnn)
{
tnn= tn->next;
if (tn->active > 2)
{
/* Valid tristrip: copy the vertices and free the heap */
result->strip[s].num_vertices= tn->active;
MALLOC(result->strip[s].vertex, tn->active * sizeof(gpc_vertex),
"tristrip creation", gpc_vertex);
v= 0;
if (INVERT_TRISTRIPS)
{
lt= tn->v[RIGHT];
rt= tn->v[LEFT];
}
else
{
lt= tn->v[LEFT];
rt= tn->v[RIGHT];
}
while (lt || rt)
{
if (lt)
{
ltn= lt->next;
result->strip[s].vertex[v].x= lt->x;
result->strip[s].vertex[v].y= lt->y;
v++;
FREE(lt);
lt= ltn;
}
if (rt)
{
rtn= rt->next;
result->strip[s].vertex[v].x= rt->x;
result->strip[s].vertex[v].y= rt->y;
v++;
FREE(rt);
rt= rtn;
}
}
s++;
}
else
{
/* Invalid tristrip: just free the heap */
for (lt= tn->v[LEFT]; lt; lt= ltn)
{
ltn= lt->next;
FREE(lt);
}
for (rt= tn->v[RIGHT]; rt; rt=rtn)
{
rtn= rt->next;
FREE(rt);
}
}
FREE(tn);
}
}
/* Tidy up */
reset_it(&it);
reset_lmt(&lmt);
FREE(c_heap);
FREE(s_heap);
FREE(sbt);
}
/*
===========================================================================
End of file: gpc.c
===========================================================================
*/
| 67,922 | 25.688802 | 91 | cpp |
octomap | octomap-master/octovis/src/extern/QGLViewer/VRender/gpc.h | /*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler ([email protected])
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - [email protected]
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
/*
===========================================================================
Project: Generic Polygon Clipper
A new algorithm for calculating the difference, intersection,
exclusive-or or union of arbitrary polygon sets.
File: gpc.h
Author: Alan Murta (email: [email protected])
Version: 2.32
Date: 17th December 2004
Copyright: (C) 1997-2004, Advanced Interfaces Group,
University of Manchester.
This software is free for non-commercial use. It may be copied,
modified, and redistributed provided that this copyright notice
is preserved on all copies. The intellectual property rights of
the algorithms used reside with the University of Manchester
Advanced Interfaces Group.
You may not use this software, in whole or in part, in support
of any commercial product without the express consent of the
author.
There is no warranty or other guarantee of fitness of this
software for any purpose. It is provided solely "as is".
===========================================================================
*/
#ifndef __gpc_h
#define __gpc_h
#include <stdio.h>
/*
===========================================================================
Constants
===========================================================================
*/
/* Increase GPC_EPSILON to encourage merging of near coincident edges */
//#define GPC_EPSILON (DBL_EPSILON)
#define GPC_EPSILON 1e-7
#define GPC_VERSION "2.32"
/*
===========================================================================
Public Data Types
===========================================================================
*/
typedef enum /* Set operation type */
{
GPC_DIFF, /* Difference */
GPC_INT, /* Intersection */
GPC_XOR, /* Exclusive or */
GPC_UNION /* Union */
} gpc_op;
typedef struct /* Polygon vertex structure */
{
double x; /* Vertex x component */
double y; /* vertex y component */
} gpc_vertex;
typedef struct /* Vertex list structure */
{
long num_vertices; /* Number of vertices in list */
gpc_vertex *vertex; /* Vertex array pointer */
} gpc_vertex_list;
typedef struct /* Polygon set structure */
{
unsigned long num_contours; /* Number of contours in polygon */
int *hole; /* Hole / external contour flags */
gpc_vertex_list *contour; /* Contour array pointer */
} gpc_polygon;
typedef struct /* Tristrip set structure */
{
unsigned long num_strips; /* Number of tristrips */
gpc_vertex_list *strip; /* Tristrip array pointer */
} gpc_tristrip;
/*
===========================================================================
Public Function Prototypes
===========================================================================
*/
void gpc_read_polygon (FILE *infile_ptr,
int read_hole_flags,
gpc_polygon *polygon);
void gpc_write_polygon (FILE *outfile_ptr,
int write_hole_flags,
gpc_polygon *polygon);
void gpc_add_contour (gpc_polygon *polygon,
gpc_vertex_list *contour,
int hole);
void gpc_polygon_clip (gpc_op set_operation,
gpc_polygon *subject_polygon,
gpc_polygon *clip_polygon,
gpc_polygon *result_polygon);
void gpc_tristrip_clip (gpc_op set_operation,
gpc_polygon *subject_polygon,
gpc_polygon *clip_polygon,
gpc_tristrip *result_tristrip);
void gpc_polygon_to_tristrip (gpc_polygon *polygon,
gpc_tristrip *tristrip);
void gpc_free_polygon (gpc_polygon *polygon);
void gpc_free_tristrip (gpc_tristrip *tristrip);
#endif
/*
===========================================================================
End of file: gpc.h
===========================================================================
*/
| 6,364 | 34.361111 | 78 | h |
octomap | octomap-master/scripts/travis_build_jobs.sh | #!/bin/bash
# travis build script for test compilations
set -e
function build {
cd $1
mkdir build
cd build
cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/octomap/$1
make -j4
cd ..
}
case "$1" in
"dist")
build .
cd build && make test
make install
;;
"components")
build octomap
cd build && make test
make install
cd ../..
build dynamicEDT3D
cd ..
build octovis
cd ..
;;
*)
echo "Invalid build variant"
exit 1
esac
| 453 | 10.35 | 49 | sh |
mmsegmentation | mmsegmentation-master/.circleci/scripts/get_mmcv_var.sh | #!/bin/bash
TORCH=$1
CUDA=$2
# 10.2 -> cu102
MMCV_CUDA="cu`echo ${CUDA} | tr -d '.'`"
# MMCV only provides pre-compiled packages for torch 1.x.0
# which works for any subversions of torch 1.x.
# We force the torch version to be 1.x.0 to ease package searching
# and avoid unnecessary rebuild during MMCV's installation.
TORCH_VER_ARR=(${TORCH//./ })
TORCH_VER_ARR[2]=0
printf -v MMCV_TORCH "%s." "${TORCH_VER_ARR[@]}"
MMCV_TORCH=${MMCV_TORCH%?} # Remove the last dot
echo "export MMCV_CUDA=${MMCV_CUDA}" >> $BASH_ENV
echo "export MMCV_TORCH=${MMCV_TORCH}" >> $BASH_ENV
| 574 | 27.75 | 66 | sh |
mmsegmentation | mmsegmentation-master/.dev/benchmark_evaluation.sh | PARTITION=$1
CHECKPOINT_DIR=$2
echo 'configs/hrnet/fcn_hr18s_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION fcn_hr18s_512x512_160k_ade20k configs/hrnet/fcn_hr18s_512x512_160k_ade20k.py $CHECKPOINT_DIR/fcn_hr18s_512x512_160k_ade20k_20200614_214413-870f65ac.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/fcn_hr18s_512x512_160k_ade20k --cfg-options dist_params.port=28171 &
echo 'configs/hrnet/fcn_hr18s_512x1024_160k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION fcn_hr18s_512x1024_160k_cityscapes configs/hrnet/fcn_hr18s_512x1024_160k_cityscapes.py $CHECKPOINT_DIR/fcn_hr18s_512x1024_160k_cityscapes_20200602_190901-4a0797ea.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/fcn_hr18s_512x1024_160k_cityscapes --cfg-options dist_params.port=28172 &
echo 'configs/hrnet/fcn_hr48_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION fcn_hr48_512x512_160k_ade20k configs/hrnet/fcn_hr48_512x512_160k_ade20k.py $CHECKPOINT_DIR/fcn_hr48_512x512_160k_ade20k_20200614_214407-a52fc02c.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/fcn_hr48_512x512_160k_ade20k --cfg-options dist_params.port=28173 &
echo 'configs/hrnet/fcn_hr48_512x1024_160k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION fcn_hr48_512x1024_160k_cityscapes configs/hrnet/fcn_hr48_512x1024_160k_cityscapes.py $CHECKPOINT_DIR/fcn_hr48_512x1024_160k_cityscapes_20200602_190946-59b7973e.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/fcn_hr48_512x1024_160k_cityscapes --cfg-options dist_params.port=28174 &
echo 'configs/pspnet/pspnet_r50-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION pspnet_r50-d8_512x1024_80k_cityscapes configs/pspnet/pspnet_r50-d8_512x1024_80k_cityscapes.py $CHECKPOINT_DIR/pspnet_r50-d8_512x1024_80k_cityscapes_20200606_112131-2376f12b.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/pspnet_r50-d8_512x1024_80k_cityscapes --cfg-options dist_params.port=28175 &
echo 'configs/pspnet/pspnet_r101-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION pspnet_r101-d8_512x1024_80k_cityscapes configs/pspnet/pspnet_r101-d8_512x1024_80k_cityscapes.py $CHECKPOINT_DIR/pspnet_r101-d8_512x1024_80k_cityscapes_20200606_112211-e1e1100f.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/pspnet_r101-d8_512x1024_80k_cityscapes --cfg-options dist_params.port=28176 &
echo 'configs/pspnet/pspnet_r101-d8_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION pspnet_r101-d8_512x512_160k_ade20k configs/pspnet/pspnet_r101-d8_512x512_160k_ade20k.py $CHECKPOINT_DIR/pspnet_r101-d8_512x512_160k_ade20k_20200615_100650-967c316f.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/pspnet_r101-d8_512x512_160k_ade20k --cfg-options dist_params.port=28177 &
echo 'configs/pspnet/pspnet_r50-d8_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION pspnet_r50-d8_512x512_160k_ade20k configs/pspnet/pspnet_r50-d8_512x512_160k_ade20k.py $CHECKPOINT_DIR/pspnet_r50-d8_512x512_160k_ade20k_20200615_184358-1890b0bd.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/pspnet_r50-d8_512x512_160k_ade20k --cfg-options dist_params.port=28178 &
echo 'configs/resnest/pspnet_s101-d8_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION pspnet_s101-d8_512x512_160k_ade20k configs/resnest/pspnet_s101-d8_512x512_160k_ade20k.py $CHECKPOINT_DIR/pspnet_s101-d8_512x512_160k_ade20k_20200807_145416-a6daa92a.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/pspnet_s101-d8_512x512_160k_ade20k --cfg-options dist_params.port=28179 &
echo 'configs/resnest/pspnet_s101-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION pspnet_s101-d8_512x1024_80k_cityscapes configs/resnest/pspnet_s101-d8_512x1024_80k_cityscapes.py $CHECKPOINT_DIR/pspnet_s101-d8_512x1024_80k_cityscapes_20200807_140631-c75f3b99.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/pspnet_s101-d8_512x1024_80k_cityscapes --cfg-options dist_params.port=28180 &
echo 'configs/fastscnn/fast_scnn_lr0.12_8x4_160k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION fast_scnn_lr0.12_8x4_160k_cityscapes configs/fastscnn/fast_scnn_lr0.12_8x4_160k_cityscapes.py $CHECKPOINT_DIR/fast_scnn_8x4_160k_lr0.12_cityscapes-0cec9937.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/fast_scnn_lr0.12_8x4_160k_cityscapes --cfg-options dist_params.port=28181 &
echo 'configs/deeplabv3plus/deeplabv3plus_r101-d8_769x769_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION deeplabv3plus_r101-d8_769x769_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r101-d8_769x769_80k_cityscapes.py $CHECKPOINT_DIR/deeplabv3plus_r101-d8_769x769_80k_cityscapes_20200607_000405-a7573d20.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/deeplabv3plus_r101-d8_769x769_80k_cityscapes --cfg-options dist_params.port=28182 &
echo 'configs/deeplabv3plus/deeplabv3plus_r101-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION deeplabv3plus_r101-d8_512x1024_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r101-d8_512x1024_80k_cityscapes.py $CHECKPOINT_DIR/deeplabv3plus_r101-d8_512x1024_80k_cityscapes_20200606_114143-068fcfe9.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/deeplabv3plus_r101-d8_512x1024_80k_cityscapes --cfg-options dist_params.port=28183 &
echo 'configs/deeplabv3plus/deeplabv3plus_r50-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION deeplabv3plus_r50-d8_512x1024_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r50-d8_512x1024_80k_cityscapes.py $CHECKPOINT_DIR/deeplabv3plus_r50-d8_512x1024_80k_cityscapes_20200606_114049-f9fb496d.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/deeplabv3plus_r50-d8_512x1024_80k_cityscapes --cfg-options dist_params.port=28184 &
echo 'configs/deeplabv3plus/deeplabv3plus_r50-d8_769x769_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION deeplabv3plus_r50-d8_769x769_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r50-d8_769x769_80k_cityscapes.py $CHECKPOINT_DIR/deeplabv3plus_r50-d8_769x769_80k_cityscapes_20200606_210233-0e9dfdc4.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/deeplabv3plus_r50-d8_769x769_80k_cityscapes --cfg-options dist_params.port=28185 &
echo 'configs/vit/upernet_vit-b16_ln_mln_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION upernet_vit-b16_ln_mln_512x512_160k_ade20k configs/vit/upernet_vit-b16_ln_mln_512x512_160k_ade20k.py $CHECKPOINT_DIR/upernet_vit-b16_ln_mln_512x512_160k_ade20k-f444c077.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/upernet_vit-b16_ln_mln_512x512_160k_ade20k --cfg-options dist_params.port=28186 &
echo 'configs/vit/upernet_deit-s16_ln_mln_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION upernet_deit-s16_ln_mln_512x512_160k_ade20k configs/vit/upernet_deit-s16_ln_mln_512x512_160k_ade20k.py $CHECKPOINT_DIR/upernet_deit-s16_ln_mln_512x512_160k_ade20k-c0cd652f.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/upernet_deit-s16_ln_mln_512x512_160k_ade20k --cfg-options dist_params.port=28187 &
echo 'configs/deeplabv3plus/deeplabv3plus_r101-d8_fp16_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION deeplabv3plus_r101-d8_fp16_512x1024_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r101-d8_fp16_512x1024_80k_cityscapes.py $CHECKPOINT_DIR/deeplabv3plus_r101-d8_512x1024_80k_fp16_cityscapes-cc58bc8d.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/deeplabv3plus_r101-d8_512x1024_80k_fp16_cityscapes --cfg-options dist_params.port=28188 &
echo 'configs/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 tools/slurm_test.sh $PARTITION upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K configs/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K.py $CHECKPOINT_DIR/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth --eval mIoU --work-dir work_dirs/benchmark_evaluation/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K --cfg-options dist_params.port=28189 &
| 8,747 | 207.285714 | 517 | sh |
mmsegmentation | mmsegmentation-master/.dev/benchmark_train.sh | PARTITION=$1
echo 'configs/hrnet/fcn_hr18s_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION fcn_hr18s_512x512_160k_ade20k configs/hrnet/fcn_hr18s_512x512_160k_ade20k.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24727 --work-dir work_dirs/hrnet/fcn_hr18s_512x512_160k_ade20k >/dev/null &
echo 'configs/hrnet/fcn_hr18s_512x1024_160k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION fcn_hr18s_512x1024_160k_cityscapes configs/hrnet/fcn_hr18s_512x1024_160k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24728 --work-dir work_dirs/hrnet/fcn_hr18s_512x1024_160k_cityscapes >/dev/null &
echo 'configs/hrnet/fcn_hr48_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION fcn_hr48_512x512_160k_ade20k configs/hrnet/fcn_hr48_512x512_160k_ade20k.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24729 --work-dir work_dirs/hrnet/fcn_hr48_512x512_160k_ade20k >/dev/null &
echo 'configs/hrnet/fcn_hr48_512x1024_160k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION fcn_hr48_512x1024_160k_cityscapes configs/hrnet/fcn_hr48_512x1024_160k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24730 --work-dir work_dirs/hrnet/fcn_hr48_512x1024_160k_cityscapes >/dev/null &
echo 'configs/pspnet/pspnet_r50-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION pspnet_r50-d8_512x1024_80k_cityscapes configs/pspnet/pspnet_r50-d8_512x1024_80k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24731 --work-dir work_dirs/pspnet/pspnet_r50-d8_512x1024_80k_cityscapes >/dev/null &
echo 'configs/pspnet/pspnet_r101-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION pspnet_r101-d8_512x1024_80k_cityscapes configs/pspnet/pspnet_r101-d8_512x1024_80k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24732 --work-dir work_dirs/pspnet/pspnet_r101-d8_512x1024_80k_cityscapes >/dev/null &
echo 'configs/pspnet/pspnet_r101-d8_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION pspnet_r101-d8_512x512_160k_ade20k configs/pspnet/pspnet_r101-d8_512x512_160k_ade20k.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24733 --work-dir work_dirs/pspnet/pspnet_r101-d8_512x512_160k_ade20k >/dev/null &
echo 'configs/pspnet/pspnet_r50-d8_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION pspnet_r50-d8_512x512_160k_ade20k configs/pspnet/pspnet_r50-d8_512x512_160k_ade20k.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24734 --work-dir work_dirs/pspnet/pspnet_r50-d8_512x512_160k_ade20k >/dev/null &
echo 'configs/resnest/pspnet_s101-d8_512x512_160k_ade20k.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION pspnet_s101-d8_512x512_160k_ade20k configs/resnest/pspnet_s101-d8_512x512_160k_ade20k.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24735 --work-dir work_dirs/resnest/pspnet_s101-d8_512x512_160k_ade20k >/dev/null &
echo 'configs/resnest/pspnet_s101-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION pspnet_s101-d8_512x1024_80k_cityscapes configs/resnest/pspnet_s101-d8_512x1024_80k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24736 --work-dir work_dirs/resnest/pspnet_s101-d8_512x1024_80k_cityscapes >/dev/null &
echo 'configs/fastscnn/fast_scnn_lr0.12_8x4_160k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION fast_scnn_lr0.12_8x4_160k_cityscapes configs/fastscnn/fast_scnn_lr0.12_8x4_160k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24737 --work-dir work_dirs/fastscnn/fast_scnn_lr0.12_8x4_160k_cityscapes >/dev/null &
echo 'configs/deeplabv3plus/deeplabv3plus_r101-d8_769x769_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION deeplabv3plus_r101-d8_769x769_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r101-d8_769x769_80k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24738 --work-dir work_dirs/deeplabv3plus/deeplabv3plus_r101-d8_769x769_80k_cityscapes >/dev/null &
echo 'configs/deeplabv3plus/deeplabv3plus_r101-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION deeplabv3plus_r101-d8_512x1024_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r101-d8_512x1024_80k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24739 --work-dir work_dirs/deeplabv3plus/deeplabv3plus_r101-d8_512x1024_80k_cityscapes >/dev/null &
echo 'configs/deeplabv3plus/deeplabv3plus_r50-d8_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION deeplabv3plus_r50-d8_512x1024_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r50-d8_512x1024_80k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24740 --work-dir work_dirs/deeplabv3plus/deeplabv3plus_r50-d8_512x1024_80k_cityscapes >/dev/null &
echo 'configs/deeplabv3plus/deeplabv3plus_r50-d8_769x769_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION deeplabv3plus_r50-d8_769x769_80k_cityscapes configs/deeplabv3plus/deeplabv3plus_r50-d8_769x769_80k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24741 --work-dir work_dirs/deeplabv3plus/deeplabv3plus_r50-d8_769x769_80k_cityscapes >/dev/null &
echo 'configs/vit/upernet_vit-b16_ln_mln_512x512_160k_ade20k.py' &
GPUS=8 GPUS_PER_NODE=8 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION upernet_vit-b16_ln_mln_512x512_160k_ade20k configs/vit/upernet_vit-b16_ln_mln_512x512_160k_ade20k.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24742 --work-dir work_dirs/vit/upernet_vit-b16_ln_mln_512x512_160k_ade20k >/dev/null &
echo 'configs/vit/upernet_deit-s16_ln_mln_512x512_160k_ade20k.py' &
GPUS=8 GPUS_PER_NODE=8 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION upernet_deit-s16_ln_mln_512x512_160k_ade20k configs/vit/upernet_deit-s16_ln_mln_512x512_160k_ade20k.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24743 --work-dir work_dirs/vit/upernet_deit-s16_ln_mln_512x512_160k_ade20k >/dev/null &
echo 'configs/deeplabv3plus/deeplabv3plus_r101-d8_fp16_512x1024_80k_cityscapes.py' &
GPUS=4 GPUS_PER_NODE=4 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION deeplabv3plus_r101-d8_512x1024_80k_fp16_cityscapes configs/deeplabv3plus/deeplabv3plus_r101-d8_fp16_512x1024_80k_cityscapes.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24744 --work-dir work_dirs/deeplabv3plus/deeplabv3plus_r101-d8_512x1024_80k_fp16_cityscapes >/dev/null &
echo 'configs/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K.py' &
GPUS=8 GPUS_PER_NODE=8 CPUS_PER_TASK=2 ./tools/slurm_train.sh $PARTITION upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K configs/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K.py --cfg-options checkpoint_config.max_keep_ckpts=1 dist_params.port=24745 --work-dir work_dirs/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K >/dev/null &
| 7,626 | 185.02439 | 420 | sh |
mmsegmentation | mmsegmentation-master/docker/serve/entrypoint.sh | #!/bin/bash
set -e
if [[ "$1" = "serve" ]]; then
shift 1
torchserve --start --ts-config /home/model-server/config.properties
else
eval "$@"
fi
# prevent docker exit
tail -f /dev/null
| 197 | 14.230769 | 71 | sh |
mmsegmentation | mmsegmentation-master/tools/dist_test.sh | CONFIG=$1
CHECKPOINT=$2
GPUS=$3
NNODES=${NNODES:-1}
NODE_RANK=${NODE_RANK:-0}
PORT=${PORT:-29500}
MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"}
PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \
python -m torch.distributed.launch \
--nnodes=$NNODES \
--node_rank=$NODE_RANK \
--master_addr=$MASTER_ADDR \
--nproc_per_node=$GPUS \
--master_port=$PORT \
$(dirname "$0")/test.py \
$CONFIG \
$CHECKPOINT \
--launcher pytorch \
${@:4}
| 458 | 20.857143 | 43 | sh |
mmsegmentation | mmsegmentation-master/tools/dist_train.sh | CONFIG=$1
GPUS=$2
NNODES=${NNODES:-1}
NODE_RANK=${NODE_RANK:-0}
PORT=${PORT:-29500}
MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"}
PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \
python -m torch.distributed.launch \
--nnodes=$NNODES \
--node_rank=$NODE_RANK \
--master_addr=$MASTER_ADDR \
--nproc_per_node=$GPUS \
--master_port=$PORT \
$(dirname "$0")/train.py \
$CONFIG \
--launcher pytorch ${@:3}
| 421 | 22.444444 | 43 | sh |
mmsegmentation | mmsegmentation-master/tools/slurm_test.sh | #!/usr/bin/env bash
set -x
PARTITION=$1
JOB_NAME=$2
CONFIG=$3
CHECKPOINT=$4
GPUS=${GPUS:-4}
GPUS_PER_NODE=${GPUS_PER_NODE:-4}
CPUS_PER_TASK=${CPUS_PER_TASK:-5}
PY_ARGS=${@:5}
SRUN_ARGS=${SRUN_ARGS:-""}
PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \
srun -p ${PARTITION} \
--job-name=${JOB_NAME} \
--gres=gpu:${GPUS_PER_NODE} \
--ntasks=${GPUS} \
--ntasks-per-node=${GPUS_PER_NODE} \
--cpus-per-task=${CPUS_PER_TASK} \
--kill-on-bad-exit=1 \
${SRUN_ARGS} \
python -u tools/test.py ${CONFIG} ${CHECKPOINT} --launcher="slurm" ${PY_ARGS}
| 566 | 21.68 | 81 | sh |
mmsegmentation | mmsegmentation-master/tools/slurm_train.sh | #!/usr/bin/env bash
set -x
PARTITION=$1
JOB_NAME=$2
CONFIG=$3
GPUS=${GPUS:-4}
GPUS_PER_NODE=${GPUS_PER_NODE:-4}
CPUS_PER_TASK=${CPUS_PER_TASK:-5}
SRUN_ARGS=${SRUN_ARGS:-""}
PY_ARGS=${@:4}
PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \
srun -p ${PARTITION} \
--job-name=${JOB_NAME} \
--gres=gpu:${GPUS_PER_NODE} \
--ntasks=${GPUS} \
--ntasks-per-node=${GPUS_PER_NODE} \
--cpus-per-task=${CPUS_PER_TASK} \
--kill-on-bad-exit=1 \
${SRUN_ARGS} \
python -u tools/train.py ${CONFIG} --launcher="slurm" ${PY_ARGS}
| 539 | 21.5 | 68 | sh |
smartbugs | smartbugs-master/.github/github_results.sh | #!/bin/bash
# Run .github/github_results.sh from SmartBugs home directory
# Generates .github/results-ubuntu.csv, needed for the workflow ubuntu.yml
# as a reference for comparing the results of the workflow with
#rm -rf results/*/github-sol
./smartbugs -t all -f 'samples/SimpleDAO.sol' --runid github-sol --sarif --main --timeout 180
./results2csv -x start duration -- results/*/github-sol | sed '/confuzzius/s/".*"//' > .github/results-ubuntu-sol.csv
#rm -rf results/*/github-rt
./smartbugs -t all -f 'samples/SimpleDAO.rt.hex' --runid github-rt --sarif --timeout 180
./results2csv -x start duration -- results/*/github-rt > .github/results-ubuntu-rt.csv
#rm -rf results/*/github-hx
./smartbugs -t all -f 'samples/SimpleDAO.hex' --runid github-hx --sarif --timeout 180
./results2csv -x start duration -- results/*/github-hx > .github/results-ubuntu-hx.csv
| 863 | 47 | 117 | sh |
smartbugs | smartbugs-master/.github/old/github_results.sh | #!/bin/bash
# Run .github/github_results.sh from SmartBugs home directory
# Generates .github/results-ubuntu.csv, needed for the workflow ubuntu.yml
# as a reference for comparing the results of the workflow with
rm -rf results/github
./smartbugs -t all -f 'samples/SimpleDAO.*' --runid github --json --main --timeout 360
./results2csv -x start duration -- results/*/github | sed '/confuzzius/s/".*"//' > .github/results-ubuntu.csv
| 434 | 42.5 | 109 | sh |
smartbugs | smartbugs-master/install/setup-venv.sh | #!/bin/bash
# tested for python >= 3.6.9
# python < 3.10 will give an error when using the ':'-feature in input patterns
python3 -m venv venv
source venv/bin/activate
# avoid spurious errors/warnings; the next two lines could be omitted
pip install --upgrade pip
pip install wheel
# install the packages needed by smartbugs
pip install pyyaml colorama requests semantic_version docker py-cpuinfo
| 399 | 27.571429 | 79 | sh |
smartbugs | smartbugs-master/tools/confuzzius/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
MAIN="$4"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
COUNT=$(echo $CONTRACTS | wc -w)
[ "$COUNT" -gt 0 ] || COUNT=1
OPT_CONTRACT=""
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
COUNT=1
OPT_CONTRACT="--contract $CONTRACT"
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
# Fuzz each contract at least 10 seconds
OPT_TIMEOUT=""
TO=$(((TIMEOUT - (10 * COUNT)) / COUNT))
if [ "$TIMEOUT" -gt 0 ] && [ $TO -ge 10 ]; then
OPT_TIMEOUT="--timeout $TO"
fi
touch /root/results.json
python3 fuzzer/main.py -s "$FILENAME" --evm byzantium --results results.json --seed 1427655 $OPT_TIMEOUT $OPT_CONTRACT
| 865 | 22.405405 | 118 | sh |
smartbugs | smartbugs-master/tools/conkas/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
cd /conkas
python3 conkas.py -fav "$FILENAME"
| 72 | 9.428571 | 34 | sh |
smartbugs | smartbugs-master/tools/conkas/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
BIN="$2"
MAIN="$3"
export PATH="$BIN:$PATH"
chmod +x $BIN/solc
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
OPT_CONTRACT=""
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
OPT_CONTRACT="--contract $CONTRACT"
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
cd /conkas
python3 conkas.py -fav -s "$FILENAME" $OPT_CONTRACT
| 509 | 18.615385 | 61 | sh |
smartbugs | smartbugs-master/tools/ethainter/docker/scripts/run.sh | #!/bin/sh
FILENAME="$1"
./analyze.py --reuse_datalog_bin --restart --rerun_clients -d /data -C ../../ethainter-inlined.dl
| 124 | 19.833333 | 97 | sh |
smartbugs | smartbugs-master/tools/ethainter/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
SB=$(dirname "$FILENAME")
OPT_TIMEOUT=""
if [ "$TIMEOUT" -ge 170 ]; then
# reserve 50s for Ethainter to finish after timeout
TO=$((TIMEOUT-50))
OPT_TIMEOUT="-T $TO"
fi
cd /home/reviewer/gigahorse-toolchain/logic
./analyze.py --reuse_datalog_bin --restart --rerun_clients $OPT_TIMEOUT -d "$SB" -C ../../ethainter-inlined.dl
| 375 | 22.5 | 110 | sh |
smartbugs | smartbugs-master/tools/honeybadger/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for honeybadger to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="-glt $TO"
fi
python honeybadger/honeybadger.py $OPT_TIMEOUT -b -s "$FILENAME"
| 290 | 18.4 | 64 | sh |
smartbugs | smartbugs-master/tools/honeybadger/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
MAIN="$4"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
OPT_CONTRACT=""
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
OPT_CONTRACT="--contract $CONTRACT"
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for honeybadger to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="-glt $TO"
fi
python honeybadger/honeybadger.py $OPT_TIMEOUT -s "$FILENAME" $OPT_CONTRACT
| 723 | 20.294118 | 75 | sh |
smartbugs | smartbugs-master/tools/madmax/docker/scripts/run.sh | #!/bin/sh
FILENAME=$1
CODE=$(cat ${FILENAME})
python3 gigahorse-toolchain/gigahorse.py --reuse_datalog_bin --rerun_clients --restart -C madmax.dl ${FILENAME}
| 160 | 22 | 111 | sh |
smartbugs | smartbugs-master/tools/madmax/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
OPT_TIMEOUT=""
if [ "$TIMEOUT" -ge 170 ]; then
# reserve 50s for MaxMax to finish after timeout
TO=$((TIMEOUT-50))
OPT_TIMEOUT="-T $TO"
fi
cd /MadMax
python3 gigahorse-toolchain/gigahorse.py --reuse_datalog_bin --rerun_clients --restart $OPT_TIMEOUT -C madmax.dl "${FILENAME}"
| 329 | 21 | 126 | sh |
smartbugs | smartbugs-master/tools/maian/docker/scripts/runMAIANall.sh | #!/bin/sh
FILENAME=$1
for c in `python3 printContractNames.py ${FILENAME} | grep -v "ANTLR runtime and generated code versions disagree:"`;
do
cd /MAIAN/tool;
python3 maian.py -c 0 -s ${FILENAME} ${c};
python3 maian.py -c 1 -s ${FILENAME} ${c};
python3 maian.py -c 2 -s ${FILENAME} ${c}
done
| 329 | 26.5 | 118 | sh |
smartbugs | smartbugs-master/tools/maian/docker/scripts/run_maian_bytecode.sh | #!/bin/sh
FILENAME=$1
cd /MAIAN/tool
python3 maian.py -c 0 -b ${FILENAME}
python3 maian.py -c 1 -b ${FILENAME}
python3 maian.py -c 2 -b ${FILENAME}
| 150 | 15.777778 | 36 | sh |
smartbugs | smartbugs-master/tools/maian/docker/scripts/run_maian_solidity.sh | #!/bin/sh
FILENAME=$1
for c in `python3 printContractNames.py ${FILENAME} | grep -v "ANTLR runtime and generated code versions disagree:"`;
do
cd /MAIAN/tool;
python3 maian.py -c 0 -s ${FILENAME} ${c};
python3 maian.py -c 1 -s ${FILENAME} ${c};
python3 maian.py -c 2 -s ${FILENAME} ${c}
done
| 329 | 26.5 | 118 | sh |
smartbugs | smartbugs-master/tools/maian/scripts/do_bytecode.sh | #!/bin/sh
FILENAME="$1"
cd /MAIAN/tool
python3 maian.py -c 0 -bs "$FILENAME"
python3 maian.py -c 1 -bs "$FILENAME"
python3 maian.py -c 2 -bs "$FILENAME"
| 155 | 16.333333 | 37 | sh |
smartbugs | smartbugs-master/tools/maian/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
cd /MAIAN/tool
python3 maian.py -c 0 -b "$FILENAME"
python3 maian.py -c 1 -b "$FILENAME"
python3 maian.py -c 2 -b "$FILENAME"
| 152 | 16 | 36 | sh |
smartbugs | smartbugs-master/tools/maian/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
BIN="$2"
MAIN="$3"
export PATH="$BIN:$PATH"
chmod +x $BIN/solc
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
CONTRACTS="$CONTRACT"
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
cd /MAIAN/tool;
for CONTRACT in $CONTRACTS; do
for c in 0 1 2; do
python3 maian.py -c "$c" -s "$FILENAME" "$CONTRACT"
done
done
| 561 | 18.37931 | 61 | sh |
smartbugs | smartbugs-master/tools/manticore-0.3.7/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
BIN="$2"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
mkdir /results
for c in `python3 "$BIN/printContractNames.py" "${FILENAME}"`; do
manticore --no-colors --contract "${c}" "${FILENAME#/}"
mv /mcore_* /results
done
| 263 | 16.6 | 66 | sh |
smartbugs | smartbugs-master/tools/mythril-0.23.15/scripts/do_bytecode.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for mythril to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="--execution-timeout $TO"
fi
/usr/local/bin/myth analyze $OPT_TIMEOUT -o json -f "$FILENAME"
| 300 | 19.066667 | 63 | sh |
smartbugs | smartbugs-master/tools/mythril-0.23.15/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for mythril to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="--execution-timeout $TO"
fi
/usr/local/bin/myth analyze $OPT_TIMEOUT -o json --bin-runtime -f "$FILENAME"
| 314 | 20 | 77 | sh |
smartbugs | smartbugs-master/tools/mythril-0.23.15/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
MAIN="$4"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
OPT_CONTRACT=""
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
OPT_CONTRACT=":$CONTRACT"
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for mythril to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="--execution-timeout $TO"
fi
/usr/local/bin/myth analyze $OPT_TIMEOUT -o json "$FILENAME$OPT_CONTRACT"
| 722 | 20.264706 | 73 | sh |
smartbugs | smartbugs-master/tools/mythril-0.23.5/scripts/do_bytecode.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for mythril to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="--execution-timeout $TO"
fi
/usr/local/bin/myth analyze $OPT_TIMEOUT -o json -f "$FILENAME"
| 300 | 19.066667 | 63 | sh |
smartbugs | smartbugs-master/tools/mythril-0.23.5/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for mythril to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="--execution-timeout $TO"
fi
/usr/local/bin/myth analyze $OPT_TIMEOUT -o json --bin-runtime -f "$FILENAME"
| 314 | 20 | 77 | sh |
smartbugs | smartbugs-master/tools/mythril-0.23.5/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
MAIN="$4"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
OPT_CONTRACT=""
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
OPT_CONTRACT=":$CONTRACT"
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for mythril to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="--execution-timeout $TO"
fi
/usr/local/bin/myth analyze $OPT_TIMEOUT -o json "$FILENAME$OPT_CONTRACT"
| 722 | 20.264706 | 73 | sh |
smartbugs | smartbugs-master/tools/osiris/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for osiris to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="-glt $TO"
fi
python osiris/osiris.py $OPT_TIMEOUT -b -s "$FILENAME"
| 275 | 17.4 | 54 | sh |
smartbugs | smartbugs-master/tools/osiris/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
MAIN="$4"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
OPT_CONTRACT=""
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
OPT_CONTRACT="--contract $CONTRACT"
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for osiris to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="-glt $TO"
fi
python osiris/osiris.py $OPT_TIMEOUT -s "$FILENAME" $OPT_CONTRACT
| 709 | 19.882353 | 66 | sh |
smartbugs | smartbugs-master/tools/oyente/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for Oyente to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="-glt $TO"
fi
cd /oyente
/oyente/oyente/oyente.py $OPT_TIMEOUT -b -s "$FILENAME"
| 287 | 17 | 55 | sh |
smartbugs | smartbugs-master/tools/oyente/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
MAIN="$4"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
OPT_CONTRACT=""
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
OPT_CONTRACT="--target-contracts $CONTRACT"
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
OPT_TIMEOUT=""
if [ "$TIMEOUT" -gt 0 ]; then
# TO = TIMEOUT * 80%
# the remaining 20% are for Oyente to finish
TO=$(( (TIMEOUT*8+9)/10 ))
OPT_TIMEOUT="-glt $TO"
fi
cd /oyente
/oyente/oyente/oyente.py $OPT_TIMEOUT -s "$FILENAME" $OPT_CONTRACT
| 728 | 19.828571 | 66 | sh |
smartbugs | smartbugs-master/tools/pakala/docker/scripts/runPakala.sh | #!/bin/sh
FILENAME="$1"
geth --dev --http --http.api eth,web3,personal,net &
sleep 2
export WEB3_PROVIDER_URI="http://127.0.0.1:8545"
cat "$FILENAME" | pakala - --exec-timeout 1500 --analysis-timeout 300
| 207 | 19.8 | 69 | sh |
smartbugs | smartbugs-master/tools/pakala/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
geth --dev --http --http.api eth,web3,personal,net &
sleep 2
export WEB3_PROVIDER_URI="http://127.0.0.1:8545"
if [ "$TIMEOUT" -eq 0 ]; then
cat "$FILENAME" | pakala -
else
# TO1 = TIMEOUT * 80%
# TO2 = TIMEOUT * 17%
TO1=$(( TIMEOUT*8/10 ))
TO2=$(( TIMEOUT*17/100 ))
cat "$FILENAME" | pakala - --exec-timeout ${TO1} --analysis-timeout ${TO2}
fi
| 408 | 20.526316 | 78 | sh |
smartbugs | smartbugs-master/tools/securify/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
BIN="$2"
mkdir /results
java -Xmx16G -jar /securify_jar/securify.jar --livestatusfile /results/live.json --output /results/results.json -fh "$FILENAME"
| 178 | 21.375 | 127 | sh |
smartbugs | smartbugs-master/tools/securify/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
BIN="$2"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
mkdir /results
java -Xmx16G -jar /securify_jar/securify.jar --livestatusfile /results/live.json --output /results/results.json -fs "$FILENAME"
| 225 | 19.545455 | 127 | sh |
smartbugs | smartbugs-master/tools/sfuzz/scripts/do_solidity.sh | #!/bin/bash
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
MAIN="$4"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
CONTRACT="${FILENAME%.sol}"
CONTRACT="${CONTRACT##*/}"
CONTRACTS=$(python3 "$BIN"/printContractNames.py "$FILENAME")
COUNT=$(echo $CONTRACTS | wc -w)
[ "$COUNT" -gt 0 ] || COUNT=1
if [ "$MAIN" -eq 1 ]; then
if (echo "$CONTRACTS" | grep -q "$CONTRACT"); then
CONTRACTS="$CONTRACT"
COUNT=1
else
echo "Contract '$CONTRACT' not found in $FILENAME"
exit 127
fi
fi
mkdir -p /home/contracts
for CONTRACT in $CONTRACTS; do
echo "Extract contract $CONTRACT from $FILENAME"
cp "$FILENAME" "/home/contracts/$CONTRACT.sol"
done
echo "Extracted $COUNT contract(s) from $FILENAME"
# Fuzz each contract at least 10 seconds
TO=$(((TIMEOUT - (2 * COUNT)) / COUNT))
if [ "$TIMEOUT" -eq 0 ] || [ $TO -lt 10 ]; then
TO=120
fi
cd /home/ && ./fuzzer -g -r 1 -d $TO && chmod +x fuzzMe && ./fuzzMe
| 938 | 20.837209 | 67 | sh |
smartbugs | smartbugs-master/tools/slither/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
slither "$FILENAME" --json /output.json
| 135 | 11.363636 | 39 | sh |
smartbugs | smartbugs-master/tools/smartcheck/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
BIN="$2"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
smartcheck -p "$FILENAME"
| 108 | 9.9 | 25 | sh |
smartbugs | smartbugs-master/tools/solhint-2.1.0/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
solhint -f unix -q "$FILENAME"
| 126 | 10.545455 | 30 | sh |
smartbugs | smartbugs-master/tools/solhint-3.3.8/docker/docker-entrypoint.sh | #!/bin/sh
set -e
if [ "${1#-}" != "${1}" ] || [ -z "$(command -v "${1}")" ]; then
set -- node "$@"
fi
exec "$@"
| 116 | 12 | 64 | sh |
smartbugs | smartbugs-master/tools/solhint-3.3.8/scripts/do_solidity.sh | #!/bin/sh
FILENAME="$1"
BIN="$2"
export PATH="$BIN:$PATH"
chmod +x "$BIN/solc"
solhint -f unix "$FILENAME"
| 110 | 10.1 | 27 | sh |
smartbugs | smartbugs-master/tools/vandal/docker/scripts/runVandal.sh | #!/bin/sh
FILENAME=$1
mkdir -p results; cd results; /vandal/bin/analyze.sh ${FILENAME} /vandal/datalog/demo_analyses.dl; du -s *.csv | grep -v ^0
| 148 | 23.833333 | 123 | sh |
smartbugs | smartbugs-master/tools/vandal/scripts/do_runtime.sh | #!/bin/sh
FILENAME="$1"
TIMEOUT="$2"
BIN="$3"
mkdir -p /results
cd /results
/vandal/bin/analyze.sh "$FILENAME" /vandal/datalog/demo_analyses.dl
du -s *.csv | grep -v ^0
| 171 | 14.636364 | 67 | sh |
spaCy | spaCy-master/bin/get-package.sh | #!/usr/bin/env bash
set -e
version=$(grep "__title__ = " spacy/about.py)
version=${version/__title__ = }
version=${version/\'/}
version=${version/\'/}
version=${version/\"/}
version=${version/\"/}
echo $version
| 214 | 15.538462 | 45 | sh |
spaCy | spaCy-master/bin/get-version.sh | #!/usr/bin/env bash
set -e
version=$(grep "__version__ = " spacy/about.py)
version=${version/__version__ = }
version=${version/\'/}
version=${version/\'/}
version=${version/\"/}
version=${version/\"/}
echo $version
| 218 | 15.846154 | 47 | sh |
spaCy | spaCy-master/bin/push-tag.sh | #!/usr/bin/env bash
set -e
# Insist repository is clean
git diff-index --quiet HEAD
git checkout $1
git pull origin $1
git push origin $1
version=$(grep "__version__ = " spacy/about.py)
version=${version/__version__ = }
version=${version/\'/}
version=${version/\'/}
version=${version/\"/}
version=${version/\"/}
git tag "v$version"
git push origin "v$version"
| 364 | 17.25 | 47 | sh |
spaCy | spaCy-master/website/public/images/displacy-dep-founded.html | <svg
xmlns="http://www.w3.org/2000/svg"
xlink="http://www.w3.org/1999/xlink"
xml:lang="en"
id="c3124cc3e661444cb9d4175a5b7c09d1-0"
class="displacy"
width="925"
height="399.5"
direction="ltr"
style="
max-width: none;
height: 399.5px;
color: #000000;
background: #ffffff;
font-family: Arial;
direction: ltr;
"
>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="50">Smith</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="50"></tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="225">founded</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="225"></tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="400">a</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="400"></tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="575">healthcare</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="575"></tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="750">company</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="750"></tspan>
</text>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-c3124cc3e661444cb9d4175a5b7c09d1-0-0"
stroke-width="2px"
d="M70,264.5 C70,177.0 215.0,177.0 215.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-c3124cc3e661444cb9d4175a5b7c09d1-0-0"
class="displacy-label"
startOffset="50%"
side="left"
fill="currentColor"
text-anchor="middle"
>
nsubj
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M70,266.5 L62,254.5 78,254.5"
fill="currentColor"
></path>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-c3124cc3e661444cb9d4175a5b7c09d1-0-1"
stroke-width="2px"
d="M420,264.5 C420,89.5 745.0,89.5 745.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-c3124cc3e661444cb9d4175a5b7c09d1-0-1"
class="displacy-label"
startOffset="50%"
side="left"
fill="currentColor"
text-anchor="middle"
>
det
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M420,266.5 L412,254.5 428,254.5"
fill="currentColor"
></path>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-c3124cc3e661444cb9d4175a5b7c09d1-0-2"
stroke-width="2px"
d="M595,264.5 C595,177.0 740.0,177.0 740.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-c3124cc3e661444cb9d4175a5b7c09d1-0-2"
class="displacy-label"
startOffset="50%"
side="left"
fill="currentColor"
text-anchor="middle"
>
compound
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M595,266.5 L587,254.5 603,254.5"
fill="currentColor"
></path>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-c3124cc3e661444cb9d4175a5b7c09d1-0-3"
stroke-width="2px"
d="M245,264.5 C245,2.0 750.0,2.0 750.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-c3124cc3e661444cb9d4175a5b7c09d1-0-3"
class="displacy-label"
startOffset="50%"
side="left"
fill="currentColor"
text-anchor="middle"
>
dobj
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M750.0,266.5 L758.0,254.5 742.0,254.5"
fill="currentColor"
></path>
</g>
</svg>
| 5,233 | 32.551282 | 84 | html |
spaCy | spaCy-master/website/public/images/displacy-ent-custom.html | <div
class="entities"
style="
line-height: 2.5;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif,
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
font-size: 18px;
"
>But
<mark
class="entity"
style="
background: linear-gradient(90deg, #aa9cfc, #fc9ce7);
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>Google
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>ORG</span
></mark
>is starting from behind. The company made a late push into hardware, and
<mark
class="entity"
style="
background: linear-gradient(90deg, #aa9cfc, #fc9ce7);
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>Apple
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>ORG</span
></mark
>’s Siri, available on iPhones, and
<mark
class="entity"
style="
background: linear-gradient(90deg, #aa9cfc, #fc9ce7);
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>Amazon
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>ORG</span
></mark
>’s Alexa software, which runs on its Echo and Dot devices, have clear leads in consumer
adoption.</div
>
| 2,351 | 28.037037 | 97 | html |
spaCy | spaCy-master/website/public/images/displacy-ent-snek.html | <div
class="entities"
style="
line-height: 2.5;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif,
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
font-size: 16px;
"
>
🌱🌿
<mark
class="entity"
style="
background: #3dff74;
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>🐍
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>SNEK</span
></mark
>
____ 🌳🌲 ____
<mark
class="entity"
style="
background: #cfc5ff;
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>👨🌾
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>HUMAN</span
></mark
>
🏘️
</div>
| 1,476 | 23.616667 | 97 | html |
spaCy | spaCy-master/website/public/images/displacy-ent1.html | <div
class="entities"
style="
line-height: 2.5;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif,
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
font-size: 16px;
"
>
<mark
class="entity"
style="
background: #7aecec;
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>
Apple
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>ORG</span
>
</mark>
is looking at buying
<mark
class="entity"
style="
background: #feca74;
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>
U.K.
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>GPE</span
>
</mark>
startup for
<mark
class="entity"
style="
background: #e4e7d2;
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>
$1 billion
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>MONEY</span
>
</mark>
</div>
| 2,098 | 23.694118 | 97 | html |
spaCy | spaCy-master/website/public/images/displacy-ent2.html | <div
class="entities"
style="
line-height: 2.5;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif,
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
font-size: 18px;
"
>
When
<mark
class="entity"
style="
background: #aa9cfc;
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>
Sebastian Thrun
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>PERSON</span
>
</mark>
started working on self-driving cars at
<mark
class="entity"
style="
background: #7aecec;
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>
Google
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>ORG</span
>
</mark>
in
<mark
class="entity"
style="
background: #bfe1d9;
padding: 0.45em 0.6em;
margin: 0 0.25em;
line-height: 1;
border-radius: 0.35em;
"
>
2007
<span
style="
font-size: 0.8em;
font-weight: bold;
line-height: 1;
border-radius: 0.35em;
text-transform: uppercase;
vertical-align: middle;
margin-left: 0.5rem;
"
>DATE</span
>
</mark>
, few people outside of the company took him seriously.
</div>
| 2,185 | 24.126437 | 97 | html |
spaCy | spaCy-master/website/public/images/displacy-long.html | <svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
id="e109581593f245ce9c4ac12f78e0c74e-0"
class="displacy"
width="1975"
height="399.5"
style="
max-width: none;
height: 399.5px;
color: #000000;
background: #ffffff;
font-family: Arial;
"
>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="50">Apple</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="50">PROPN</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="225">is</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="225">VERB</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="400">looking</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="400">VERB</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="575">at</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="575">ADP</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="750">buying</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="750">VERB</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="925">U.K.</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="925">PROPN</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="1100">startup</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="1100">NOUN</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="1275">for</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="1275">ADP</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="1450">$</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="1450">SYM</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="1625">1</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="1625">NUM</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="1800">billion</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="1800">NUM</tspan>
</text>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-0"
stroke-width="2px"
d="M70,264.5 C70,89.5 395.0,89.5 395.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-0"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
nsubj
</textPath>
</text>
<path class="displacy-arrowhead" d="M70,266.5 L62,254.5 78,254.5" fill="currentColor" />
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-1"
stroke-width="2px"
d="M245,264.5 C245,177.0 390.0,177.0 390.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-1"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
aux
</textPath>
</text>
<path class="displacy-arrowhead" d="M245,266.5 L237,254.5 253,254.5" fill="currentColor" />
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-2"
stroke-width="2px"
d="M420,264.5 C420,177.0 565.0,177.0 565.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-2"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
prep
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M565.0,266.5 L573.0,254.5 557.0,254.5"
fill="currentColor"
/>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-3"
stroke-width="2px"
d="M595,264.5 C595,177.0 740.0,177.0 740.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-3"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
pcomp
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M740.0,266.5 L748.0,254.5 732.0,254.5"
fill="currentColor"
/>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-4"
stroke-width="2px"
d="M945,264.5 C945,177.0 1090.0,177.0 1090.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-4"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
compound
</textPath>
</text>
<path class="displacy-arrowhead" d="M945,266.5 L937,254.5 953,254.5" fill="currentColor" />
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-5"
stroke-width="2px"
d="M770,264.5 C770,89.5 1095.0,89.5 1095.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-5"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
dobj
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M1095.0,266.5 L1103.0,254.5 1087.0,254.5"
fill="currentColor"
/>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-6"
stroke-width="2px"
d="M770,264.5 C770,2.0 1275.0,2.0 1275.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-6"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
prep
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M1275.0,266.5 L1283.0,254.5 1267.0,254.5"
fill="currentColor"
/>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-7"
stroke-width="2px"
d="M1470,264.5 C1470,89.5 1795.0,89.5 1795.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-7"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
quantmod
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M1470,266.5 L1462,254.5 1478,254.5"
fill="currentColor"
/>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-8"
stroke-width="2px"
d="M1645,264.5 C1645,177.0 1790.0,177.0 1790.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-8"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
compound
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M1645,266.5 L1637,254.5 1653,254.5"
fill="currentColor"
/>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-e109581593f245ce9c4ac12f78e0c74e-0-9"
stroke-width="2px"
d="M1295,264.5 C1295,2.0 1800.0,2.0 1800.0,264.5"
fill="none"
stroke="currentColor"
/>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textPath
xlink:href="#arrow-e109581593f245ce9c4ac12f78e0c74e-0-9"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
pobj
</textPath>
</text>
<path
class="displacy-arrowhead"
d="M1800.0,266.5 L1808.0,254.5 1792.0,254.5"
fill="currentColor"
/>
</g>
</svg>
| 11,592 | 34.237082 | 99 | html |
spaCy | spaCy-master/website/public/images/displacy-long2.html | <svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
id="0"
class="displacy"
width="1275"
height="399.5"
style="
max-width: none;
height: 399.5px;
color: #000000;
background: #ffffff;
font-family: Arial;
"
>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="50">Autonomous</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="50">ADJ</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="225">cars</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="225">NOUN</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="400">shift</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="400">VERB</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="575">insurance</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="575">NOUN</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="750">liability</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="750">NOUN</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="925">toward</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="925">ADP</tspan>
</text>
<text class="displacy-token" fill="currentColor" text-anchor="middle" y="309.5">
<tspan class="displacy-word" fill="currentColor" x="1100">manufacturers</tspan>
<tspan class="displacy-tag" dy="2em" fill="currentColor" x="1100">NOUN</tspan>
</text>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-0-0"
stroke-width="2px"
d="M70,264.5 C70,177.0 215.0,177.0 215.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textpath
xlink:href="#arrow-0-0"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
amod
</textpath>
</text>
<path
class="displacy-arrowhead"
d="M70,266.5 L62,254.5 78,254.5"
fill="currentColor"
></path>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-0-1"
stroke-width="2px"
d="M245,264.5 C245,177.0 390.0,177.0 390.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textpath
xlink:href="#arrow-0-1"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
nsubj
</textpath>
</text>
<path
class="displacy-arrowhead"
d="M245,266.5 L237,254.5 253,254.5"
fill="currentColor"
></path>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-0-2"
stroke-width="2px"
d="M595,264.5 C595,177.0 740.0,177.0 740.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textpath
xlink:href="#arrow-0-2"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
compound
</textpath>
</text>
<path
class="displacy-arrowhead"
d="M595,266.5 L587,254.5 603,254.5"
fill="currentColor"
></path>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-0-3"
stroke-width="2px"
d="M420,264.5 C420,89.5 745.0,89.5 745.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textpath
xlink:href="#arrow-0-3"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
dobj
</textpath>
</text>
<path
class="displacy-arrowhead"
d="M745.0,266.5 L753.0,254.5 737.0,254.5"
fill="currentColor"
></path>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-0-4"
stroke-width="2px"
d="M420,264.5 C420,2.0 925.0,2.0 925.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textpath
xlink:href="#arrow-0-4"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
prep
</textpath>
</text>
<path
class="displacy-arrowhead"
d="M925.0,266.5 L933.0,254.5 917.0,254.5"
fill="currentColor"
></path>
</g>
<g class="displacy-arrow">
<path
class="displacy-arc"
id="arrow-0-5"
stroke-width="2px"
d="M945,264.5 C945,177.0 1090.0,177.0 1090.0,264.5"
fill="none"
stroke="currentColor"
></path>
<text dy="1.25em" style="font-size: 0.8em; letter-spacing: 1px">
<textpath
xlink:href="#arrow-0-5"
class="displacy-label"
startOffset="50%"
fill="currentColor"
text-anchor="middle"
>
pobj
</textpath>
</text>
<path
class="displacy-arrowhead"
d="M1090.0,266.5 L1098.0,254.5 1082.0,254.5"
fill="currentColor"
></path>
</g>
</svg>
| 6,927 | 31.525822 | 87 | html |
spaCy | spaCy-master/website/public/images/displacy-span-custom.html | <div
class="spans"
style="
line-height: 2.5;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif,
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
font-size: 18px;
direction: ltr;
"
>
Welcome to the
<span style="font-weight: bold; display: inline-block; position: relative">
Bank
<span
style="
background: #ddd;
top: 40px;
height: 4px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
</span>
<span
style="
background: #ddd;
top: 40px;
height: 4px;
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
<span
style="
background: #ddd;
color: #000;
top: -0.5em;
padding: 2px 3px;
position: absolute;
font-size: 0.6em;
font-weight: bold;
line-height: 1;
border-radius: 3px;
"
>
BANK
</span>
</span>
</span>
<span style="font-weight: bold; display: inline-block; position: relative">
of
<span
style="
background: #ddd;
top: 40px;
height: 4px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
</span>
</span>
<span style="font-weight: bold; display: inline-block; position: relative">
China
<span
style="
background: #ddd;
top: 40px;
height: 4px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
</span>
</span>
.
</div>
| 2,252 | 25.505882 | 97 | html |
spaCy | spaCy-master/website/public/images/displacy-span.html | <div
class="spans"
style="
line-height: 2.5;
direction: ltr;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif,
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
font-size: 18px;
"
>
Welcome to the
<span style="font-weight: bold; display: inline-block; position: relative">
Bank
<span
style="
background: #7aecec;
top: 40px;
height: 4px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
</span>
<span
style="
background: #7aecec;
top: 40px;
height: 4px;
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
<span
style="
background: #7aecec;
color: #000;
top: -0.5em;
padding: 2px 3px;
position: absolute;
font-size: 0.6em;
font-weight: bold;
line-height: 1;
border-radius: 3px;
"
>
ORG
</span>
</span>
</span>
<span style="font-weight: bold; display: inline-block; position: relative">
of
<span
style="
background: #7aecec;
top: 40px;
height: 4px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
</span>
</span>
<span style="font-weight: bold; display: inline-block; position: relative">
China
<span
style="
background: #7aecec;
top: 40px;
height: 4px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
</span>
<span
style="
background: #feca74;
top: 57px;
height: 4px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
</span>
<span
style="
background: #feca74;
top: 57px;
height: 4px;
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
left: -1px;
width: calc(100% + 2px);
position: absolute;
"
>
<span
style="
background: #feca74;
color: #000;
top: -0.5em;
padding: 2px 3px;
position: absolute;
font-size: 0.6em;
font-weight: bold;
line-height: 1;
border-radius: 3px;
"
>
GPE
</span>
</span>
</span>
.
</div>
| 3,355 | 26.064516 | 97 | html |
spaCy | spaCy-master/website/setup/setup.sh | python setup/jinja_to_js.py ../spacy/cli/templates/quickstart_training.jinja src/widgets/quickstart-training-generator.js ../spacy/cli/templates/quickstart_training_recommendations.yml
| 185 | 92 | 184 | sh |
la3dm | la3dm-master/include/bgkloctomap/bgklblock.h | #ifndef LA3DM_BGKL_BLOCK_H
#define LA3DM_BGKL_BLOCK_H
#include <unordered_map>
#include <array>
#include "point3f.h"
#include "bgkloctree_node.h"
#include "bgkloctree.h"
namespace la3dm {
/// Hask key to index Block given block's center.
typedef int64_t BlockHashKey;
/// Initialize Look-Up Table
std::unordered_map<OcTreeHashKey, point3f> init_key_loc_map(float resolution, unsigned short max_depth);
std::unordered_map<unsigned short, OcTreeHashKey> init_index_map(const std::unordered_map<OcTreeHashKey, point3f> &key_loc_map,
unsigned short max_depth);
/// Extended Block
#ifdef PREDICT
typedef std::array<BlockHashKey, 27> ExtendedBlock;
#else
typedef std::array<BlockHashKey, 7> ExtendedBlock;
#endif
/// Convert from block to hash key.
BlockHashKey block_to_hash_key(point3f center);
/// Convert from block to hash key.
BlockHashKey block_to_hash_key(float x, float y, float z);
/// Convert from hash key to block.
point3f hash_key_to_block(BlockHashKey key);
/// Get current block's extended block.
ExtendedBlock get_extended_block(BlockHashKey key);
/*
* @brief Block is built on top of OcTree, providing the functions to locate nodes.
*
* Block stores the information needed to locate each OcTreeNode's position:
* fixed resolution, fixed block_size, both of which must be initialized.
* The localization is implemented using Loop-Up Table.
*/
class Block : public OcTree {
friend BlockHashKey block_to_hash_key(point3f center);
friend BlockHashKey block_to_hash_key(float x, float y, float z);
friend point3f hash_key_to_block(BlockHashKey key);
friend ExtendedBlock get_extended_block(BlockHashKey key);
friend class BGKLOctoMap;
public:
Block();
Block(point3f center);
/// @return location of the OcTreeNode given OcTree's LeafIterator.
inline point3f get_loc(const LeafIterator &it) const {
return Block::key_loc_map[it.get_hash_key()] + center;
}
/// @return size of the OcTreeNode given OcTree's LeafIterator.
inline float get_size(const LeafIterator &it) const {
unsigned short depth, index;
hash_key_to_node(it.get_hash_key(), depth, index);
return float(size / pow(2, depth));
}
/// @return center of current Block.
inline point3f get_center() const { return center; }
/// @return min lim of current Block.
inline point3f get_lim_min() const { return center - point3f(size / 2.0f, size / 2.0f, size / 2.0f); }
/// @return max lim of current Block.
inline point3f get_lim_max() const { return center + point3f(size / 2.0f, size / 2.0f, size / 2.0f); }
/// @return ExtendedBlock of current Block.
ExtendedBlock get_extended_block() const;
OcTreeHashKey get_node(unsigned short x, unsigned short y, unsigned short z) const;
point3f get_point(unsigned short x, unsigned short y, unsigned short z) const;
void get_index(const point3f &p, unsigned short &x, unsigned short &y, unsigned short &z) const;
OcTreeNode &search(float x, float y, float z) const;
OcTreeNode &search(point3f p) const;
private:
// Loop-Up Table
static std::unordered_map<OcTreeHashKey, point3f> key_loc_map;
static std::unordered_map<unsigned short, OcTreeHashKey> index_map;
static float resolution;
static float size;
static unsigned short cell_num;
point3f center;
};
}
#endif // LA3DM_BGKL_BLOCK_H
| 3,715 | 32.781818 | 131 | h |
la3dm | la3dm-master/include/bgkloctomap/bgklinference.h | #ifndef LA3DM_BGKL_H
#define LA3DM_BGKL_H
namespace la3dm {
/*
* @brief Bayesian Generalized Kernel Inference on Bernoulli distribution
* @param dim dimension of data (2, 3, etc.)
* @param T data type (float, double, etc.)
* @ref Nonparametric Bayesian inference on multivariate exponential families
*/
template<int dim, typename T>
class BGKLInference {
public:
/// Eigen matrix type for training and test data and kernel
using MatrixXType = Eigen::Matrix<T, -1, 2*dim, Eigen::RowMajor>;
using MatrixPType = Eigen::Matrix<T, -1, dim, Eigen::RowMajor>;
using MatrixKType = Eigen::Matrix<T, -1, -1, Eigen::RowMajor>;
using MatrixDKType = Eigen::Matrix<T, -1, 1>;
using MatrixYType = Eigen::Matrix<T, -1, 1>;
float EPSILON = 0.0001;
BGKLInference(T sf2, T ell) : sf2(sf2), ell(ell), trained(false) { }
/*
* @brief Fit BGK Model
* @param x input vector (3N, row major)
* @param y target vector (N)
*/
void train(const std::vector<T> &x, const std::vector<T> &y) {
assert(x.size() % (2*dim) == 0 && (int) (x.size() / (2*dim)) == y.size());
MatrixXType _x = Eigen::Map<const MatrixXType>(x.data(), x.size() / (2*dim), 2*dim);
MatrixYType _y = Eigen::Map<const MatrixYType>(y.data(), y.size(), 1);
train(_x, _y);
}
/*
* @brief Fit BGK Model
* @param x input matrix (NX3)
* @param y target matrix (NX1)
*/
void train(const MatrixXType &x, const MatrixYType &y) {
// std::cout << "training pt2" << std::endl;
this->x = MatrixXType(x);
this->y = MatrixYType(y);
trained = true;
}
/*
* @brief Predict with BGK Model
* @param xs input vector (3M, row major)
* @param ybar positive class kernel density estimate (\bar{y})
* @param kbar kernel density estimate (\bar{k})
*/
void predict(const std::vector<T> &xs, std::vector<T> &ybar, std::vector<T> &kbar) const {
// std::cout << "predicting" << std::endl;
assert(xs.size() % dim == 0);
// std::cout << "passed assertion" << std::endl;
MatrixPType _xs = Eigen::Map<const MatrixPType>(xs.data(), xs.size() / dim, dim);
// std::cout << "matrix conversion successful" << std::endl;
MatrixYType _ybar, _kbar;
predict(_xs, _ybar, _kbar);
// std::cout << "finished prediction" << std::endl;
ybar.resize(_ybar.rows());
kbar.resize(_kbar.rows());
for (int r = 0; r < _ybar.rows(); ++r) {
ybar[r] = _ybar(r, 0);
kbar[r] = _kbar(r, 0);
}
}
/*
* @brief Predict with nonparametric Bayesian generalized kernel inference
* @param xs input vector (M x 3)
* @param ybar positive class kernel density estimate (M x 1)
* @param kbar kernel density estimate (M x 1)
*/
void predict(const MatrixPType &xs, MatrixYType &ybar, MatrixYType &kbar) const {
// std::cout << "second prediction step" << std::endl;
assert(trained == true);
MatrixKType Ks;
covSparseLine(xs, x, Ks);
// std::cout << "computed covsparseline" << std::endl;
ybar = (Ks * y).array();
kbar = Ks.rowwise().sum().array();
}
private:
/*
* @brief Compute Euclid distances between two vectors.
* @param x input vector
* @param z input vecotr
* @return d distance matrix
*/
void dist(const MatrixXType &x, const MatrixXType &z, MatrixKType &d) const {
d = MatrixKType::Zero(x.rows(), z.rows());
for (int i = 0; i < x.rows(); ++i) {
d.row(i) = (z.rowwise() - x.row(i)).rowwise().norm();
}
}
// TODO: validate me
void point_to_line_dist(const MatrixPType &x, const MatrixXType &z, MatrixKType &d) const {
assert((x.cols() == 3) && (z.cols() == 6));
// std::cout << "made it" << std::endl;
d = MatrixKType::Zero(x.rows(), z.rows());
float line_len;
point3f p, p0, p1, v, w, line_vec, pnt_vec, nearest;
float t;
for (int i = 0; i < x.rows(); ++i) {
p = point3f(x(i,0), x(i,1), x(i,2));
for (int j = 0; j < z.rows(); ++j) {
p0 = point3f(z(j,0), z(j,1), z(j,2));
p1 = point3f(z(j,3), z(j,4), z(j,5));
line_vec = p1 - p0;
line_len = line_vec.norm();
pnt_vec = p - p0;
if (line_len < EPSILON) {
d(i,j) = (p-p0).norm();
}
else {
double c1 = pnt_vec.dot(line_vec);
double c2 = line_vec.dot(line_vec);
if ( c1 <= 0) {
d(i,j) = (p - p0).norm();
}
else if (c2 <= c1) {
d(i,j) = (p - p1).norm();
}
else{
double b = c1 / c2;
nearest = p0 + (line_vec*b);
d(i,j) = (p - nearest).norm();
}
}
}
}
}
/*
* @brief Matern3 kernel.
* @param x input vector
* @param z input vector
* @return Kxz covariance matrix
*/
void covMaterniso3(const MatrixXType &x, const MatrixXType &z, MatrixKType &Kxz) const {
dist(1.73205 / ell * x, 1.73205 / ell * z, Kxz);
Kxz = ((1 + Kxz.array()) * exp(-Kxz.array())).matrix() * sf2;
}
/*
* @brief Sparse kernel.
* @param x input vector
* @param z input vector
* @return Kxz covariance matrix
* @ref A sparse covariance function for exact gaussian process inference in large datasets.
*/
void covSparse(const MatrixXType &x, const MatrixXType &z, MatrixKType &Kxz) const {
dist(x / ell, z / ell, Kxz);
Kxz = (((2.0f + (Kxz * 2.0f * 3.1415926f).array().cos()) * (1.0f - Kxz.array()) / 3.0f) +
(Kxz * 2.0f * 3.1415926f).array().sin() / (2.0f * 3.1415926f)).matrix() * sf2;
// Clean up for values with distance outside length scale
// Possible because Kxz <= 0 when dist >= ell
for (int i = 0; i < Kxz.rows(); ++i)
{
for (int j = 0; j < Kxz.cols(); ++j)
if (Kxz(i,j) < 0.0)
Kxz(i,j) = 0.0f;
}
}
/*
* @brief Sparse kernel.
* @param x input vector
* @param z input vector
* @return Kxz covariance matrix
* @ref A sparse covariance function for exact gaussian process inference in large datasets.
*/
void covSparseLine(const MatrixPType &x, const MatrixXType &z, MatrixKType &Kxz) const {
point_to_line_dist(x, z, Kxz); // Check on this
Kxz /= ell;
Kxz = (((2.0f + (Kxz * 2.0f * 3.1415926f).array().cos()) * (1.0f - Kxz.array()) / 3.0f) +
(Kxz * 2.0f * 3.1415926f).array().sin() / (2.0f * 3.1415926f)).matrix() * sf2;
// Clean up for values with distance outside length scale
// Possible because Kxz <= 0 when dist >= ell
for (int i = 0; i < Kxz.rows(); ++i)
{
for (int j = 0; j < Kxz.cols(); ++j)
if (Kxz(i,j) < 0.0)
Kxz(i,j) = 0.0f;
}
}
T sf2; // signal variance
T ell; // length-scale
MatrixXType x; // temporary storage of training data
MatrixYType y; // temporary storage of training labels
bool trained; // true if bgkinference stored training data
};
typedef BGKLInference<3, float> BGKL3f;
}
#endif // LA3DM_BGKL_H
| 8,306 | 38.183962 | 101 | h |
la3dm | la3dm-master/include/bgkloctomap/bgkloctomap.h | #ifndef LA3DM_BGKL_OCTOMAP_H
#define LA3DM_BGKL_OCTOMAP_H
#include <unordered_map>
#include <vector>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include "rtree.h"
#include "bgklblock.h"
#include "bgkloctree_node.h"
#include "point6f.h"
namespace la3dm {
/// PCL PointCloud types as input
typedef pcl::PointXYZ PCLPointType;
typedef pcl::PointCloud<PCLPointType> PCLPointCloud;
/*
* @brief BGKLOctoMap
*
* Bayesian Generalized Kernel Inference for Occupancy Map Prediction
* The space is partitioned by Blocks in which OcTrees with fixed
* depth are rooted. Occupancy values in one Block is predicted by
* its ExtendedBlock via Bayesian generalized kernel inference.
*/
class BGKLOctoMap {
public:
/// Types used internally
typedef std::vector<point3f> PointCloud;
typedef std::pair<point3f, float> GPPointType;
typedef std::pair<point6f, float> GPLineType; // generalizes GPPointType
typedef std::vector<GPPointType> GPPointCloud;
typedef std::vector<GPLineType> GPLineCloud; // generalizes GPLineType
typedef RTree<int, float, 3, float> MyRTree;
public:
BGKLOctoMap();
/*
* @param resolution (default 0.1m)
* @param block_depth maximum depth of OcTree (default 4)
* @param sf2 signal variance in GPs (default 1.0)
* @param ell length-scale in GPs (default 1.0)
* @param noise noise variance in GPs (default 0.01)
* @param l length-scale in logistic regression function (default 100)
* @param min_var minimum variance in Occupancy (default 0.001)
* @param max_var maximum variance in Occupancy (default 1000)
* @param max_known_var maximum variance for Occuapncy to be classified as KNOWN State (default 0.02)
* @param free_thresh free threshold for Occupancy probability (default 0.3)
* @param occupied_thresh occupied threshold for Occupancy probability (default 0.7)
*/
BGKLOctoMap(float resolution,
unsigned short block_depth,
float sf2,
float ell,
float free_thresh,
float occupied_thresh,
float var_thresh,
float prior_A,
float prior_B);
~BGKLOctoMap();
/// Set resolution.
void set_resolution(float resolution);
/// Set block max depth.
void set_block_depth(unsigned short max_depth);
/// Get resolution.
inline float get_resolution() const { return resolution; }
/// Get block max depth.
inline float get_block_depth() const { return block_depth; }
/*
* @brief Insert PCL PointCloud into BGKLOctoMaps.
* @param cloud one scan in PCLPointCloud format
* @param origin sensor origin in the scan
* @param ds_resolution downsampling resolution for PCL VoxelGrid filtering (-1 if no downsampling)
* @param free_res resolution for sampling free training points along sensor beams (default 2.0)
* @param max_range maximum range for beams to be considered as valid measurements (-1 if no limitation)
*/
void insert_pointcloud(const PCLPointCloud &cloud, const point3f &origin, float ds_resolution,
float free_res = 2.0f,
float max_range = -1);
void insert_training_data(const GPLineCloud &cloud);
/// Get bounding box of the map.
void get_bbox(point3f &lim_min, point3f &lim_max) const;
class RayCaster {
public:
RayCaster(const BGKLOctoMap *map, const point3f &start, const point3f &end) : map(map) {
assert(map != nullptr);
_block_key = block_to_hash_key(start);
block = map->search(_block_key);
lim = static_cast<unsigned short>(pow(2, map->block_depth - 1));
if (block != nullptr) {
block->get_index(start, x, y, z);
block_lim = block->get_center();
block_size = block->size;
current_p = start;
resolution = map->resolution;
int x0 = static_cast<int>((start.x() / resolution));
int y0 = static_cast<int>((start.y() / resolution));
int z0 = static_cast<int>((start.z() / resolution));
int x1 = static_cast<int>((end.x() / resolution));
int y1 = static_cast<int>((end.y() / resolution));
int z1 = static_cast<int>((end.z() / resolution));
dx = abs(x1 - x0);
dy = abs(y1 - y0);
dz = abs(z1 - z0);
n = 1 + dx + dy + dz;
x_inc = x1 > x0 ? 1 : (x1 == x0 ? 0 : -1);
y_inc = y1 > y0 ? 1 : (y1 == y0 ? 0 : -1);
z_inc = z1 > z0 ? 1 : (z1 == z0 ? 0 : -1);
xy_error = dx - dy;
xz_error = dx - dz;
yz_error = dy - dz;
dx *= 2;
dy *= 2;
dz *= 2;
} else {
n = 0;
}
}
inline bool end() const { return n <= 0; }
bool next(point3f &p, OcTreeNode &node, BlockHashKey &block_key, OcTreeHashKey &node_key) {
assert(!end());
bool valid = false;
unsigned short index = x + y * lim + z * lim * lim;
node_key = Block::index_map[index];
block_key = _block_key;
if (block != nullptr) {
valid = true;
node = (*block)[node_key];
current_p = block->get_point(x, y, z);
p = current_p;
} else {
p = current_p;
}
if (xy_error > 0 && xz_error > 0) {
x += x_inc;
current_p.x() += x_inc * resolution;
xy_error -= dy;
xz_error -= dz;
if (x >= lim || x < 0) {
block_lim.x() += x_inc * block_size;
_block_key = block_to_hash_key(block_lim);
block = map->search(_block_key);
x = x_inc > 0 ? 0 : lim - 1;
}
} else if (xy_error < 0 && yz_error > 0) {
y += y_inc;
current_p.y() += y_inc * resolution;
xy_error += dx;
yz_error -= dz;
if (y >= lim || y < 0) {
block_lim.y() += y_inc * block_size;
_block_key = block_to_hash_key(block_lim);
block = map->search(_block_key);
y = y_inc > 0 ? 0 : lim - 1;
}
} else if (yz_error < 0 && xz_error < 0) {
z += z_inc;
current_p.z() += z_inc * resolution;
xz_error += dx;
yz_error += dy;
if (z >= lim || z < 0) {
block_lim.z() += z_inc * block_size;
_block_key = block_to_hash_key(block_lim);
block = map->search(_block_key);
z = z_inc > 0 ? 0 : lim - 1;
}
} else if (xy_error == 0) {
x += x_inc;
y += y_inc;
n -= 2;
current_p.x() += x_inc * resolution;
current_p.y() += y_inc * resolution;
if (x >= lim || x < 0) {
block_lim.x() += x_inc * block_size;
_block_key = block_to_hash_key(block_lim);
block = map->search(_block_key);
x = x_inc > 0 ? 0 : lim - 1;
}
if (y >= lim || y < 0) {
block_lim.y() += y_inc * block_size;
_block_key = block_to_hash_key(block_lim);
block = map->search(_block_key);
y = y_inc > 0 ? 0 : lim - 1;
}
}
n--;
return valid;
}
private:
const BGKLOctoMap *map;
Block *block;
point3f block_lim;
float block_size, resolution;
int dx, dy, dz, error, n;
int x_inc, y_inc, z_inc, xy_error, xz_error, yz_error;
unsigned short index, x, y, z, lim;
BlockHashKey _block_key;
point3f current_p;
};
/// LeafIterator for iterating all leaf nodes in blocks
class LeafIterator : public std::iterator<std::forward_iterator_tag, OcTreeNode> {
public:
LeafIterator(const BGKLOctoMap *map) {
assert(map != nullptr);
block_it = map->block_arr.cbegin();
end_block = map->block_arr.cend();
if (map->block_arr.size() > 0) {
leaf_it = block_it->second->begin_leaf();
end_leaf = block_it->second->end_leaf();
} else {
leaf_it = OcTree::LeafIterator();
end_leaf = OcTree::LeafIterator();
}
}
// just for initializing end iterator
LeafIterator(std::unordered_map<BlockHashKey, Block *>::const_iterator block_it,
OcTree::LeafIterator leaf_it)
: block_it(block_it), leaf_it(leaf_it), end_block(block_it), end_leaf(leaf_it) { }
bool operator==(const LeafIterator &other) {
return (block_it == other.block_it) && (leaf_it == other.leaf_it);
}
bool operator!=(const LeafIterator &other) {
return !(this->operator==(other));
}
LeafIterator operator++(int) {
LeafIterator result(*this);
++(*this);
return result;
}
LeafIterator &operator++() {
++leaf_it;
if (leaf_it == end_leaf) {
++block_it;
if (block_it != end_block) {
leaf_it = block_it->second->begin_leaf();
end_leaf = block_it->second->end_leaf();
}
}
return *this;
}
OcTreeNode &operator*() const {
return *leaf_it;
}
std::vector<point3f> get_pruned_locs() const {
std::vector<point3f> pruned_locs;
point3f center = get_loc();
float size = get_size();
float x0 = center.x() - size * 0.5 + Block::resolution * 0.5;
float y0 = center.y() - size * 0.5 + Block::resolution * 0.5;
float z0 = center.z() - size * 0.5 + Block::resolution * 0.5;
float x1 = center.x() + size * 0.5;
float y1 = center.y() + size * 0.5;
float z1 = center.z() + size * 0.5;
for (float x = x0; x < x1; x += Block::resolution) {
for (float y = y0; y < y1; y += Block::resolution) {
for (float z = z0; z < z1; z += Block::resolution) {
pruned_locs.emplace_back(x, y, z);
}
}
}
return pruned_locs;
}
inline OcTreeNode &get_node() const {
return operator*();
}
inline point3f get_loc() const {
return block_it->second->get_loc(leaf_it);
}
inline float get_size() const {
return block_it->second->get_size(leaf_it);
}
private:
std::unordered_map<BlockHashKey, Block *>::const_iterator block_it;
std::unordered_map<BlockHashKey, Block *>::const_iterator end_block;
OcTree::LeafIterator leaf_it;
OcTree::LeafIterator end_leaf;
};
/// @return the beginning of leaf iterator
inline LeafIterator begin_leaf() const { return LeafIterator(this); }
/// @return the end of leaf iterator
inline LeafIterator end_leaf() const { return LeafIterator(block_arr.cend(), OcTree::LeafIterator()); }
OcTreeNode search(point3f p) const;
OcTreeNode search(float x, float y, float z) const;
Block *search(BlockHashKey key) const;
inline float get_block_size() const { return block_size; }
private:
/// @return true if point is inside a bounding box given min and max limits.
inline bool gp_point_in_bbox(const GPPointType &p, const point3f &lim_min, const point3f &lim_max) const {
return (p.first.x() > lim_min.x() && p.first.x() < lim_max.x() &&
p.first.y() > lim_min.y() && p.first.y() < lim_max.y() &&
p.first.z() > lim_min.z() && p.first.z() < lim_max.z());
}
/// Get the bounding box of a pointcloud.
void bbox(const GPLineCloud &cloud, point3f &lim_min, point3f &lim_max) const;
/// Get all block indices inside a bounding box.
void get_blocks_in_bbox(const point3f &lim_min, const point3f &lim_max,
std::vector<BlockHashKey> &blocks) const;
/// Get all points inside a bounding box assuming pointcloud has been inserted in rtree before.
int get_gp_points_in_bbox(const point3f &lim_min, const point3f &lim_max,
std::vector<int> &out);
/// @return true if point exists inside a bounding box assuming pointcloud has been inserted in rtree before.
int has_gp_points_in_bbox(const point3f &lim_min, const point3f &lim_max);
/// Get all points inside a bounding box (block) assuming pointcloud has been inserted in rtree before.
int get_gp_points_in_bbox(const BlockHashKey &key, std::vector<int> &out);
/// @return true if point exists inside a bounding box (block) assuming pointcloud has been inserted in rtree before.
int has_gp_points_in_bbox(const BlockHashKey &key);
/// Get all points inside an extended block assuming pointcloud has been inserted in rtree before.
int get_gp_points_in_bbox(const ExtendedBlock &block, std::vector<int> &out);
/// @return true if point exists inside an extended block assuming pointcloud has been inserted in rtree before.
int has_gp_points_in_bbox(const ExtendedBlock &block);
/// RTree callback function
static bool count_callback(int p, void *arg);
/// RTree callback function
static bool search_callback(int p, void *arg);
/// Downsample PCLPointCloud using PCL VoxelGrid Filtering.
void downsample(const PCLPointCloud &in, PCLPointCloud &out, float ds_resolution) const;
/// Sample free training points along sensor beams.
void beam_sample(const point3f &hits, const point3f &origin, PointCloud &frees,
float free_resolution) const;
/// Get training data from one sensor scan.
void get_training_data(const PCLPointCloud &cloud, const point3f &origin, float ds_resolution,
float free_resolution, float max_range, GPLineCloud &xy, GPLineCloud &rays, std::vector<int> &ray_idx) const;
float resolution;
float block_size;
unsigned short block_depth;
std::unordered_map<BlockHashKey, Block *> block_arr;
MyRTree rtree;
};
}
#endif // LA3DM_BGKLOCTOMAP_H
| 16,070 | 40.527132 | 140 | h |
la3dm | la3dm-master/include/bgkloctomap/bgkloctree.h | #ifndef LA3DM_BGKL_OCTREE_H
#define LA3DM_BGKL_OCTREE_H
#include <stack>
#include <vector>
#include "point3f.h"
#include "bgkloctree_node.h"
namespace la3dm {
/// Hash key to index OcTree nodes given depth and the index in that layer.
typedef int OcTreeHashKey;
/// Convert from node to hask key.
OcTreeHashKey node_to_hash_key(unsigned short depth, unsigned short index);
/// Convert from hash key to node.
void hash_key_to_node(OcTreeHashKey key, unsigned short &depth, unsigned short &index);
/*
* @brief A simple OcTree to organize occupancy data in one block.
*
* OcTree doesn't store positions of nodes in order to reduce memory usage.
* The nodes in OcTrees are indexed by OcTreeHashKey which can be used to
* retrieve positions later (See Block).
* For the purpose of mapping, this OcTree has fixed depth which should be
* set before using OcTrees.
*/
class OcTree {
friend class BGKLOctoMap;
public:
OcTree();
~OcTree();
OcTree(const OcTree &other);
OcTree &operator=(const OcTree &other);
/*
* @brief Rursively pruning OcTreeNodes with the same state.
*
* Prune nodes by setting nodes to PRUNED.
* Delete the layer if all nodes are pruned.
*/
bool prune();
/// @return true if this node is a leaf node.
bool is_leaf(OcTreeHashKey key) const;
/// @return true if this node is a leaf node.
bool is_leaf(unsigned short depth, unsigned short index) const;
/// @return true if this node exists and is not pruned.
bool search(OcTreeHashKey key) const;
/// @return Occupancy of the node (without checking if it exists!)
OcTreeNode &operator[](OcTreeHashKey key) const;
/// Leaf iterator for OcTrees: iterate all leaf nodes not pruned.
class LeafIterator : public std::iterator<std::forward_iterator_tag, OcTreeNode> {
public:
LeafIterator() : tree(nullptr) { }
LeafIterator(const OcTree *tree)
: tree(tree != nullptr && tree->node_arr != nullptr ? tree : nullptr) {
if (tree != nullptr) {
stack.emplace(0, 0);
stack.emplace(0, 0);
++(*this);
}
}
LeafIterator(const LeafIterator &other) : tree(other.tree), stack(other.stack) { }
LeafIterator &operator=(const LeafIterator &other) {
tree = other.tree;
stack = other.stack;
return *this;
}
bool operator==(const LeafIterator &other) const {
return (tree == other.tree) &&
(stack.size() == other.stack.size()) &&
(stack.size() == 0 || (stack.size() > 0 &&
(stack.top().depth == other.stack.top().depth) &&
(stack.top().index == other.stack.top().index)));
}
bool operator!=(const LeafIterator &other) const {
return !(this->operator==(other));
}
LeafIterator operator++(int) {
LeafIterator result(*this);
++(*this);
return result;
}
LeafIterator &operator++() {
if (stack.empty()) {
tree = nullptr;
} else {
stack.pop();
while (!stack.empty() && !tree->is_leaf(stack.top().depth, stack.top().index))
single_inc();
if (stack.empty())
tree = nullptr;
}
return *this;
}
inline OcTreeNode &operator*() const {
return (*tree)[get_hash_key()];
}
inline OcTreeNode &get_node() const {
return operator*();
}
inline OcTreeHashKey get_hash_key() const {
OcTreeHashKey key = node_to_hash_key(stack.top().depth, stack.top().index);
return key;
}
protected:
void single_inc() {
StackElement top(stack.top());
stack.pop();
for (int i = 0; i < 8; ++i) {
stack.emplace(top.depth + 1, top.index * 8 + i);
}
}
struct StackElement {
unsigned short depth;
unsigned short index;
StackElement(unsigned short depth, unsigned short index)
: depth(depth), index(index) { }
};
const OcTree *tree;
std::stack<StackElement, std::vector<StackElement> > stack;
};
/// @return the beginning of leaf iterator
inline LeafIterator begin_leaf() const { return LeafIterator(this); };
/// @return the end of leaf iterator
inline LeafIterator end_leaf() const { return LeafIterator(nullptr); };
private:
OcTreeNode **node_arr;
static unsigned short max_depth;
};
}
#endif // LA3DM_BGKL_OCTREE_H
| 5,281 | 31.604938 | 98 | h |
la3dm | la3dm-master/include/bgkloctomap/bgkloctree_node.h | #ifndef LA3DM_BGKL_OCCUPANCY_H
#define LA3DM_BGKL_OCCUPANCY_H
#include <iostream>
#include <fstream>
namespace la3dm {
/// Occupancy state: before pruning: FREE, OCCUPIED, UNKNOWN; after pruning: PRUNED
enum class State : char {
FREE, OCCUPIED, UNKNOWN, PRUNED
};
/*
* @brief Inference ouputs and occupancy state.
*
* Occupancy has member variables: m_A and m_B (kernel densities of positive
* and negative class, respectively) and State.
* Before using this class, set the static member variables first.
*/
class Occupancy {
friend std::ostream &operator<<(std::ostream &os, const Occupancy &oc);
friend std::ofstream &operator<<(std::ofstream &os, const Occupancy &oc);
friend std::ifstream &operator>>(std::ifstream &is, Occupancy &oc);
friend class BGKLOctoMap;
public:
/*
* @brief Constructors and destructor.
*/
Occupancy() : m_A(Occupancy::prior_A), m_B(Occupancy::prior_B), state(State::UNKNOWN) { classified = false; }
Occupancy(float A, float B);
Occupancy(const Occupancy &other) : m_A(other.m_A), m_B(other.m_B), state(other.state) { }
Occupancy &operator=(const Occupancy &other) {
m_A = other.m_A;
m_B = other.m_B;
state = other.state;
return *this;
}
~Occupancy() { }
/*
* @brief Exact updates for nonparametric Bayesian kernel inference
* @param ybar kernel density estimate of positive class (occupied)
* @param kbar kernel density of negative class (unoccupied)
*/
void update(float ybar, float kbar);
/// Get probability of occupancy.
float get_prob() const;
/// Get variance of occupancy (uncertainty)
inline float get_var() const { return (m_A * m_B) / ( (m_A + m_B) * (m_A + m_B) * (m_A + m_B + 1.0f)); }
/*
* @brief Get occupancy state of the node.
* @return occupancy state (see State).
*/
inline State get_state() const { return state; }
/// Prune current node; set state to PRUNED.
inline void prune() { state = State::PRUNED; }
/// Only FREE and OCCUPIED nodes can be equal.
inline bool operator==(const Occupancy &rhs) const {
return this->state != State::UNKNOWN && this->state == rhs.state;
}
bool classified;
private:
float m_A;
float m_B;
State state;
static float sf2;
static float ell; // length-scale
static float prior_A; // prior on alpha
static float prior_B; // prior on beta
static float free_thresh; // FREE occupancy threshold
static float occupied_thresh; // OCCUPIED occupancy threshold
static float var_thresh;
};
typedef Occupancy OcTreeNode;
}
#endif // LA3DM_BGKL_OCCUPANCY_H
| 2,950 | 29.112245 | 117 | h |
la3dm | la3dm-master/include/bgklvoctomap/bgklvblock.h | #ifndef LA3DM_BGKLV_BLOCK_H
#define LA3DM_BGKLV_BLOCK_H
#include <unordered_map>
#include <array>
#include "point3f.h"
#include "bgklvoctree_node.h"
#include "bgklvoctree.h"
namespace la3dm {
/// Hask key to index Block given block's center.
typedef int64_t BlockHashKey;
/// Initialize Look-Up Table
std::unordered_map<OcTreeHashKey, point3f> init_key_loc_map(float resolution, unsigned short max_depth);
std::unordered_map<unsigned short, OcTreeHashKey> init_index_map(const std::unordered_map<OcTreeHashKey, point3f> &key_loc_map,
unsigned short max_depth);
/// Extended Block
#ifdef PREDICT
typedef std::array<BlockHashKey, 27> ExtendedBlock;
#else
typedef std::array<BlockHashKey, 7> ExtendedBlock;
#endif
/// Convert from block to hash key.
BlockHashKey block_to_hash_key(point3f center);
/// Convert from block to hash key.
BlockHashKey block_to_hash_key(float x, float y, float z);
/// Convert from hash key to block.
point3f hash_key_to_block(BlockHashKey key);
/// Get current block's extended block.
ExtendedBlock get_extended_block(BlockHashKey key);
/*
* @brief Block is built on top of OcTree, providing the functions to locate nodes.
*
* Block stores the information needed to locate each OcTreeNode's position:
* fixed resolution, fixed block_size, both of which must be initialized.
* The localization is implemented using Loop-Up Table.
*/
class Block : public OcTree {
friend BlockHashKey block_to_hash_key(point3f center);
friend BlockHashKey block_to_hash_key(float x, float y, float z);
friend point3f hash_key_to_block(BlockHashKey key);
friend ExtendedBlock get_extended_block(BlockHashKey key);
friend class BGKLVOctoMap;
public:
Block();
Block(point3f center);
/// @return location of the OcTreeNode given OcTree's LeafIterator.
inline point3f get_loc(const LeafIterator &it) const {
return Block::key_loc_map[it.get_hash_key()] + center;
}
/// @return size of the OcTreeNode given OcTree's LeafIterator.
inline float get_size(const LeafIterator &it) const {
unsigned short depth;
unsigned long index;
hash_key_to_node(it.get_hash_key(), depth, index);
return float(size / pow(2, depth));
}
/// @return center of current Block.
inline point3f get_center() const { return center; }
/// @return min lim of current Block.
inline point3f get_lim_min() const { return center - point3f(size / 2.0f, size / 2.0f, size / 2.0f); }
/// @return max lim of current Block.
inline point3f get_lim_max() const { return center + point3f(size / 2.0f, size / 2.0f, size / 2.0f); }
/// @return ExtendedBlock of current Block.
ExtendedBlock get_extended_block() const;
OcTreeHashKey get_node(unsigned short x, unsigned short y, unsigned short z) const;
point3f get_point(unsigned short x, unsigned short y, unsigned short z) const;
void get_index(const point3f &p, unsigned short &x, unsigned short &y, unsigned short &z) const;
OcTreeNode &search(float x, float y, float z) const;
OcTreeNode &search(point3f p) const;
private:
// Loop-Up Table
static std::unordered_map<OcTreeHashKey, point3f> key_loc_map;
static std::unordered_map<unsigned short, OcTreeHashKey> index_map;
static float resolution;
static float size;
static unsigned short cell_num;
point3f center;
};
}
#endif // LA3DM_BGKLV_BLOCK_H
| 3,747 | 32.765766 | 131 | h |