Merge pull request #3506 from gwicke/path_newlines

Path: Opt into automatic git newline normalization
This commit is contained in:
sliptonic
2020-05-31 12:44:47 -05:00
committed by GitHub
96 changed files with 32403 additions and 32403 deletions

View File

@@ -77,6 +77,7 @@ JtReader export-ignore
# Fem/** -text
# Material/** -text
# OpenSCAD/** -text
# Path/** -text
# Show/** -text
# Tux/** -text
@@ -97,7 +98,6 @@ Mesh/** -text
MeshPart/** -text
Part/** -text
PartDesign/** -text
Path/** -text
Plot/** -text
Points/** -text
Raytracing/** -text

View File

@@ -1,99 +1,99 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include <Base/Console.h>
#include <Base/PyObjectBase.h>
#include <Base/Interpreter.h>
#include "Command.h"
#include "CommandPy.h"
#include "Path.h"
#include "PathPy.h"
#include "Tool.h"
#include "Tooltable.h"
#include "ToolPy.h"
#include "TooltablePy.h"
#include "PropertyPath.h"
#include "FeaturePath.h"
#include "PropertyTool.h"
#include "PropertyTooltable.h"
#include "FeaturePathCompound.h"
#include "FeaturePathShape.h"
#include "AreaPy.h"
#include "FeatureArea.h"
namespace Path {
extern PyObject* initModule();
}
/* Python entry */
PyMOD_INIT_FUNC(Path)
{
// load dependent module
try {
Base::Interpreter().runString("import Part");
}
catch(const Base::Exception& e) {
PyErr_SetString(PyExc_ImportError, e.what());
PyMOD_Return(NULL);
}
PyObject* pathModule = Path::initModule();
Base::Console().Log("Loading Path module... done\n");
// Add Types to module
Base::Interpreter().addType(&Path::CommandPy ::Type, pathModule, "Command");
Base::Interpreter().addType(&Path::PathPy ::Type, pathModule, "Path");
Base::Interpreter().addType(&Path::ToolPy ::Type, pathModule, "Tool");
Base::Interpreter().addType(&Path::TooltablePy ::Type, pathModule, "Tooltable");
Base::Interpreter().addType(&Path::AreaPy ::Type, pathModule, "Area");
// NOTE: To finish the initialization of our own type objects we must
// call PyType_Ready, otherwise we run into a segmentation fault, later on.
// This function is responsible for adding inherited slots from a type's base class.
Path::Command ::init();
Path::Toolpath ::init();
Path::Tool ::init();
Path::Tooltable ::init();
Path::PropertyPath ::init();
Path::Feature ::init();
Path::FeaturePython ::init();
Path::PropertyTool ::init();
Path::PropertyTooltable ::init();
Path::FeatureCompound ::init();
Path::FeatureCompoundPython ::init();
Path::FeatureShape ::init();
Path::FeatureShapePython ::init();
Path::Area ::init();
Path::FeatureArea ::init();
Path::FeatureAreaPython ::init();
Path::FeatureAreaView ::init();
Path::FeatureAreaViewPython ::init();
PyMOD_Return(pathModule);
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include <Base/Console.h>
#include <Base/PyObjectBase.h>
#include <Base/Interpreter.h>
#include "Command.h"
#include "CommandPy.h"
#include "Path.h"
#include "PathPy.h"
#include "Tool.h"
#include "Tooltable.h"
#include "ToolPy.h"
#include "TooltablePy.h"
#include "PropertyPath.h"
#include "FeaturePath.h"
#include "PropertyTool.h"
#include "PropertyTooltable.h"
#include "FeaturePathCompound.h"
#include "FeaturePathShape.h"
#include "AreaPy.h"
#include "FeatureArea.h"
namespace Path {
extern PyObject* initModule();
}
/* Python entry */
PyMOD_INIT_FUNC(Path)
{
// load dependent module
try {
Base::Interpreter().runString("import Part");
}
catch(const Base::Exception& e) {
PyErr_SetString(PyExc_ImportError, e.what());
PyMOD_Return(NULL);
}
PyObject* pathModule = Path::initModule();
Base::Console().Log("Loading Path module... done\n");
// Add Types to module
Base::Interpreter().addType(&Path::CommandPy ::Type, pathModule, "Command");
Base::Interpreter().addType(&Path::PathPy ::Type, pathModule, "Path");
Base::Interpreter().addType(&Path::ToolPy ::Type, pathModule, "Tool");
Base::Interpreter().addType(&Path::TooltablePy ::Type, pathModule, "Tooltable");
Base::Interpreter().addType(&Path::AreaPy ::Type, pathModule, "Area");
// NOTE: To finish the initialization of our own type objects we must
// call PyType_Ready, otherwise we run into a segmentation fault, later on.
// This function is responsible for adding inherited slots from a type's base class.
Path::Command ::init();
Path::Toolpath ::init();
Path::Tool ::init();
Path::Tooltable ::init();
Path::PropertyPath ::init();
Path::Feature ::init();
Path::FeaturePython ::init();
Path::PropertyTool ::init();
Path::PropertyTooltable ::init();
Path::FeatureCompound ::init();
Path::FeatureCompoundPython ::init();
Path::FeatureShape ::init();
Path::FeatureShapePython ::init();
Path::Area ::init();
Path::FeatureArea ::init();
Path::FeatureAreaPython ::init();
Path::FeatureAreaView ::init();
Path::FeatureAreaViewPython ::init();
PyMOD_Return(pathModule);
}

View File

@@ -1,441 +1,441 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include <CXX/Extensions.hxx>
#include <CXX/Objects.hxx>
#include <Base/Console.h>
#include <Base/VectorPy.h>
#include <Base/FileInfo.h>
#include <Base/Interpreter.h>
#include <App/Document.h>
#include <App/DocumentObjectPy.h>
#include <App/Application.h>
#include <Mod/Part/App/OCCError.h>
#include <Mod/Part/App/TopoShape.h>
#include <Mod/Part/App/TopoShapePy.h>
#include <Mod/Part/App/PartPyCXX.h>
#include <TopoDS.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopExp_Explorer.hxx>
#include <gp_Lin.hxx>
#include <BRep_Tool.hxx>
#include <BRepAdaptor_CompCurve.hxx>
#include <BRepAdaptor_HCompCurve.hxx>
#include <Approx_Curve3d.hxx>
#include <BRepAdaptor_HCurve.hxx>
#include "CommandPy.h"
#include "PathPy.h"
#include "Path.h"
#include "FeaturePath.h"
#include "FeaturePathCompound.h"
#include "Area.h"
#define PATH_CATCH catch (Standard_Failure &e) \
{ \
std::string str; \
Standard_CString msg = e.GetMessageString(); \
str += typeid(e).name(); \
str += " "; \
if (msg) {str += msg;} \
else {str += "No OCCT Exception Message";} \
Base::Console().Error(str.c_str()); \
PyErr_SetString(Part::PartExceptionOCCError,str.c_str()); \
} \
catch(Base::Exception &e) \
{ \
std::string str; \
str += "FreeCAD exception thrown ("; \
str += e.what(); \
str += ")"; \
e.ReportException(); \
PyErr_SetString(Base::BaseExceptionFreeCADError,str.c_str());\
} \
catch(std::exception &e) \
{ \
std::string str; \
str += "STL exception thrown ("; \
str += e.what(); \
str += ")"; \
Base::Console().Error(str.c_str()); \
PyErr_SetString(Base::BaseExceptionFreeCADError,str.c_str());\
} \
catch(const char *e) \
{ \
PyErr_SetString(Base::BaseExceptionFreeCADError,e); \
} throw Py::Exception();
namespace Path {
class Module : public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("Path")
{
add_varargs_method("write",&Module::write,
"write(object,filename): Exports a given path object to a GCode file"
);
add_varargs_method("read",&Module::read,
"read(filename,[document]): Imports a GCode file into the given document"
);
add_varargs_method("show",&Module::show,
"show(path,[string]): Add the path to the active document or create one if no document exists"
);
add_varargs_method("fromShape",&Module::fromShape,
"fromShape(Shape): Returns a Path object from a Part Shape (deprecated - use fromShapes() instead)"
);
add_keyword_method("fromShapes",&Module::fromShapes,
"fromShapes(shapes, start=Vector(), return_end=False" PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_PATH) ")\n"
"\nReturns a Path object from a list of shapes\n"
"\n* shapes: input list of shapes.\n"
"\n* start (Vector()): feed start position, and also serves as a hint of path entry.\n"
"\n* return_end (False): if True, returns tuple (path, endPosition).\n"
PARAM_PY_DOC(ARG, AREA_PARAMS_PATH)
);
add_keyword_method("sortWires",&Module::sortWires,
"sortWires(shapes, start=Vector(), "
PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_ARC_PLANE)
PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_SORT) ")\n"
"\nReturns (wires,end), where 'wires' is sorted across Z value and with optimized travel distance,\n"
"and 'end' is the ending position of the whole wires. If arc_plane==1, it returns (wires,end,arc_plane),\n"
"where arc_plane is the found plane if any, or unchanged.\n"
"\n* shapes: input shape list\n"
"\n* start (Vector()): optional start position.\n"
PARAM_PY_DOC(ARG, AREA_PARAMS_ARC_PLANE)
PARAM_PY_DOC(ARG, AREA_PARAMS_SORT)
);
initialize("This module is the Path module."); // register with Python
}
virtual ~Module() {}
private:
Py::Object write(const Py::Tuple& args)
{
char* Name;
PyObject* pObj;
if (!PyArg_ParseTuple(args.ptr(), "Oet",&pObj,"utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Base::FileInfo file(EncodedName.c_str());
if (PyObject_TypeCheck(pObj, &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(pObj)->getDocumentObjectPtr();
if (obj->getTypeId().isDerivedFrom(Base::Type::fromName("Path::Feature"))) {
const Toolpath& path = static_cast<Path::Feature*>(obj)->Path.getValue();
std::string gcode = path.toGCode();
std::ofstream ofile(EncodedName.c_str());
ofile << gcode;
ofile.close();
}
else {
throw Py::RuntimeError("The given file is not a path");
}
}
return Py::None();
}
Py::Object read(const Py::Tuple& args)
{
char* Name;
const char* DocName=0;
if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Base::FileInfo file(EncodedName.c_str());
if (!file.exists())
throw Py::RuntimeError("File doesn't exist");
App::Document *pcDoc;
if (DocName)
pcDoc = App::GetApplication().getDocument(DocName);
else
pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc)
pcDoc = App::GetApplication().newDocument(DocName);
try {
// read the gcode file
std::ifstream filestr(file.filePath().c_str());
std::stringstream buffer;
buffer << filestr.rdbuf();
std::string gcode = buffer.str();
Toolpath path;
path.setFromGCode(gcode);
Path::Feature *object = static_cast<Path::Feature *>(pcDoc->addObject("Path::Feature",file.fileNamePure().c_str()));
object->Path.setValue(path);
pcDoc->recompute();
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
Py::Object show(const Py::Tuple& args)
{
PyObject *pcObj;
char *name = "Path";
if (!PyArg_ParseTuple(args.ptr(), "O!|s", &(PathPy::Type), &pcObj, &name))
throw Py::Exception();
try {
App::Document *pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc)
pcDoc = App::GetApplication().newDocument();
PathPy* pPath = static_cast<PathPy*>(pcObj);
Path::Feature *pcFeature = static_cast<Path::Feature*>(pcDoc->addObject("Path::Feature", name));
Path::Toolpath* pa = pPath->getToolpathPtr();
if (!pa) {
throw Py::Exception(PyExc_ReferenceError, "object doesn't reference a valid path");
}
// copy the data
pcFeature->Path.setValue(*pa);
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
Py::Object fromShape(const Py::Tuple& args)
{
PyObject *pcObj;
if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj))
throw Py::Exception();
TopoDS_Shape shape;
try {
if (PyObject_TypeCheck(pcObj, &(Part::TopoShapePy::Type))) {
shape = static_cast<Part::TopoShapePy*>(pcObj)->getTopoShapePtr()->getShape();
} else {
throw Py::TypeError("the given object is not a shape");
}
if (!shape.IsNull()) {
if (shape.ShapeType() == TopAbs_WIRE) {
Path::Toolpath result;
bool first = true;
Base::Placement last;
TopExp_Explorer ExpEdges (shape,TopAbs_EDGE);
while (ExpEdges.More()) {
const TopoDS_Edge& edge = TopoDS::Edge(ExpEdges.Current());
TopExp_Explorer ExpVerts(edge,TopAbs_VERTEX);
bool vfirst = true;
while (ExpVerts.More()) {
const TopoDS_Vertex& vert = TopoDS::Vertex(ExpVerts.Current());
gp_Pnt pnt = BRep_Tool::Pnt(vert);
Base::Placement tpl;
tpl.setPosition(Base::Vector3d(pnt.X(),pnt.Y(),pnt.Z()));
if (first) {
// add first point as a G0 move
Path::Command cmd;
std::ostringstream ctxt;
ctxt << "G0 X" << tpl.getPosition().x << " Y" << tpl.getPosition().y << " Z" << tpl.getPosition().z;
cmd.setFromGCode(ctxt.str());
result.addCommand(cmd);
first = false;
vfirst = false;
} else {
if (vfirst)
vfirst = false;
else {
Path::Command cmd;
cmd.setFromPlacement(tpl);
// write arc data if needed
BRepAdaptor_Curve adapt(edge);
if (adapt.GetType() == GeomAbs_Circle) {
gp_Circ circ = adapt.Circle();
gp_Pnt c = circ.Location();
bool clockwise = false;
gp_Dir n = circ.Axis().Direction();
if (n.Z() < 0)
clockwise = true;
Base::Vector3d center = Base::Vector3d(c.X(),c.Y(),c.Z());
// center coords must be relative to last point
center -= last.getPosition();
cmd.setCenter(center,clockwise);
}
result.addCommand(cmd);
}
}
ExpVerts.Next();
last = tpl;
}
ExpEdges.Next();
}
return Py::asObject(new PathPy(new Path::Toolpath(result)));
} else {
throw Py::TypeError("the given shape must be a wire");
}
} else {
throw Py::TypeError("the given shape is empty");
}
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
}
Py::Object fromShapes(const Py::Tuple& args, const Py::Dict &kwds)
{
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_PATH)
PyObject *pShapes=NULL;
PyObject *start=NULL;
PyObject *return_end=Py_False;
static char* kwd_list[] = {"shapes", "start", "return_end",
PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_PATH), NULL};
if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(),
"O|O!O" PARAM_PY_KWDS(AREA_PARAMS_PATH),
kwd_list, &pShapes, &(Base::VectorPy::Type), &start, &return_end,
PARAM_REF(PARAM_FARG,AREA_PARAMS_PATH)))
throw Py::Exception();
std::list<TopoDS_Shape> shapes;
if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type)))
shapes.push_back(static_cast<Part::TopoShapePy*>(pShapes)->getTopoShapePtr()->getShape());
else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) ||
PyObject_TypeCheck(pShapes, &(PyTuple_Type)))
{
Py::Sequence shapeSeq(pShapes);
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) {
PyObject* item = (*it).ptr();
if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) {
PyErr_SetString(PyExc_TypeError, "non-shape object in sequence");
throw Py::Exception();
}
shapes.push_back(static_cast<Part::TopoShapePy*>(item)->getTopoShapePtr()->getShape());
}
}
gp_Pnt pstart;
if(start) {
Base::Vector3d vec = static_cast<Base::VectorPy*>(start)->value();
pstart.SetCoord(vec.x, vec.y, vec.z);
}
try {
gp_Pnt pend;
std::unique_ptr<Toolpath> path(new Toolpath);
Area::toPath(*path,shapes,start?&pstart:0, &pend,
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_PATH));
if(!PyObject_IsTrue(return_end))
return Py::asObject(new PathPy(path.release()));
Py::Tuple tuple(2);
tuple.setItem(0, Py::asObject(new PathPy(path.release())));
tuple.setItem(1, Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(),pend.Y(),pend.Z()))));
return tuple;
} PATH_CATCH
}
Py::Object sortWires(const Py::Tuple& args, const Py::Dict &kwds)
{
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_ARC_PLANE)
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_SORT)
PyObject *pShapes=NULL;
PyObject *start=NULL;
static char* kwd_list[] = {"shapes", "start",
PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_ARC_PLANE),
PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_SORT), NULL};
if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(),
"O|O!"
PARAM_PY_KWDS(AREA_PARAMS_ARC_PLANE)
PARAM_PY_KWDS(AREA_PARAMS_SORT),
kwd_list, &pShapes, &(Base::VectorPy::Type), &start,
PARAM_REF(PARAM_FARG,AREA_PARAMS_ARC_PLANE),
PARAM_REF(PARAM_FARG,AREA_PARAMS_SORT)))
throw Py::Exception();
std::list<TopoDS_Shape> shapes;
if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type)))
shapes.push_back(static_cast<Part::TopoShapePy*>(pShapes)->getTopoShapePtr()->getShape());
else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) ||
PyObject_TypeCheck(pShapes, &(PyTuple_Type))) {
Py::Sequence shapeSeq(pShapes);
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) {
PyObject* item = (*it).ptr();
if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) {
PyErr_SetString(PyExc_TypeError, "non-shape object in sequence");
throw Py::Exception();
}
shapes.push_back(static_cast<Part::TopoShapePy*>(item)->getTopoShapePtr()->getShape());
}
}
gp_Pnt pstart,pend;
if(start) {
Base::Vector3d vec = static_cast<Base::VectorPy*>(start)->value();
pstart.SetCoord(vec.x, vec.y, vec.z);
}
try {
bool need_arc_plane = arc_plane==Area::ArcPlaneAuto;
std::list<TopoDS_Shape> wires = Area::sortWires(shapes,start!=0,&pstart,
&pend, 0, &arc_plane, PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_SORT));
PyObject *list = PyList_New(0);
for(auto &wire : wires)
PyList_Append(list,Py::new_reference_to(
Part::shape2pyshape(TopoDS::Wire(wire))));
PyObject *ret = PyTuple_New(need_arc_plane?3:2);
PyTuple_SetItem(ret,0,list);
PyTuple_SetItem(ret,1,new Base::VectorPy(
Base::Vector3d(pend.X(),pend.Y(),pend.Z())));
if(need_arc_plane)
#if PY_MAJOR_VERSION < 3
PyTuple_SetItem(ret,2,PyInt_FromLong(arc_plane));
#else
PyTuple_SetItem(ret,2,PyLong_FromLong(arc_plane));
#endif
return Py::asObject(ret);
} PATH_CATCH
}
};
PyObject* initModule()
{
return (new Module)->module().ptr();
}
} // namespace Path
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include <CXX/Extensions.hxx>
#include <CXX/Objects.hxx>
#include <Base/Console.h>
#include <Base/VectorPy.h>
#include <Base/FileInfo.h>
#include <Base/Interpreter.h>
#include <App/Document.h>
#include <App/DocumentObjectPy.h>
#include <App/Application.h>
#include <Mod/Part/App/OCCError.h>
#include <Mod/Part/App/TopoShape.h>
#include <Mod/Part/App/TopoShapePy.h>
#include <Mod/Part/App/PartPyCXX.h>
#include <TopoDS.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopExp_Explorer.hxx>
#include <gp_Lin.hxx>
#include <BRep_Tool.hxx>
#include <BRepAdaptor_CompCurve.hxx>
#include <BRepAdaptor_HCompCurve.hxx>
#include <Approx_Curve3d.hxx>
#include <BRepAdaptor_HCurve.hxx>
#include "CommandPy.h"
#include "PathPy.h"
#include "Path.h"
#include "FeaturePath.h"
#include "FeaturePathCompound.h"
#include "Area.h"
#define PATH_CATCH catch (Standard_Failure &e) \
{ \
std::string str; \
Standard_CString msg = e.GetMessageString(); \
str += typeid(e).name(); \
str += " "; \
if (msg) {str += msg;} \
else {str += "No OCCT Exception Message";} \
Base::Console().Error(str.c_str()); \
PyErr_SetString(Part::PartExceptionOCCError,str.c_str()); \
} \
catch(Base::Exception &e) \
{ \
std::string str; \
str += "FreeCAD exception thrown ("; \
str += e.what(); \
str += ")"; \
e.ReportException(); \
PyErr_SetString(Base::BaseExceptionFreeCADError,str.c_str());\
} \
catch(std::exception &e) \
{ \
std::string str; \
str += "STL exception thrown ("; \
str += e.what(); \
str += ")"; \
Base::Console().Error(str.c_str()); \
PyErr_SetString(Base::BaseExceptionFreeCADError,str.c_str());\
} \
catch(const char *e) \
{ \
PyErr_SetString(Base::BaseExceptionFreeCADError,e); \
} throw Py::Exception();
namespace Path {
class Module : public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("Path")
{
add_varargs_method("write",&Module::write,
"write(object,filename): Exports a given path object to a GCode file"
);
add_varargs_method("read",&Module::read,
"read(filename,[document]): Imports a GCode file into the given document"
);
add_varargs_method("show",&Module::show,
"show(path,[string]): Add the path to the active document or create one if no document exists"
);
add_varargs_method("fromShape",&Module::fromShape,
"fromShape(Shape): Returns a Path object from a Part Shape (deprecated - use fromShapes() instead)"
);
add_keyword_method("fromShapes",&Module::fromShapes,
"fromShapes(shapes, start=Vector(), return_end=False" PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_PATH) ")\n"
"\nReturns a Path object from a list of shapes\n"
"\n* shapes: input list of shapes.\n"
"\n* start (Vector()): feed start position, and also serves as a hint of path entry.\n"
"\n* return_end (False): if True, returns tuple (path, endPosition).\n"
PARAM_PY_DOC(ARG, AREA_PARAMS_PATH)
);
add_keyword_method("sortWires",&Module::sortWires,
"sortWires(shapes, start=Vector(), "
PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_ARC_PLANE)
PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_SORT) ")\n"
"\nReturns (wires,end), where 'wires' is sorted across Z value and with optimized travel distance,\n"
"and 'end' is the ending position of the whole wires. If arc_plane==1, it returns (wires,end,arc_plane),\n"
"where arc_plane is the found plane if any, or unchanged.\n"
"\n* shapes: input shape list\n"
"\n* start (Vector()): optional start position.\n"
PARAM_PY_DOC(ARG, AREA_PARAMS_ARC_PLANE)
PARAM_PY_DOC(ARG, AREA_PARAMS_SORT)
);
initialize("This module is the Path module."); // register with Python
}
virtual ~Module() {}
private:
Py::Object write(const Py::Tuple& args)
{
char* Name;
PyObject* pObj;
if (!PyArg_ParseTuple(args.ptr(), "Oet",&pObj,"utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Base::FileInfo file(EncodedName.c_str());
if (PyObject_TypeCheck(pObj, &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(pObj)->getDocumentObjectPtr();
if (obj->getTypeId().isDerivedFrom(Base::Type::fromName("Path::Feature"))) {
const Toolpath& path = static_cast<Path::Feature*>(obj)->Path.getValue();
std::string gcode = path.toGCode();
std::ofstream ofile(EncodedName.c_str());
ofile << gcode;
ofile.close();
}
else {
throw Py::RuntimeError("The given file is not a path");
}
}
return Py::None();
}
Py::Object read(const Py::Tuple& args)
{
char* Name;
const char* DocName=0;
if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Base::FileInfo file(EncodedName.c_str());
if (!file.exists())
throw Py::RuntimeError("File doesn't exist");
App::Document *pcDoc;
if (DocName)
pcDoc = App::GetApplication().getDocument(DocName);
else
pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc)
pcDoc = App::GetApplication().newDocument(DocName);
try {
// read the gcode file
std::ifstream filestr(file.filePath().c_str());
std::stringstream buffer;
buffer << filestr.rdbuf();
std::string gcode = buffer.str();
Toolpath path;
path.setFromGCode(gcode);
Path::Feature *object = static_cast<Path::Feature *>(pcDoc->addObject("Path::Feature",file.fileNamePure().c_str()));
object->Path.setValue(path);
pcDoc->recompute();
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
Py::Object show(const Py::Tuple& args)
{
PyObject *pcObj;
char *name = "Path";
if (!PyArg_ParseTuple(args.ptr(), "O!|s", &(PathPy::Type), &pcObj, &name))
throw Py::Exception();
try {
App::Document *pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc)
pcDoc = App::GetApplication().newDocument();
PathPy* pPath = static_cast<PathPy*>(pcObj);
Path::Feature *pcFeature = static_cast<Path::Feature*>(pcDoc->addObject("Path::Feature", name));
Path::Toolpath* pa = pPath->getToolpathPtr();
if (!pa) {
throw Py::Exception(PyExc_ReferenceError, "object doesn't reference a valid path");
}
// copy the data
pcFeature->Path.setValue(*pa);
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
Py::Object fromShape(const Py::Tuple& args)
{
PyObject *pcObj;
if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj))
throw Py::Exception();
TopoDS_Shape shape;
try {
if (PyObject_TypeCheck(pcObj, &(Part::TopoShapePy::Type))) {
shape = static_cast<Part::TopoShapePy*>(pcObj)->getTopoShapePtr()->getShape();
} else {
throw Py::TypeError("the given object is not a shape");
}
if (!shape.IsNull()) {
if (shape.ShapeType() == TopAbs_WIRE) {
Path::Toolpath result;
bool first = true;
Base::Placement last;
TopExp_Explorer ExpEdges (shape,TopAbs_EDGE);
while (ExpEdges.More()) {
const TopoDS_Edge& edge = TopoDS::Edge(ExpEdges.Current());
TopExp_Explorer ExpVerts(edge,TopAbs_VERTEX);
bool vfirst = true;
while (ExpVerts.More()) {
const TopoDS_Vertex& vert = TopoDS::Vertex(ExpVerts.Current());
gp_Pnt pnt = BRep_Tool::Pnt(vert);
Base::Placement tpl;
tpl.setPosition(Base::Vector3d(pnt.X(),pnt.Y(),pnt.Z()));
if (first) {
// add first point as a G0 move
Path::Command cmd;
std::ostringstream ctxt;
ctxt << "G0 X" << tpl.getPosition().x << " Y" << tpl.getPosition().y << " Z" << tpl.getPosition().z;
cmd.setFromGCode(ctxt.str());
result.addCommand(cmd);
first = false;
vfirst = false;
} else {
if (vfirst)
vfirst = false;
else {
Path::Command cmd;
cmd.setFromPlacement(tpl);
// write arc data if needed
BRepAdaptor_Curve adapt(edge);
if (adapt.GetType() == GeomAbs_Circle) {
gp_Circ circ = adapt.Circle();
gp_Pnt c = circ.Location();
bool clockwise = false;
gp_Dir n = circ.Axis().Direction();
if (n.Z() < 0)
clockwise = true;
Base::Vector3d center = Base::Vector3d(c.X(),c.Y(),c.Z());
// center coords must be relative to last point
center -= last.getPosition();
cmd.setCenter(center,clockwise);
}
result.addCommand(cmd);
}
}
ExpVerts.Next();
last = tpl;
}
ExpEdges.Next();
}
return Py::asObject(new PathPy(new Path::Toolpath(result)));
} else {
throw Py::TypeError("the given shape must be a wire");
}
} else {
throw Py::TypeError("the given shape is empty");
}
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
}
Py::Object fromShapes(const Py::Tuple& args, const Py::Dict &kwds)
{
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_PATH)
PyObject *pShapes=NULL;
PyObject *start=NULL;
PyObject *return_end=Py_False;
static char* kwd_list[] = {"shapes", "start", "return_end",
PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_PATH), NULL};
if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(),
"O|O!O" PARAM_PY_KWDS(AREA_PARAMS_PATH),
kwd_list, &pShapes, &(Base::VectorPy::Type), &start, &return_end,
PARAM_REF(PARAM_FARG,AREA_PARAMS_PATH)))
throw Py::Exception();
std::list<TopoDS_Shape> shapes;
if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type)))
shapes.push_back(static_cast<Part::TopoShapePy*>(pShapes)->getTopoShapePtr()->getShape());
else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) ||
PyObject_TypeCheck(pShapes, &(PyTuple_Type)))
{
Py::Sequence shapeSeq(pShapes);
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) {
PyObject* item = (*it).ptr();
if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) {
PyErr_SetString(PyExc_TypeError, "non-shape object in sequence");
throw Py::Exception();
}
shapes.push_back(static_cast<Part::TopoShapePy*>(item)->getTopoShapePtr()->getShape());
}
}
gp_Pnt pstart;
if(start) {
Base::Vector3d vec = static_cast<Base::VectorPy*>(start)->value();
pstart.SetCoord(vec.x, vec.y, vec.z);
}
try {
gp_Pnt pend;
std::unique_ptr<Toolpath> path(new Toolpath);
Area::toPath(*path,shapes,start?&pstart:0, &pend,
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_PATH));
if(!PyObject_IsTrue(return_end))
return Py::asObject(new PathPy(path.release()));
Py::Tuple tuple(2);
tuple.setItem(0, Py::asObject(new PathPy(path.release())));
tuple.setItem(1, Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(),pend.Y(),pend.Z()))));
return tuple;
} PATH_CATCH
}
Py::Object sortWires(const Py::Tuple& args, const Py::Dict &kwds)
{
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_ARC_PLANE)
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_SORT)
PyObject *pShapes=NULL;
PyObject *start=NULL;
static char* kwd_list[] = {"shapes", "start",
PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_ARC_PLANE),
PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_SORT), NULL};
if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(),
"O|O!"
PARAM_PY_KWDS(AREA_PARAMS_ARC_PLANE)
PARAM_PY_KWDS(AREA_PARAMS_SORT),
kwd_list, &pShapes, &(Base::VectorPy::Type), &start,
PARAM_REF(PARAM_FARG,AREA_PARAMS_ARC_PLANE),
PARAM_REF(PARAM_FARG,AREA_PARAMS_SORT)))
throw Py::Exception();
std::list<TopoDS_Shape> shapes;
if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type)))
shapes.push_back(static_cast<Part::TopoShapePy*>(pShapes)->getTopoShapePtr()->getShape());
else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) ||
PyObject_TypeCheck(pShapes, &(PyTuple_Type))) {
Py::Sequence shapeSeq(pShapes);
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) {
PyObject* item = (*it).ptr();
if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) {
PyErr_SetString(PyExc_TypeError, "non-shape object in sequence");
throw Py::Exception();
}
shapes.push_back(static_cast<Part::TopoShapePy*>(item)->getTopoShapePtr()->getShape());
}
}
gp_Pnt pstart,pend;
if(start) {
Base::Vector3d vec = static_cast<Base::VectorPy*>(start)->value();
pstart.SetCoord(vec.x, vec.y, vec.z);
}
try {
bool need_arc_plane = arc_plane==Area::ArcPlaneAuto;
std::list<TopoDS_Shape> wires = Area::sortWires(shapes,start!=0,&pstart,
&pend, 0, &arc_plane, PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_SORT));
PyObject *list = PyList_New(0);
for(auto &wire : wires)
PyList_Append(list,Py::new_reference_to(
Part::shape2pyshape(TopoDS::Wire(wire))));
PyObject *ret = PyTuple_New(need_arc_plane?3:2);
PyTuple_SetItem(ret,0,list);
PyTuple_SetItem(ret,1,new Base::VectorPy(
Base::Vector3d(pend.X(),pend.Y(),pend.Z())));
if(need_arc_plane)
#if PY_MAJOR_VERSION < 3
PyTuple_SetItem(ret,2,PyInt_FromLong(arc_plane));
#else
PyTuple_SetItem(ret,2,PyLong_FromLong(arc_plane));
#endif
return Py::asObject(ret);
} PATH_CATCH
}
};
PyObject* initModule()
{
return (new Module)->module().ptr();
}
} // namespace Path

View File

@@ -1,107 +1,107 @@
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="BaseClassPy"
Name="AreaPy"
Twin="Area"
TwinPointer="Area"
Include="Mod/Path/App/Area.h"
Namespace="Path"
FatherInclude="Base/BaseClassPy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Zheng, Lei" EMail="realthunder.dev@gmail.com" />
<UserDocu>FreeCAD python wrapper of libarea\n
Path.Area(key=value ...)\n
The constructor accepts the same parameters as setParams(...) to configure the object
All arguments are optional.</UserDocu>
</Documentation>
<Methode Name="add" Keyword='true'>
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="setPlane">
<Documentation>
<UserDocu>setPlane(shape): Set the working plane.\n
The supplied shape does not need to be planar. Area will try to find planar
sub-shape (face, wire or edge). If more than one planar sub-shape is found, it
will prefer the top plane parallel to XY0 plane. If no working plane are set,
Area will try to find a working plane from the added children shape using the
same algorithm</UserDocu>
</Documentation>
</Methode>
<Methode Name="getShape" Keyword='true'>
<Documentation>
<UserDocu>getShape(index=-1,rebuild=False): Return the resulting shape\n
\n* index (-1): the index of the section. -1 means all sections. No effect on planar shape.\n
\n* rebuild: clean the internal cache and rebuild</UserDocu>
</Documentation>
</Methode>
<Methode Name="makeOffset" Keyword='true'>
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="makePocket" Keyword='true'>
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="makeSections" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="setParams" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="setDefaultParams" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="getDefaultParams">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="getParamsDesc" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="getParams">
<Documentation>
<UserDocu>Get current algorithm parameters as a dictionary.</UserDocu>
</Documentation>
</Methode>
<Methode Name="abort" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Attribute Name="Sections" ReadOnly="true">
<Documentation>
<UserDocu>List of sections in this area.</UserDocu>
</Documentation>
<Parameter Name="Sections" Type="List"/>
</Attribute>
<Attribute Name="Workplane" ReadOnly="false">
<Documentation>
<UserDocu>The current workplane. If no plane is set, it is derived from the added shapes.</UserDocu>
</Documentation>
<Parameter Name="Workplane" Type="Object"/>
</Attribute>
<Attribute Name="Shapes" ReadOnly="true">
<Documentation>
<UserDocu>A list of tuple: [(shape,op), ...] containing the added shapes together with their operation code</UserDocu>
</Documentation>
<Parameter Name="Shapes" Type="List"/>
</Attribute>
</PythonExport>
</GenerateModel>
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="BaseClassPy"
Name="AreaPy"
Twin="Area"
TwinPointer="Area"
Include="Mod/Path/App/Area.h"
Namespace="Path"
FatherInclude="Base/BaseClassPy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Zheng, Lei" EMail="realthunder.dev@gmail.com" />
<UserDocu>FreeCAD python wrapper of libarea\n
Path.Area(key=value ...)\n
The constructor accepts the same parameters as setParams(...) to configure the object
All arguments are optional.</UserDocu>
</Documentation>
<Methode Name="add" Keyword='true'>
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="setPlane">
<Documentation>
<UserDocu>setPlane(shape): Set the working plane.\n
The supplied shape does not need to be planar. Area will try to find planar
sub-shape (face, wire or edge). If more than one planar sub-shape is found, it
will prefer the top plane parallel to XY0 plane. If no working plane are set,
Area will try to find a working plane from the added children shape using the
same algorithm</UserDocu>
</Documentation>
</Methode>
<Methode Name="getShape" Keyword='true'>
<Documentation>
<UserDocu>getShape(index=-1,rebuild=False): Return the resulting shape\n
\n* index (-1): the index of the section. -1 means all sections. No effect on planar shape.\n
\n* rebuild: clean the internal cache and rebuild</UserDocu>
</Documentation>
</Methode>
<Methode Name="makeOffset" Keyword='true'>
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="makePocket" Keyword='true'>
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="makeSections" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="setParams" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="setDefaultParams" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="getDefaultParams">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="getParamsDesc" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Methode Name="getParams">
<Documentation>
<UserDocu>Get current algorithm parameters as a dictionary.</UserDocu>
</Documentation>
</Methode>
<Methode Name="abort" Keyword="true">
<Documentation>
<UserDocu></UserDocu>
</Documentation>
</Methode>
<Attribute Name="Sections" ReadOnly="true">
<Documentation>
<UserDocu>List of sections in this area.</UserDocu>
</Documentation>
<Parameter Name="Sections" Type="List"/>
</Attribute>
<Attribute Name="Workplane" ReadOnly="false">
<Documentation>
<UserDocu>The current workplane. If no plane is set, it is derived from the added shapes.</UserDocu>
</Documentation>
<Parameter Name="Workplane" Type="Object"/>
</Attribute>
<Attribute Name="Shapes" ReadOnly="true">
<Documentation>
<UserDocu>A list of tuple: [(shape,op), ...] containing the added shapes together with their operation code</UserDocu>
</Documentation>
<Parameter Name="Shapes" Type="List"/>
</Attribute>
</PythonExport>
</GenerateModel>

View File

@@ -1,488 +1,488 @@
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#include <Mod/Part/App/OCCError.h>
#include <Mod/Part/App/TopoShapePy.h>
#include <Base/VectorPy.h>
#include "Area.h"
// inclusion of the generated files (generated out of AreaPy.xml)
#include "AreaPy.h"
#include "AreaPy.cpp"
static PyObject * areaAbort(PyObject *, PyObject *args, PyObject *kwd) {
static char *kwlist[] = {"aborting", NULL};
PyObject *pObj = Py_True;
if (!PyArg_ParseTupleAndKeywords(args,kwd,"|O",kwlist,&pObj))
return 0;
Area::abort(PyObject_IsTrue(pObj));
Py_INCREF(Py_None);
return Py_None;
}
static PyObject * areaSetParams(PyObject *, PyObject *args, PyObject *kwd) {
static char *kwlist[] = {PARAM_FIELD_STRINGS(NAME,AREA_PARAMS_STATIC_CONF),NULL};
if(args && PySequence_Size(args)>0)
PyErr_SetString(PyExc_ValueError,"Non-keyword argument is not supported");
//Declare variables defined in the NAME field of the CONF parameter list
PARAM_PY_DECLARE(PARAM_FNAME,AREA_PARAMS_STATIC_CONF);
AreaStaticParams params = Area::getDefaultParams();
#define AREA_SET(_param) \
PARAM_FNAME(_param) = \
PARAM_TYPED(PARAM_PY_CAST_,_param)(params.PARAM_FNAME(_param));
//populate the CONF variables with params
PARAM_FOREACH(AREA_SET,AREA_PARAMS_STATIC_CONF)
//Parse arguments to overwrite CONF variables
if (!PyArg_ParseTupleAndKeywords(args, kwd,
"|" PARAM_PY_KWDS(AREA_PARAMS_STATIC_CONF), kwlist,
PARAM_REF(PARAM_FNAME,AREA_PARAMS_STATIC_CONF)))
return 0;
#define AREA_GET(_param) \
params.PARAM_FNAME(_param) = \
PARAM_TYPED(PARAM_CAST_PY_,_param)(PARAM_FNAME(_param));
//populate 'params' with the CONF variables
PARAM_FOREACH(AREA_GET,AREA_PARAMS_STATIC_CONF)
Area::setDefaultParams(params);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* areaGetParams(PyObject *, PyObject *args) {
if (!PyArg_ParseTuple(args, ""))
return 0;
const AreaStaticParams &params = Area::getDefaultParams();
PyObject *dict = PyDict_New();
#define AREA_SRC(_param) params.PARAM_FNAME(_param)
PARAM_PY_DICT_SET_VALUE(dict,NAME,AREA_SRC,AREA_PARAMS_STATIC_CONF)
return dict;
}
static PyObject * areaGetParamsDesc(PyObject *, PyObject *args, PyObject *kwd) {
PyObject *pcObj = Py_False;
static char *kwlist[] = {"as_string", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwd, "|O",kwlist,&pcObj))
return 0;
#if PY_MAJOR_VERSION < 3
if(PyObject_IsTrue(pcObj))
return PyString_FromString(PARAM_PY_DOC(NAME,AREA_PARAMS_STATIC_CONF));
#else
if(PyObject_IsTrue(pcObj))
return PyUnicode_FromString(PARAM_PY_DOC(NAME,AREA_PARAMS_STATIC_CONF));
#endif
PyObject *dict = PyDict_New();
PARAM_PY_DICT_SET_DOC(dict,NAME,AREA_PARAMS_STATIC_CONF)
return dict;
}
static const PyMethodDef areaOverrides[] = {
{
"setParams",NULL,0,
"setParam(key=value...): Set algorithm parameters. You can call getParamsDesc() to \n"
"get a list of supported parameters and their descriptions.\n"
PARAM_PY_DOC(NAME,AREA_PARAMS_CONF)
},
{
"add",NULL,0,
"add((shape...)," PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_OPCODE) "):\n"
"Add TopoShape(s) with given operation code\n"
PARAM_PY_DOC(ARG,AREA_PARAMS_OPCODE)
"\nThe first shape's wires will be unioned together regardless of the op code given\n"
"(except for 'Compound'). Subsequent shape's wire will be combined using the op code.\n"
"All shape wires shall be coplanar, and are used to determine a working plane for face\n"
"making and offsetting. You can call setPlane() to supply a reference shape to determine\n"
"the workplane in case the added shapes are all colinear lines.\n",
},
{
"makeOffset",NULL,0,
"makeOffset(index=-1, " PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_OFFSET) "):\n"
"Make an 2D offset of the shape.\n"
"\n* index (-1): the index of the section. -1 means all sections. No effect on planar shape.\n"
PARAM_PY_DOC(ARG,AREA_PARAMS_OFFSET),
},
{
"makePocket",NULL,0,
"makePocket(index=-1, " PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_POCKET) "):\n"
"Generate pocket toolpath of the shape.\n"
"\n* index (-1): the index of the section. -1 means all sections. No effect on planar shape.\n"
PARAM_PY_DOC(ARG,AREA_PARAMS_POCKET),
},
{
"makeSections",NULL,0,
"makeSections(" PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_SECTION_EXTRA) ", heights=[], plane=None):\n"
"Make a list of area holding the sectioned children shapes on given heights\n"
PARAM_PY_DOC(ARG,AREA_PARAMS_SECTION_EXTRA)
"\n* heights ([]): a list of section heights, the meaning of the value is determined by 'mode'.\n"
"If not specified, the current SectionCount, and SectionOffset of this Area is used.\n"
"\n* plane (None): optional shape to specify a section plane. If not give, the current workplane\n"
"of this Area is used if section mode is 'Workplane'.",
},
{
"setDefaultParams",reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(areaSetParams)), METH_VARARGS|METH_KEYWORDS|METH_STATIC,
"setDefaultParams(key=value...):\n"
"Static method to set the default parameters of all following Path.Area, plus the following\n"
"additional parameters.\n"
},
{
"getDefaultParams",(PyCFunction)areaGetParams, METH_VARARGS|METH_STATIC,
"getDefaultParams(): Static method to return the current default parameters."
},
{
"abort",reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(areaAbort)), METH_VARARGS|METH_KEYWORDS|METH_STATIC,
"abort(aborting=True): Static method to abort any ongoing operation\n"
"\nTo ensure no stray abortion is left in the previous operation, it is advised to manually clear\n"
"the aborting flag by calling abort(False) before starting a new operation.",
},
{
"getParamsDesc",reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(areaGetParamsDesc)), METH_VARARGS|METH_KEYWORDS|METH_STATIC,
"getParamsDesc(as_string=False): Returns a list of supported parameters and their descriptions.\n"
"\n* as_string: if False, then return a dictionary of documents of all supported parameters."
},
};
struct AreaPyModifier {
AreaPyModifier() {
for(auto &method : Path::AreaPy::Methods) {
if(!method.ml_name) continue;
for(auto &entry : areaOverrides) {
if(std::strcmp(method.ml_name,entry.ml_name)==0) {
if(entry.ml_doc)
method.ml_doc = entry.ml_doc;
if(entry.ml_meth)
method.ml_meth = entry.ml_meth;
if(entry.ml_flags)
method.ml_flags = entry.ml_flags;
break;
}
}
}
}
};
static AreaPyModifier mod;
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string AreaPy::representation(void) const
{
std::stringstream str;
str << "<Area object at " << getAreaPtr() << ">";
return str.str();
}
PyObject *AreaPy::PyMake(struct _typeobject *, PyObject *args, PyObject *kwd) // Python wrapper
{
AreaPy* ret = new AreaPy(new Area);
if(!ret->setParams(args,kwd)) {
Py_DecRef(ret);
return 0;
}
return ret;
}
// constructor method
int AreaPy::PyInit(PyObject* , PyObject* )
{
return 0;
}
PyObject* AreaPy::setPlane(PyObject *args) {
PyObject *pcObj;
if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &pcObj))
return 0;
#define GET_TOPOSHAPE(_p) static_cast<Part::TopoShapePy*>(_p)->getTopoShapePtr()->getShape()
getAreaPtr()->setPlane(GET_TOPOSHAPE(pcObj));
Py_INCREF(this);
return this;
}
PyObject* AreaPy::getShape(PyObject *args, PyObject *keywds)
{
PyObject *pcObj = Py_False;
short index=-1;
static char *kwlist[] = {"index","rebuild", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds,"|hO",kwlist,&index,&pcObj))
return 0;
PY_TRY {
if(PyObject_IsTrue(pcObj))
getAreaPtr()->clean();
return Py::new_reference_to(Part::shape2pyshape(getAreaPtr()->getShape(index)));
} PY_CATCH_OCC
}
PyObject* AreaPy::add(PyObject *args, PyObject *keywds)
{
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_OPCODE)
PyObject *pcObj;
//Strangely, PyArg_ParseTupleAndKeywords requires all arguments to be keyword based,
//even non-optional ones? That doesn't make sense in python. Seems only in python 3
//they added '$' to address that issue.
static char *kwlist[] = {"shape",PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_OPCODE), NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"O|" PARAM_PY_KWDS(AREA_PARAMS_OPCODE),
kwlist,&pcObj,PARAM_REF(PARAM_FARG,AREA_PARAMS_OPCODE)))
return 0;
PY_TRY {
if (PyObject_TypeCheck(pcObj, &(Part::TopoShapePy::Type))) {
getAreaPtr()->add(GET_TOPOSHAPE(pcObj),op);
Py_INCREF(this);
return this;
} else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) ||
PyObject_TypeCheck(pcObj, &(PyTuple_Type))) {
Py::Sequence shapeSeq(pcObj);
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) {
PyObject* item = (*it).ptr();
if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) {
PyErr_SetString(PyExc_TypeError, "non-shape object in sequence");
return 0;
}
}
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it){
PyObject* item = (*it).ptr();
getAreaPtr()->add(GET_TOPOSHAPE(item),
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_OPCODE));
}
Py_INCREF(this);
return this;
}
} PY_CATCH_OCC
PyErr_SetString(PyExc_TypeError, "shape must be 'TopoShape' or list of 'TopoShape'");
return 0;
}
PyObject* AreaPy::makeOffset(PyObject *args, PyObject *keywds)
{
//Generate a keyword string defined in the ARG field of OFFSET parameter list
static char *kwlist[] = {"index",PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_OFFSET), NULL};
short index = -1;
//Declare variables defined in the ARG field of the OFFSET parameter list with
//initialization to defaults
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_OFFSET)
//Parse arguments to overwrite the defaults
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|h" PARAM_PY_KWDS(AREA_PARAMS_OFFSET), kwlist,
&index,PARAM_REF(PARAM_FARG,AREA_PARAMS_OFFSET)))
return 0;
PY_TRY {
//Expand the variable as function call arguments
TopoDS_Shape resultShape = getAreaPtr()->makeOffset(index,
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_OFFSET));
return Py::new_reference_to(Part::shape2pyshape(resultShape));
} PY_CATCH_OCC
}
PyObject* AreaPy::makePocket(PyObject *args, PyObject *keywds)
{
static char *kwlist[] = {"index",PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_POCKET), NULL};
short index = -1;
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_POCKET)
//Override pocket mode default
mode = Area::PocketModeZigZagOffset;
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|h" PARAM_PY_KWDS(AREA_PARAMS_POCKET), kwlist,
&index,PARAM_REF(PARAM_FARG,AREA_PARAMS_POCKET)))
return 0;
PY_TRY {
TopoDS_Shape resultShape = getAreaPtr()->makePocket(index,
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_POCKET));
return Py::new_reference_to(Part::shape2pyshape(resultShape));
} PY_CATCH_OCC
}
PyObject* AreaPy::makeSections(PyObject *args, PyObject *keywds)
{
static char *kwlist[] = {PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_SECTION_EXTRA),
"heights", "plane", NULL};
PyObject *heights = NULL;
PyObject *plane = NULL;
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_SECTION_EXTRA)
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|" PARAM_PY_KWDS(AREA_PARAMS_SECTION_EXTRA) "OO!", kwlist,
PARAM_REF(PARAM_FARG,AREA_PARAMS_SECTION_EXTRA),
&heights, &(Part::TopoShapePy::Type), &plane))
return 0;
PY_TRY {
std::vector<double> h;
if(heights) {
if (PyObject_TypeCheck(heights, &(PyFloat_Type)))
h.push_back(PyFloat_AsDouble(heights));
else if (PyObject_TypeCheck(heights, &(PyList_Type)) ||
PyObject_TypeCheck(heights, &(PyTuple_Type))) {
Py::Sequence shapeSeq(heights);
h.reserve(shapeSeq.size());
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) {
PyObject* item = (*it).ptr();
if(!PyObject_TypeCheck(item, &(PyFloat_Type))) {
PyErr_SetString(PyExc_TypeError, "heights must only contain float type");
return 0;
}
h.push_back(PyFloat_AsDouble(item));
}
}else{
PyErr_SetString(PyExc_TypeError, "heights must be of type float or list/tuple of float");
return 0;
}
}
std::vector<std::shared_ptr<Area> > sections = getAreaPtr()->makeSections(
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_SECTION_EXTRA),
h,plane?GET_TOPOSHAPE(plane):TopoDS_Shape());
Py::List ret;
for(auto &area : sections)
ret.append(Py::asObject(new AreaPy(new Area(*area,true))));
return Py::new_reference_to(ret);
} PY_CATCH_OCC
}
PyObject* AreaPy::setDefaultParams(PyObject *, PyObject *)
{
return 0;
}
PyObject* AreaPy::setParams(PyObject *args, PyObject *keywds)
{
static char *kwlist[] = {PARAM_FIELD_STRINGS(NAME,AREA_PARAMS_CONF),NULL};
//Declare variables defined in the NAME field of the CONF parameter list
PARAM_PY_DECLARE(PARAM_FNAME,AREA_PARAMS_CONF);
AreaParams params = getAreaPtr()->getParams();
//populate the CONF variables with params
PARAM_FOREACH(AREA_SET,AREA_PARAMS_CONF)
//Parse arguments to overwrite CONF variables
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|" PARAM_PY_KWDS(AREA_PARAMS_CONF), kwlist,
PARAM_REF(PARAM_FNAME,AREA_PARAMS_CONF)))
return 0;
PY_TRY {
//populate 'params' with the CONF variables
PARAM_FOREACH(AREA_GET,AREA_PARAMS_CONF)
getAreaPtr()->setParams(params);
Py_INCREF(this);
return this;
} PY_CATCH_OCC
}
PyObject* AreaPy::getParams(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
const AreaParams &params =getAreaPtr()->getParams();
PyObject *dict = PyDict_New();
PARAM_PY_DICT_SET_VALUE(dict,NAME,AREA_SRC,AREA_PARAMS_CONF)
return dict;
}
PyObject* AreaPy::getDefaultParams(PyObject *)
{
return 0;
}
PyObject* AreaPy::abort(PyObject *, PyObject *) {
return 0;
}
PyObject* AreaPy::getParamsDesc(PyObject *, PyObject *)
{
return 0;
}
Py::List AreaPy::getSections(void) const {
Py::List ret;
Area *area = getAreaPtr();
for(size_t i=0,count=area->getSectionCount(); i<count;++i)
ret.append(Part::shape2pyshape(getAreaPtr()->getShape(i)));
return ret;
}
Py::List AreaPy::getShapes(void) const {
Py::List ret;
Area *area = getAreaPtr();
const std::list<Area::Shape> &shapes = area->getChildren();
for(auto &s : shapes)
ret.append(Py::TupleN(Part::shape2pyshape(s.shape),Py::Int(s.op)));
return ret;
}
Py::Object AreaPy::getWorkplane(void) const {
return Part::shape2pyshape(getAreaPtr()->getPlane());
}
void AreaPy::setWorkplane(Py::Object obj) {
PyObject* p = obj.ptr();
if (!PyObject_TypeCheck(p, &(Part::TopoShapePy::Type))) {
std::string error = std::string("type must be 'TopoShape', not ");
error += p->ob_type->tp_name;
throw Py::TypeError(error);
}
getAreaPtr()->setPlane(GET_TOPOSHAPE(p));
}
// custom attributes get/set
PyObject *AreaPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int AreaPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#include <Mod/Part/App/OCCError.h>
#include <Mod/Part/App/TopoShapePy.h>
#include <Base/VectorPy.h>
#include "Area.h"
// inclusion of the generated files (generated out of AreaPy.xml)
#include "AreaPy.h"
#include "AreaPy.cpp"
static PyObject * areaAbort(PyObject *, PyObject *args, PyObject *kwd) {
static char *kwlist[] = {"aborting", NULL};
PyObject *pObj = Py_True;
if (!PyArg_ParseTupleAndKeywords(args,kwd,"|O",kwlist,&pObj))
return 0;
Area::abort(PyObject_IsTrue(pObj));
Py_INCREF(Py_None);
return Py_None;
}
static PyObject * areaSetParams(PyObject *, PyObject *args, PyObject *kwd) {
static char *kwlist[] = {PARAM_FIELD_STRINGS(NAME,AREA_PARAMS_STATIC_CONF),NULL};
if(args && PySequence_Size(args)>0)
PyErr_SetString(PyExc_ValueError,"Non-keyword argument is not supported");
//Declare variables defined in the NAME field of the CONF parameter list
PARAM_PY_DECLARE(PARAM_FNAME,AREA_PARAMS_STATIC_CONF);
AreaStaticParams params = Area::getDefaultParams();
#define AREA_SET(_param) \
PARAM_FNAME(_param) = \
PARAM_TYPED(PARAM_PY_CAST_,_param)(params.PARAM_FNAME(_param));
//populate the CONF variables with params
PARAM_FOREACH(AREA_SET,AREA_PARAMS_STATIC_CONF)
//Parse arguments to overwrite CONF variables
if (!PyArg_ParseTupleAndKeywords(args, kwd,
"|" PARAM_PY_KWDS(AREA_PARAMS_STATIC_CONF), kwlist,
PARAM_REF(PARAM_FNAME,AREA_PARAMS_STATIC_CONF)))
return 0;
#define AREA_GET(_param) \
params.PARAM_FNAME(_param) = \
PARAM_TYPED(PARAM_CAST_PY_,_param)(PARAM_FNAME(_param));
//populate 'params' with the CONF variables
PARAM_FOREACH(AREA_GET,AREA_PARAMS_STATIC_CONF)
Area::setDefaultParams(params);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* areaGetParams(PyObject *, PyObject *args) {
if (!PyArg_ParseTuple(args, ""))
return 0;
const AreaStaticParams &params = Area::getDefaultParams();
PyObject *dict = PyDict_New();
#define AREA_SRC(_param) params.PARAM_FNAME(_param)
PARAM_PY_DICT_SET_VALUE(dict,NAME,AREA_SRC,AREA_PARAMS_STATIC_CONF)
return dict;
}
static PyObject * areaGetParamsDesc(PyObject *, PyObject *args, PyObject *kwd) {
PyObject *pcObj = Py_False;
static char *kwlist[] = {"as_string", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwd, "|O",kwlist,&pcObj))
return 0;
#if PY_MAJOR_VERSION < 3
if(PyObject_IsTrue(pcObj))
return PyString_FromString(PARAM_PY_DOC(NAME,AREA_PARAMS_STATIC_CONF));
#else
if(PyObject_IsTrue(pcObj))
return PyUnicode_FromString(PARAM_PY_DOC(NAME,AREA_PARAMS_STATIC_CONF));
#endif
PyObject *dict = PyDict_New();
PARAM_PY_DICT_SET_DOC(dict,NAME,AREA_PARAMS_STATIC_CONF)
return dict;
}
static const PyMethodDef areaOverrides[] = {
{
"setParams",NULL,0,
"setParam(key=value...): Set algorithm parameters. You can call getParamsDesc() to \n"
"get a list of supported parameters and their descriptions.\n"
PARAM_PY_DOC(NAME,AREA_PARAMS_CONF)
},
{
"add",NULL,0,
"add((shape...)," PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_OPCODE) "):\n"
"Add TopoShape(s) with given operation code\n"
PARAM_PY_DOC(ARG,AREA_PARAMS_OPCODE)
"\nThe first shape's wires will be unioned together regardless of the op code given\n"
"(except for 'Compound'). Subsequent shape's wire will be combined using the op code.\n"
"All shape wires shall be coplanar, and are used to determine a working plane for face\n"
"making and offsetting. You can call setPlane() to supply a reference shape to determine\n"
"the workplane in case the added shapes are all colinear lines.\n",
},
{
"makeOffset",NULL,0,
"makeOffset(index=-1, " PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_OFFSET) "):\n"
"Make an 2D offset of the shape.\n"
"\n* index (-1): the index of the section. -1 means all sections. No effect on planar shape.\n"
PARAM_PY_DOC(ARG,AREA_PARAMS_OFFSET),
},
{
"makePocket",NULL,0,
"makePocket(index=-1, " PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_POCKET) "):\n"
"Generate pocket toolpath of the shape.\n"
"\n* index (-1): the index of the section. -1 means all sections. No effect on planar shape.\n"
PARAM_PY_DOC(ARG,AREA_PARAMS_POCKET),
},
{
"makeSections",NULL,0,
"makeSections(" PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_SECTION_EXTRA) ", heights=[], plane=None):\n"
"Make a list of area holding the sectioned children shapes on given heights\n"
PARAM_PY_DOC(ARG,AREA_PARAMS_SECTION_EXTRA)
"\n* heights ([]): a list of section heights, the meaning of the value is determined by 'mode'.\n"
"If not specified, the current SectionCount, and SectionOffset of this Area is used.\n"
"\n* plane (None): optional shape to specify a section plane. If not give, the current workplane\n"
"of this Area is used if section mode is 'Workplane'.",
},
{
"setDefaultParams",reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(areaSetParams)), METH_VARARGS|METH_KEYWORDS|METH_STATIC,
"setDefaultParams(key=value...):\n"
"Static method to set the default parameters of all following Path.Area, plus the following\n"
"additional parameters.\n"
},
{
"getDefaultParams",(PyCFunction)areaGetParams, METH_VARARGS|METH_STATIC,
"getDefaultParams(): Static method to return the current default parameters."
},
{
"abort",reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(areaAbort)), METH_VARARGS|METH_KEYWORDS|METH_STATIC,
"abort(aborting=True): Static method to abort any ongoing operation\n"
"\nTo ensure no stray abortion is left in the previous operation, it is advised to manually clear\n"
"the aborting flag by calling abort(False) before starting a new operation.",
},
{
"getParamsDesc",reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(areaGetParamsDesc)), METH_VARARGS|METH_KEYWORDS|METH_STATIC,
"getParamsDesc(as_string=False): Returns a list of supported parameters and their descriptions.\n"
"\n* as_string: if False, then return a dictionary of documents of all supported parameters."
},
};
struct AreaPyModifier {
AreaPyModifier() {
for(auto &method : Path::AreaPy::Methods) {
if(!method.ml_name) continue;
for(auto &entry : areaOverrides) {
if(std::strcmp(method.ml_name,entry.ml_name)==0) {
if(entry.ml_doc)
method.ml_doc = entry.ml_doc;
if(entry.ml_meth)
method.ml_meth = entry.ml_meth;
if(entry.ml_flags)
method.ml_flags = entry.ml_flags;
break;
}
}
}
}
};
static AreaPyModifier mod;
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string AreaPy::representation(void) const
{
std::stringstream str;
str << "<Area object at " << getAreaPtr() << ">";
return str.str();
}
PyObject *AreaPy::PyMake(struct _typeobject *, PyObject *args, PyObject *kwd) // Python wrapper
{
AreaPy* ret = new AreaPy(new Area);
if(!ret->setParams(args,kwd)) {
Py_DecRef(ret);
return 0;
}
return ret;
}
// constructor method
int AreaPy::PyInit(PyObject* , PyObject* )
{
return 0;
}
PyObject* AreaPy::setPlane(PyObject *args) {
PyObject *pcObj;
if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &pcObj))
return 0;
#define GET_TOPOSHAPE(_p) static_cast<Part::TopoShapePy*>(_p)->getTopoShapePtr()->getShape()
getAreaPtr()->setPlane(GET_TOPOSHAPE(pcObj));
Py_INCREF(this);
return this;
}
PyObject* AreaPy::getShape(PyObject *args, PyObject *keywds)
{
PyObject *pcObj = Py_False;
short index=-1;
static char *kwlist[] = {"index","rebuild", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds,"|hO",kwlist,&index,&pcObj))
return 0;
PY_TRY {
if(PyObject_IsTrue(pcObj))
getAreaPtr()->clean();
return Py::new_reference_to(Part::shape2pyshape(getAreaPtr()->getShape(index)));
} PY_CATCH_OCC
}
PyObject* AreaPy::add(PyObject *args, PyObject *keywds)
{
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_OPCODE)
PyObject *pcObj;
//Strangely, PyArg_ParseTupleAndKeywords requires all arguments to be keyword based,
//even non-optional ones? That doesn't make sense in python. Seems only in python 3
//they added '$' to address that issue.
static char *kwlist[] = {"shape",PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_OPCODE), NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"O|" PARAM_PY_KWDS(AREA_PARAMS_OPCODE),
kwlist,&pcObj,PARAM_REF(PARAM_FARG,AREA_PARAMS_OPCODE)))
return 0;
PY_TRY {
if (PyObject_TypeCheck(pcObj, &(Part::TopoShapePy::Type))) {
getAreaPtr()->add(GET_TOPOSHAPE(pcObj),op);
Py_INCREF(this);
return this;
} else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) ||
PyObject_TypeCheck(pcObj, &(PyTuple_Type))) {
Py::Sequence shapeSeq(pcObj);
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) {
PyObject* item = (*it).ptr();
if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) {
PyErr_SetString(PyExc_TypeError, "non-shape object in sequence");
return 0;
}
}
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it){
PyObject* item = (*it).ptr();
getAreaPtr()->add(GET_TOPOSHAPE(item),
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_OPCODE));
}
Py_INCREF(this);
return this;
}
} PY_CATCH_OCC
PyErr_SetString(PyExc_TypeError, "shape must be 'TopoShape' or list of 'TopoShape'");
return 0;
}
PyObject* AreaPy::makeOffset(PyObject *args, PyObject *keywds)
{
//Generate a keyword string defined in the ARG field of OFFSET parameter list
static char *kwlist[] = {"index",PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_OFFSET), NULL};
short index = -1;
//Declare variables defined in the ARG field of the OFFSET parameter list with
//initialization to defaults
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_OFFSET)
//Parse arguments to overwrite the defaults
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|h" PARAM_PY_KWDS(AREA_PARAMS_OFFSET), kwlist,
&index,PARAM_REF(PARAM_FARG,AREA_PARAMS_OFFSET)))
return 0;
PY_TRY {
//Expand the variable as function call arguments
TopoDS_Shape resultShape = getAreaPtr()->makeOffset(index,
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_OFFSET));
return Py::new_reference_to(Part::shape2pyshape(resultShape));
} PY_CATCH_OCC
}
PyObject* AreaPy::makePocket(PyObject *args, PyObject *keywds)
{
static char *kwlist[] = {"index",PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_POCKET), NULL};
short index = -1;
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_POCKET)
//Override pocket mode default
mode = Area::PocketModeZigZagOffset;
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|h" PARAM_PY_KWDS(AREA_PARAMS_POCKET), kwlist,
&index,PARAM_REF(PARAM_FARG,AREA_PARAMS_POCKET)))
return 0;
PY_TRY {
TopoDS_Shape resultShape = getAreaPtr()->makePocket(index,
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_POCKET));
return Py::new_reference_to(Part::shape2pyshape(resultShape));
} PY_CATCH_OCC
}
PyObject* AreaPy::makeSections(PyObject *args, PyObject *keywds)
{
static char *kwlist[] = {PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_SECTION_EXTRA),
"heights", "plane", NULL};
PyObject *heights = NULL;
PyObject *plane = NULL;
PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_SECTION_EXTRA)
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|" PARAM_PY_KWDS(AREA_PARAMS_SECTION_EXTRA) "OO!", kwlist,
PARAM_REF(PARAM_FARG,AREA_PARAMS_SECTION_EXTRA),
&heights, &(Part::TopoShapePy::Type), &plane))
return 0;
PY_TRY {
std::vector<double> h;
if(heights) {
if (PyObject_TypeCheck(heights, &(PyFloat_Type)))
h.push_back(PyFloat_AsDouble(heights));
else if (PyObject_TypeCheck(heights, &(PyList_Type)) ||
PyObject_TypeCheck(heights, &(PyTuple_Type))) {
Py::Sequence shapeSeq(heights);
h.reserve(shapeSeq.size());
for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) {
PyObject* item = (*it).ptr();
if(!PyObject_TypeCheck(item, &(PyFloat_Type))) {
PyErr_SetString(PyExc_TypeError, "heights must only contain float type");
return 0;
}
h.push_back(PyFloat_AsDouble(item));
}
}else{
PyErr_SetString(PyExc_TypeError, "heights must be of type float or list/tuple of float");
return 0;
}
}
std::vector<std::shared_ptr<Area> > sections = getAreaPtr()->makeSections(
PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_SECTION_EXTRA),
h,plane?GET_TOPOSHAPE(plane):TopoDS_Shape());
Py::List ret;
for(auto &area : sections)
ret.append(Py::asObject(new AreaPy(new Area(*area,true))));
return Py::new_reference_to(ret);
} PY_CATCH_OCC
}
PyObject* AreaPy::setDefaultParams(PyObject *, PyObject *)
{
return 0;
}
PyObject* AreaPy::setParams(PyObject *args, PyObject *keywds)
{
static char *kwlist[] = {PARAM_FIELD_STRINGS(NAME,AREA_PARAMS_CONF),NULL};
//Declare variables defined in the NAME field of the CONF parameter list
PARAM_PY_DECLARE(PARAM_FNAME,AREA_PARAMS_CONF);
AreaParams params = getAreaPtr()->getParams();
//populate the CONF variables with params
PARAM_FOREACH(AREA_SET,AREA_PARAMS_CONF)
//Parse arguments to overwrite CONF variables
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|" PARAM_PY_KWDS(AREA_PARAMS_CONF), kwlist,
PARAM_REF(PARAM_FNAME,AREA_PARAMS_CONF)))
return 0;
PY_TRY {
//populate 'params' with the CONF variables
PARAM_FOREACH(AREA_GET,AREA_PARAMS_CONF)
getAreaPtr()->setParams(params);
Py_INCREF(this);
return this;
} PY_CATCH_OCC
}
PyObject* AreaPy::getParams(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
const AreaParams &params =getAreaPtr()->getParams();
PyObject *dict = PyDict_New();
PARAM_PY_DICT_SET_VALUE(dict,NAME,AREA_SRC,AREA_PARAMS_CONF)
return dict;
}
PyObject* AreaPy::getDefaultParams(PyObject *)
{
return 0;
}
PyObject* AreaPy::abort(PyObject *, PyObject *) {
return 0;
}
PyObject* AreaPy::getParamsDesc(PyObject *, PyObject *)
{
return 0;
}
Py::List AreaPy::getSections(void) const {
Py::List ret;
Area *area = getAreaPtr();
for(size_t i=0,count=area->getSectionCount(); i<count;++i)
ret.append(Part::shape2pyshape(getAreaPtr()->getShape(i)));
return ret;
}
Py::List AreaPy::getShapes(void) const {
Py::List ret;
Area *area = getAreaPtr();
const std::list<Area::Shape> &shapes = area->getChildren();
for(auto &s : shapes)
ret.append(Py::TupleN(Part::shape2pyshape(s.shape),Py::Int(s.op)));
return ret;
}
Py::Object AreaPy::getWorkplane(void) const {
return Part::shape2pyshape(getAreaPtr()->getPlane());
}
void AreaPy::setWorkplane(Py::Object obj) {
PyObject* p = obj.ptr();
if (!PyObject_TypeCheck(p, &(Part::TopoShapePy::Type))) {
std::string error = std::string("type must be 'TopoShape', not ");
error += p->ob_type->tp_name;
throw Py::TypeError(error);
}
getAreaPtr()->setPlane(GET_TOPOSHAPE(p));
}
// custom attributes get/set
PyObject *AreaPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int AreaPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}

View File

@@ -1,323 +1,323 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cinttypes>
# include <iomanip>
# include <boost/algorithm/string.hpp>
# include <boost/lexical_cast.hpp>
#endif
#include <Base/Vector3D.h>
#include <Base/Rotation.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include "Command.h"
using namespace Base;
using namespace Path;
TYPESYSTEM_SOURCE(Path::Command , Base::Persistence)
// Constructors & destructors
Command::Command(const char* name,
const std::map<std::string, double>& parameters)
:Name(name),Parameters(parameters)
{
}
Command::Command()
{
}
Command::~Command()
{
}
// New methods
Placement Command::getPlacement (const Base::Vector3d pos) const
{
static const std::string x = "X";
static const std::string y = "Y";
static const std::string z = "Z";
static const std::string a = "A";
static const std::string b = "B";
static const std::string c = "C";
Vector3d vec(getParam(x, pos.x),getParam(y, pos.y),getParam(z, pos.z));
Rotation rot;
rot.setYawPitchRoll(getParam(a),getParam(b),getParam(c));
Placement plac(vec,rot);
return plac;
}
Vector3d Command::getCenter (void) const
{
static const std::string i = "I";
static const std::string j = "J";
static const std::string k = "K";
Vector3d vec(getParam(i),getParam(j),getParam(k));
return vec;
}
double Command::getValue(const std::string& attr) const
{
std::string a(attr);
boost::to_upper(a);
return getParam(a);
}
bool Command::has(const std::string& attr) const
{
std::string a(attr);
boost::to_upper(a);
return Parameters.count(a) > 0;
}
std::string Command::toGCode (int precision, bool padzero) const
{
std::stringstream str;
str.fill('0');
str << Name;
if(precision<0)
precision = 0;
double scale = std::pow(10.0,precision+1);
std::int64_t iscale = static_cast<std::int64_t>(scale)/10;
for(std::map<std::string,double>::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) {
if(i->first == "N") continue;
str << " " << i->first;
std::int64_t v = static_cast<std::int64_t>(i->second*scale);
if(v<0) {
v = -v;
str << '-'; //shall we allow -0 ?
}
v+=5;
v /= 10;
str << (v/iscale);
if(!precision) continue;
int width = precision;
std::int64_t digits = v%iscale;
if(!padzero) {
if(!digits) continue;
while(digits%10 == 0) {
digits/=10;
--width;
}
}
str << '.' << std::setw(width) << std::right << digits;
}
return str.str();
}
void Command::setFromGCode (const std::string& str)
{
Parameters.clear();
std::string mode = "none";
std::string key;
std::string value;
for (unsigned int i=0; i < str.size(); i++) {
if ( (isdigit(str[i])) || (str[i] == '-') || (str[i] == '.') ) {
value += str[i];
} else if (isalpha(str[i])) {
if (mode == "command") {
if (!key.empty() && !value.empty()) {
std::string cmd = key + value;
boost::to_upper(cmd);
Name = cmd;
key = "";
value = "";
mode = "argument";
} else {
throw Base::BadFormatError("Badly formatted GCode command");
}
mode = "argument";
} else if (mode == "none") {
mode = "command";
} else if (mode == "argument") {
if (!key.empty() && !value.empty()) {
double val = std::atof(value.c_str());
boost::to_upper(key);
Parameters[key] = val;
key = "";
value = "";
} else {
throw Base::BadFormatError("Badly formatted GCode argument");
}
} else if (mode == "comment") {
value += str[i];
}
key = str[i];
} else if (str[i] == '(') {
mode = "comment";
} else if (str[i] == ')') {
key = "(";
value += ")";
} else {
// add non-ascii characters only if this is a comment
if (mode == "comment") {
value += str[i];
}
}
}
if (!key.empty() && !value.empty()) {
if ( (mode == "command") || (mode == "comment") ) {
std::string cmd = key + value;
if (mode == "command")
boost::to_upper(cmd);
Name = cmd;
} else {
double val = std::atof(value.c_str());
boost::to_upper(key);
Parameters[key] = val;
}
} else {
throw Base::BadFormatError("Badly formatted GCode argument");
}
}
void Command::setFromPlacement (const Base::Placement &plac)
{
Name = "G1";
Parameters.clear();
static const std::string x = "X";
static const std::string y = "Y";
static const std::string z = "Z";
static const std::string a = "A";
static const std::string b = "B";
static const std::string c = "C";
double xval, yval, zval, aval, bval, cval;
xval = plac.getPosition().x;
yval = plac.getPosition().y;
zval = plac.getPosition().z;
plac.getRotation().getYawPitchRoll(aval,bval,cval);
if (xval != 0.0)
Parameters[x] = xval;
if (yval != 0.0)
Parameters[y] = yval;
if (zval != 0.0)
Parameters[z] = zval;
if (aval != 0.0)
Parameters[a] = aval;
if (bval != 0.0)
Parameters[b] = bval;
if (cval != 0.0)
Parameters[c] = cval;
}
void Command::setCenter(const Base::Vector3d &pos, bool clockwise)
{
if (clockwise) {
Name = "G2";
} else {
Name = "G3";
}
static const std::string i = "I";
static const std::string j = "J";
static const std::string k = "K";
double ival, jval, kval;
ival = pos.x;
jval = pos.y;
kval = pos.z;
Parameters[i] = ival;
Parameters[j] = jval;
Parameters[k] = kval;
}
Command Command::transform(const Base::Placement other)
{
Base::Placement plac = getPlacement();
plac *= other;
double xval, yval, zval, aval, bval, cval;
xval = plac.getPosition().x;
yval = plac.getPosition().y;
zval = plac.getPosition().z;
plac.getRotation().getYawPitchRoll(aval,bval,cval);
Command c = Command();
c.Name = Name;
for(std::map<std::string,double>::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) {
std::string k = i->first;
double v = i->second;
if (k == "X")
v = xval;
if (k == "Y")
v = yval;
if (k == "Z")
v = zval;
if (k == "A")
v = aval;
if (k == "B")
v = bval;
if (k == "C")
v = cval;
c.Parameters[k] = v;
}
return c;
}
void Command::scaleBy(double factor)
{
for(std::map<std::string, double>::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) {
switch (i->first[0]) {
case 'X':
case 'Y':
case 'Z':
case 'I':
case 'J':
case 'R':
case 'Q':
case 'F':
Parameters[i->first] = i->second * factor;
break;
}
}
}
// Reimplemented from base class
unsigned int Command::getMemSize (void) const
{
return toGCode().size();
}
void Command::Save (Writer &writer) const
{
// this will only get used if saved as XML (probably never)
writer.Stream() << writer.ind() << "<Command "
<< "gcode=\"" << toGCode() << "\" />";
writer.Stream()<< std::endl;
}
void Command::Restore(XMLReader &reader)
{
reader.readElement("Command");
std::string gcode = reader.getAttribute("gcode");
setFromGCode(gcode);
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cinttypes>
# include <iomanip>
# include <boost/algorithm/string.hpp>
# include <boost/lexical_cast.hpp>
#endif
#include <Base/Vector3D.h>
#include <Base/Rotation.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include "Command.h"
using namespace Base;
using namespace Path;
TYPESYSTEM_SOURCE(Path::Command , Base::Persistence)
// Constructors & destructors
Command::Command(const char* name,
const std::map<std::string, double>& parameters)
:Name(name),Parameters(parameters)
{
}
Command::Command()
{
}
Command::~Command()
{
}
// New methods
Placement Command::getPlacement (const Base::Vector3d pos) const
{
static const std::string x = "X";
static const std::string y = "Y";
static const std::string z = "Z";
static const std::string a = "A";
static const std::string b = "B";
static const std::string c = "C";
Vector3d vec(getParam(x, pos.x),getParam(y, pos.y),getParam(z, pos.z));
Rotation rot;
rot.setYawPitchRoll(getParam(a),getParam(b),getParam(c));
Placement plac(vec,rot);
return plac;
}
Vector3d Command::getCenter (void) const
{
static const std::string i = "I";
static const std::string j = "J";
static const std::string k = "K";
Vector3d vec(getParam(i),getParam(j),getParam(k));
return vec;
}
double Command::getValue(const std::string& attr) const
{
std::string a(attr);
boost::to_upper(a);
return getParam(a);
}
bool Command::has(const std::string& attr) const
{
std::string a(attr);
boost::to_upper(a);
return Parameters.count(a) > 0;
}
std::string Command::toGCode (int precision, bool padzero) const
{
std::stringstream str;
str.fill('0');
str << Name;
if(precision<0)
precision = 0;
double scale = std::pow(10.0,precision+1);
std::int64_t iscale = static_cast<std::int64_t>(scale)/10;
for(std::map<std::string,double>::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) {
if(i->first == "N") continue;
str << " " << i->first;
std::int64_t v = static_cast<std::int64_t>(i->second*scale);
if(v<0) {
v = -v;
str << '-'; //shall we allow -0 ?
}
v+=5;
v /= 10;
str << (v/iscale);
if(!precision) continue;
int width = precision;
std::int64_t digits = v%iscale;
if(!padzero) {
if(!digits) continue;
while(digits%10 == 0) {
digits/=10;
--width;
}
}
str << '.' << std::setw(width) << std::right << digits;
}
return str.str();
}
void Command::setFromGCode (const std::string& str)
{
Parameters.clear();
std::string mode = "none";
std::string key;
std::string value;
for (unsigned int i=0; i < str.size(); i++) {
if ( (isdigit(str[i])) || (str[i] == '-') || (str[i] == '.') ) {
value += str[i];
} else if (isalpha(str[i])) {
if (mode == "command") {
if (!key.empty() && !value.empty()) {
std::string cmd = key + value;
boost::to_upper(cmd);
Name = cmd;
key = "";
value = "";
mode = "argument";
} else {
throw Base::BadFormatError("Badly formatted GCode command");
}
mode = "argument";
} else if (mode == "none") {
mode = "command";
} else if (mode == "argument") {
if (!key.empty() && !value.empty()) {
double val = std::atof(value.c_str());
boost::to_upper(key);
Parameters[key] = val;
key = "";
value = "";
} else {
throw Base::BadFormatError("Badly formatted GCode argument");
}
} else if (mode == "comment") {
value += str[i];
}
key = str[i];
} else if (str[i] == '(') {
mode = "comment";
} else if (str[i] == ')') {
key = "(";
value += ")";
} else {
// add non-ascii characters only if this is a comment
if (mode == "comment") {
value += str[i];
}
}
}
if (!key.empty() && !value.empty()) {
if ( (mode == "command") || (mode == "comment") ) {
std::string cmd = key + value;
if (mode == "command")
boost::to_upper(cmd);
Name = cmd;
} else {
double val = std::atof(value.c_str());
boost::to_upper(key);
Parameters[key] = val;
}
} else {
throw Base::BadFormatError("Badly formatted GCode argument");
}
}
void Command::setFromPlacement (const Base::Placement &plac)
{
Name = "G1";
Parameters.clear();
static const std::string x = "X";
static const std::string y = "Y";
static const std::string z = "Z";
static const std::string a = "A";
static const std::string b = "B";
static const std::string c = "C";
double xval, yval, zval, aval, bval, cval;
xval = plac.getPosition().x;
yval = plac.getPosition().y;
zval = plac.getPosition().z;
plac.getRotation().getYawPitchRoll(aval,bval,cval);
if (xval != 0.0)
Parameters[x] = xval;
if (yval != 0.0)
Parameters[y] = yval;
if (zval != 0.0)
Parameters[z] = zval;
if (aval != 0.0)
Parameters[a] = aval;
if (bval != 0.0)
Parameters[b] = bval;
if (cval != 0.0)
Parameters[c] = cval;
}
void Command::setCenter(const Base::Vector3d &pos, bool clockwise)
{
if (clockwise) {
Name = "G2";
} else {
Name = "G3";
}
static const std::string i = "I";
static const std::string j = "J";
static const std::string k = "K";
double ival, jval, kval;
ival = pos.x;
jval = pos.y;
kval = pos.z;
Parameters[i] = ival;
Parameters[j] = jval;
Parameters[k] = kval;
}
Command Command::transform(const Base::Placement other)
{
Base::Placement plac = getPlacement();
plac *= other;
double xval, yval, zval, aval, bval, cval;
xval = plac.getPosition().x;
yval = plac.getPosition().y;
zval = plac.getPosition().z;
plac.getRotation().getYawPitchRoll(aval,bval,cval);
Command c = Command();
c.Name = Name;
for(std::map<std::string,double>::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) {
std::string k = i->first;
double v = i->second;
if (k == "X")
v = xval;
if (k == "Y")
v = yval;
if (k == "Z")
v = zval;
if (k == "A")
v = aval;
if (k == "B")
v = bval;
if (k == "C")
v = cval;
c.Parameters[k] = v;
}
return c;
}
void Command::scaleBy(double factor)
{
for(std::map<std::string, double>::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) {
switch (i->first[0]) {
case 'X':
case 'Y':
case 'Z':
case 'I':
case 'J':
case 'R':
case 'Q':
case 'F':
Parameters[i->first] = i->second * factor;
break;
}
}
}
// Reimplemented from base class
unsigned int Command::getMemSize (void) const
{
return toGCode().size();
}
void Command::Save (Writer &writer) const
{
// this will only get used if saved as XML (probably never)
writer.Stream() << writer.ind() << "<Command "
<< "gcode=\"" << toGCode() << "\" />";
writer.Stream()<< std::endl;
}
void Command::Restore(XMLReader &reader)
{
reader.readElement("Command");
std::string gcode = reader.getAttribute("gcode");
setFromGCode(gcode);
}

View File

@@ -1,76 +1,76 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_COMMAND_H
#define PATH_COMMAND_H
#include <map>
#include <string>
#include <Base/Persistence.h>
#include <Base/Placement.h>
#include <Base/Vector3D.h>
namespace Path
{
/** The representation of a cnc command in a path */
class PathExport Command : public Base::Persistence
{
TYPESYSTEM_HEADER();
public:
//constructors
Command();
Command(const char* name,
const std::map<std::string,double>& parameters);
~Command();
// from base class
virtual unsigned int getMemSize (void) const;
virtual void Save (Base::Writer &/*writer*/) const;
virtual void Restore(Base::XMLReader &/*reader*/);
// specific methods
Base::Placement getPlacement (const Base::Vector3d pos = Base::Vector3d()) const; // returns a placement from the x,y,z,a,b,c parameters
Base::Vector3d getCenter (void) const; // returns a 3d vector from the i,j,k parameters
void setCenter(const Base::Vector3d&, bool clockwise=true); // sets the center coordinates and the command name
std::string toGCode (int precision=6, bool padzero=true) const; // returns a GCode string representation of the command
void setFromGCode (const std::string&); // sets the parameters from the contents of the given GCode string
void setFromPlacement (const Base::Placement&); // sets the parameters from the contents of the given placement
bool has(const std::string&) const; // returns true if the given string exists in the parameters
Command transform(const Base::Placement); // returns a transformed copy of this command
double getValue(const std::string &name) const; // returns the value of a given parameter
void scaleBy(double factor); // scales the receiver - use for imperial/metric conversions
// this assumes the name is upper case
inline double getParam(const std::string &name, double fallback = 0.0) const {
auto it = Parameters.find(name);
return it==Parameters.end() ? fallback : it->second;
}
// attributes
std::string Name;
std::map<std::string,double> Parameters;
};
} //namespace Path
#endif // PATH_COMMAND_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_COMMAND_H
#define PATH_COMMAND_H
#include <map>
#include <string>
#include <Base/Persistence.h>
#include <Base/Placement.h>
#include <Base/Vector3D.h>
namespace Path
{
/** The representation of a cnc command in a path */
class PathExport Command : public Base::Persistence
{
TYPESYSTEM_HEADER();
public:
//constructors
Command();
Command(const char* name,
const std::map<std::string,double>& parameters);
~Command();
// from base class
virtual unsigned int getMemSize (void) const;
virtual void Save (Base::Writer &/*writer*/) const;
virtual void Restore(Base::XMLReader &/*reader*/);
// specific methods
Base::Placement getPlacement (const Base::Vector3d pos = Base::Vector3d()) const; // returns a placement from the x,y,z,a,b,c parameters
Base::Vector3d getCenter (void) const; // returns a 3d vector from the i,j,k parameters
void setCenter(const Base::Vector3d&, bool clockwise=true); // sets the center coordinates and the command name
std::string toGCode (int precision=6, bool padzero=true) const; // returns a GCode string representation of the command
void setFromGCode (const std::string&); // sets the parameters from the contents of the given GCode string
void setFromPlacement (const Base::Placement&); // sets the parameters from the contents of the given placement
bool has(const std::string&) const; // returns true if the given string exists in the parameters
Command transform(const Base::Placement); // returns a transformed copy of this command
double getValue(const std::string &name) const; // returns the value of a given parameter
void scaleBy(double factor); // scales the receiver - use for imperial/metric conversions
// this assumes the name is upper case
inline double getParam(const std::string &name, double fallback = 0.0) const {
auto it = Parameters.find(name);
return it==Parameters.end() ? fallback : it->second;
}
// attributes
std::string Name;
std::map<std::string,double> Parameters;
};
} //namespace Path
#endif // PATH_COMMAND_H

View File

@@ -1,55 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="PersistencePy"
Name="CommandPy"
Twin="Command"
TwinPointer="Command"
Include="Mod/Path/App/Command.h"
Namespace="Path"
FatherInclude="Base/PersistencePy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>Command([name],[parameters]): Represents a basic Gcode command
name (optional) is the name of the command, ex. G1
parameters (optional) is a dictionary containing string:number
pairs, or a placement, or a vector</UserDocu>
</Documentation>
<Attribute Name="Name" ReadOnly="false">
<Documentation>
<UserDocu>The name of the command</UserDocu>
</Documentation>
<Parameter Name="Name" Type="String"/>
</Attribute>
<Attribute Name="Parameters" ReadOnly="false">
<Documentation>
<UserDocu>The parameters of the command</UserDocu>
</Documentation>
<Parameter Name="Parameters" Type="Dict"/>
</Attribute>
<Attribute Name="Placement" ReadOnly="false">
<Documentation>
<UserDocu>The coordinates of the endpoint of the command</UserDocu>
</Documentation>
<Parameter Name="Placement" Type="Object"/>
</Attribute>
<Methode Name="toGCode" Const="true">
<Documentation>
<UserDocu>toGCode(): returns a GCode representation of the command</UserDocu>
</Documentation>
</Methode>
<Methode Name="setFromGCode">
<Documentation>
<UserDocu>toGCode(): returns a GCode representation of the command</UserDocu>
</Documentation>
</Methode>
<Methode Name="transform">
<Documentation>
<UserDocu>transform(Placement): returns a copy of this command transformed by the given placement</UserDocu>
</Documentation>
</Methode>
</PythonExport>
</GenerateModel>
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="PersistencePy"
Name="CommandPy"
Twin="Command"
TwinPointer="Command"
Include="Mod/Path/App/Command.h"
Namespace="Path"
FatherInclude="Base/PersistencePy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>Command([name],[parameters]): Represents a basic Gcode command
name (optional) is the name of the command, ex. G1
parameters (optional) is a dictionary containing string:number
pairs, or a placement, or a vector</UserDocu>
</Documentation>
<Attribute Name="Name" ReadOnly="false">
<Documentation>
<UserDocu>The name of the command</UserDocu>
</Documentation>
<Parameter Name="Name" Type="String"/>
</Attribute>
<Attribute Name="Parameters" ReadOnly="false">
<Documentation>
<UserDocu>The parameters of the command</UserDocu>
</Documentation>
<Parameter Name="Parameters" Type="Dict"/>
</Attribute>
<Attribute Name="Placement" ReadOnly="false">
<Documentation>
<UserDocu>The coordinates of the endpoint of the command</UserDocu>
</Documentation>
<Parameter Name="Placement" Type="Object"/>
</Attribute>
<Methode Name="toGCode" Const="true">
<Documentation>
<UserDocu>toGCode(): returns a GCode representation of the command</UserDocu>
</Documentation>
</Methode>
<Methode Name="setFromGCode">
<Documentation>
<UserDocu>toGCode(): returns a GCode representation of the command</UserDocu>
</Documentation>
</Methode>
<Methode Name="transform">
<Documentation>
<UserDocu>transform(Placement): returns a copy of this command transformed by the given placement</UserDocu>
</Documentation>
</Methode>
</PythonExport>
</GenerateModel>

View File

@@ -1,317 +1,317 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/algorithm/string.hpp>
#endif
#include <Base/Exception.h>
#include <Base/Vector3D.h>
#include <Base/VectorPy.h>
#include <Base/PlacementPy.h>
#include "Mod/Path/App/Command.h"
// files generated out of CommandPy.xml
#include "CommandPy.h"
#include "CommandPy.cpp"
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string CommandPy::representation(void) const
{
std::stringstream str;
str.precision(5);
str << "Command ";
str << getCommandPtr()->Name;
str << " [";
for(std::map<std::string,double>::iterator i = getCommandPtr()->Parameters.begin(); i != getCommandPtr()->Parameters.end(); ++i) {
std::string k = i->first;
double v = i->second;
str << " " << k << ":" << v;
}
str << " ]";
return str.str();
}
PyObject *CommandPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
// create a new instance of CommandPy and the Twin object
return new CommandPy(new Command);
}
// constructor method
int CommandPy::PyInit(PyObject* args, PyObject* kwd)
{
PyObject *parameters = NULL;
char *name = "";
static char *kwlist[] = {"name", "parameters", NULL};
if ( PyArg_ParseTupleAndKeywords(args, kwd, "|sO!", kwlist, &name, &PyDict_Type, &parameters) ) {
std::string sname(name);
boost::to_upper(sname);
try {
if (!sname.empty())
getCommandPtr()->setFromGCode(name);
}
catch (const Base::Exception& e) {
PyErr_SetString(PyExc_ValueError, e.what());
return -1;
}
PyObject *key, *value;
Py_ssize_t pos = 0;
while (parameters && PyDict_Next(parameters, &pos, &key, &value)) {
std::string ckey;
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(key)) {
ckey = PyUnicode_AsUTF8(key);
#else
if (PyString_Check(key)) {
ckey = PyString_AsString(key);
#endif
}
else {
PyErr_SetString(PyExc_TypeError, "The dictionary can only contain string keys");
return -1;
}
boost::to_upper(ckey);
double cvalue;
#if PY_MAJOR_VERSION >= 3
if (PyObject_TypeCheck(value,&(PyLong_Type))) {
cvalue = (double)PyLong_AsLong(value);
#else
if (PyObject_TypeCheck(value,&(PyInt_Type))) {
cvalue = (double)PyInt_AsLong(value);
#endif
}
else if (PyObject_TypeCheck(value, &(PyFloat_Type))) {
cvalue = PyFloat_AsDouble(value);
}
else {
PyErr_SetString(PyExc_TypeError, "The dictionary can only contain number values");
return -1;
}
getCommandPtr()->Parameters[ckey]=cvalue;
}
return 0;
}
PyErr_Clear(); // set by PyArg_ParseTuple()
if ( PyArg_ParseTupleAndKeywords(args, kwd, "|sO!", kwlist, &name, &(Base::PlacementPy::Type), &parameters) ) {
std::string sname(name);
boost::to_upper(sname);
try {
if (!sname.empty())
getCommandPtr()->setFromGCode(name);
}
catch (const Base::Exception& e) {
PyErr_SetString(PyExc_ValueError, e.what());
return -1;
}
Base::PlacementPy *p = static_cast<Base::PlacementPy*>(parameters);
getCommandPtr()->setFromPlacement( *p->getPlacementPtr() );
return 0;
}
return -1;
}
// Name attribute
Py::String CommandPy::getName(void) const
{
return Py::String(getCommandPtr()->Name.c_str());
}
void CommandPy::setName(Py::String arg)
{
std::string cmd = arg.as_std_string();
boost::to_upper(cmd);
getCommandPtr()->Name = cmd;
}
// Parameters attribute get/set
Py::Dict CommandPy::getParameters(void) const
{
PyObject *dict = PyDict_New();
for(std::map<std::string,double>::iterator i = getCommandPtr()->Parameters.begin(); i != getCommandPtr()->Parameters.end(); ++i) {
#if PY_MAJOR_VERSION >= 3
PyDict_SetItem(dict,PyUnicode_FromString(i->first.c_str()),PyFloat_FromDouble(i->second));
#else
PyDict_SetItem(dict,PyString_FromString(i->first.c_str()),PyFloat_FromDouble(i->second));
#endif
}
return Py::Dict(dict);
}
void CommandPy::setParameters(Py::Dict arg)
{
PyObject* dict_copy = PyDict_Copy(arg.ptr());
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(dict_copy, &pos, &key, &value)) {
std::string ckey;
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(key)) {
ckey = PyUnicode_AsUTF8(key);
#else
if (PyString_Check(key)) {
ckey = PyString_AsString(key);
#endif
}
else {
throw Py::TypeError("The dictionary can only contain string keys");
}
boost::to_upper(ckey);
double cvalue;
#if PY_MAJOR_VERSION >= 3
if (PyObject_TypeCheck(value,&(PyLong_Type))) {
cvalue = (double)PyLong_AsLong(value);
#else
if (PyObject_TypeCheck(value,&(PyInt_Type))) {
cvalue = (double)PyInt_AsLong(value);
#endif
}
else if (PyObject_TypeCheck(value, &(PyFloat_Type))) {
cvalue = PyFloat_AsDouble(value);
}
else {
throw Py::TypeError("The dictionary can only contain number values");
}
getCommandPtr()->Parameters[ckey]=cvalue;
}
}
// GCode methods
PyObject* CommandPy::toGCode(PyObject *args)
{
if (PyArg_ParseTuple(args, "")) {
#if PY_MAJOR_VERSION >= 3
return PyUnicode_FromString(getCommandPtr()->toGCode().c_str());
#else
return PyString_FromString(getCommandPtr()->toGCode().c_str());
#endif
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* CommandPy::setFromGCode(PyObject *args)
{
char *pstr=0;
if (PyArg_ParseTuple(args, "s", &pstr)) {
std::string gcode(pstr);
try {
getCommandPtr()->setFromGCode(gcode);
}
catch (const Base::Exception& e) {
PyErr_SetString(PyExc_ValueError, e.what());
return nullptr;
}
Py_INCREF(Py_None);
return Py_None;
}
throw Py::TypeError("Argument must be a string");
}
// Placement attribute get/set
Py::Object CommandPy::getPlacement(void) const
{
return Py::asObject(new Base::PlacementPy(new Base::Placement(getCommandPtr()->getPlacement())));
}
void CommandPy::setPlacement(Py::Object arg)
{
union PyType_Object pyType = {&(Base::PlacementPy::Type)};
Py::Type PlacementType(pyType.o);
if(arg.isType(PlacementType)) {
getCommandPtr()->setFromPlacement( *static_cast<Base::PlacementPy*>((*arg))->getPlacementPtr() );
} else
throw Py::TypeError("Argument must be a placement");
}
PyObject* CommandPy::transform(PyObject *args)
{
PyObject *placement;
if ( PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &placement) ) {
Base::PlacementPy *p = static_cast<Base::PlacementPy*>(placement);
Path::Command trCmd = getCommandPtr()->transform( *p->getPlacementPtr() );
return new CommandPy(new Path::Command(trCmd));
} else
throw Py::TypeError("Argument must be a placement");
}
// custom attributes get/set
PyObject *CommandPy::getCustomAttributes(const char* attr) const
{
std::string satt(attr);
if (satt.length() == 1) {
if (isalpha(satt[0])) {
boost::to_upper(satt);
if (getCommandPtr()->Parameters.count(satt)) {
return PyFloat_FromDouble(getCommandPtr()->Parameters[satt]);
}
Py_INCREF(Py_None);
return Py_None;
}
}
return 0;
}
int CommandPy::setCustomAttributes(const char* attr, PyObject* obj)
{
std::string satt(attr);
if (satt.length() == 1) {
if (isalpha(satt[0])) {
boost::to_upper(satt);
double cvalue;
#if PY_MAJOR_VERSION >= 3
if (PyObject_TypeCheck(obj,&(PyLong_Type))) {
cvalue = (double)PyLong_AsLong(obj);
#else
if (PyObject_TypeCheck(obj,&(PyInt_Type))) {
cvalue = (double)PyInt_AsLong(obj);
#endif
} else if (PyObject_TypeCheck(obj,&(PyFloat_Type))) {
cvalue = PyFloat_AsDouble(obj);
} else {
return 0;
}
getCommandPtr()->Parameters[satt]=cvalue;
return 1;
}
}
return 0;
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/algorithm/string.hpp>
#endif
#include <Base/Exception.h>
#include <Base/Vector3D.h>
#include <Base/VectorPy.h>
#include <Base/PlacementPy.h>
#include "Mod/Path/App/Command.h"
// files generated out of CommandPy.xml
#include "CommandPy.h"
#include "CommandPy.cpp"
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string CommandPy::representation(void) const
{
std::stringstream str;
str.precision(5);
str << "Command ";
str << getCommandPtr()->Name;
str << " [";
for(std::map<std::string,double>::iterator i = getCommandPtr()->Parameters.begin(); i != getCommandPtr()->Parameters.end(); ++i) {
std::string k = i->first;
double v = i->second;
str << " " << k << ":" << v;
}
str << " ]";
return str.str();
}
PyObject *CommandPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
// create a new instance of CommandPy and the Twin object
return new CommandPy(new Command);
}
// constructor method
int CommandPy::PyInit(PyObject* args, PyObject* kwd)
{
PyObject *parameters = NULL;
char *name = "";
static char *kwlist[] = {"name", "parameters", NULL};
if ( PyArg_ParseTupleAndKeywords(args, kwd, "|sO!", kwlist, &name, &PyDict_Type, &parameters) ) {
std::string sname(name);
boost::to_upper(sname);
try {
if (!sname.empty())
getCommandPtr()->setFromGCode(name);
}
catch (const Base::Exception& e) {
PyErr_SetString(PyExc_ValueError, e.what());
return -1;
}
PyObject *key, *value;
Py_ssize_t pos = 0;
while (parameters && PyDict_Next(parameters, &pos, &key, &value)) {
std::string ckey;
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(key)) {
ckey = PyUnicode_AsUTF8(key);
#else
if (PyString_Check(key)) {
ckey = PyString_AsString(key);
#endif
}
else {
PyErr_SetString(PyExc_TypeError, "The dictionary can only contain string keys");
return -1;
}
boost::to_upper(ckey);
double cvalue;
#if PY_MAJOR_VERSION >= 3
if (PyObject_TypeCheck(value,&(PyLong_Type))) {
cvalue = (double)PyLong_AsLong(value);
#else
if (PyObject_TypeCheck(value,&(PyInt_Type))) {
cvalue = (double)PyInt_AsLong(value);
#endif
}
else if (PyObject_TypeCheck(value, &(PyFloat_Type))) {
cvalue = PyFloat_AsDouble(value);
}
else {
PyErr_SetString(PyExc_TypeError, "The dictionary can only contain number values");
return -1;
}
getCommandPtr()->Parameters[ckey]=cvalue;
}
return 0;
}
PyErr_Clear(); // set by PyArg_ParseTuple()
if ( PyArg_ParseTupleAndKeywords(args, kwd, "|sO!", kwlist, &name, &(Base::PlacementPy::Type), &parameters) ) {
std::string sname(name);
boost::to_upper(sname);
try {
if (!sname.empty())
getCommandPtr()->setFromGCode(name);
}
catch (const Base::Exception& e) {
PyErr_SetString(PyExc_ValueError, e.what());
return -1;
}
Base::PlacementPy *p = static_cast<Base::PlacementPy*>(parameters);
getCommandPtr()->setFromPlacement( *p->getPlacementPtr() );
return 0;
}
return -1;
}
// Name attribute
Py::String CommandPy::getName(void) const
{
return Py::String(getCommandPtr()->Name.c_str());
}
void CommandPy::setName(Py::String arg)
{
std::string cmd = arg.as_std_string();
boost::to_upper(cmd);
getCommandPtr()->Name = cmd;
}
// Parameters attribute get/set
Py::Dict CommandPy::getParameters(void) const
{
PyObject *dict = PyDict_New();
for(std::map<std::string,double>::iterator i = getCommandPtr()->Parameters.begin(); i != getCommandPtr()->Parameters.end(); ++i) {
#if PY_MAJOR_VERSION >= 3
PyDict_SetItem(dict,PyUnicode_FromString(i->first.c_str()),PyFloat_FromDouble(i->second));
#else
PyDict_SetItem(dict,PyString_FromString(i->first.c_str()),PyFloat_FromDouble(i->second));
#endif
}
return Py::Dict(dict);
}
void CommandPy::setParameters(Py::Dict arg)
{
PyObject* dict_copy = PyDict_Copy(arg.ptr());
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(dict_copy, &pos, &key, &value)) {
std::string ckey;
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(key)) {
ckey = PyUnicode_AsUTF8(key);
#else
if (PyString_Check(key)) {
ckey = PyString_AsString(key);
#endif
}
else {
throw Py::TypeError("The dictionary can only contain string keys");
}
boost::to_upper(ckey);
double cvalue;
#if PY_MAJOR_VERSION >= 3
if (PyObject_TypeCheck(value,&(PyLong_Type))) {
cvalue = (double)PyLong_AsLong(value);
#else
if (PyObject_TypeCheck(value,&(PyInt_Type))) {
cvalue = (double)PyInt_AsLong(value);
#endif
}
else if (PyObject_TypeCheck(value, &(PyFloat_Type))) {
cvalue = PyFloat_AsDouble(value);
}
else {
throw Py::TypeError("The dictionary can only contain number values");
}
getCommandPtr()->Parameters[ckey]=cvalue;
}
}
// GCode methods
PyObject* CommandPy::toGCode(PyObject *args)
{
if (PyArg_ParseTuple(args, "")) {
#if PY_MAJOR_VERSION >= 3
return PyUnicode_FromString(getCommandPtr()->toGCode().c_str());
#else
return PyString_FromString(getCommandPtr()->toGCode().c_str());
#endif
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* CommandPy::setFromGCode(PyObject *args)
{
char *pstr=0;
if (PyArg_ParseTuple(args, "s", &pstr)) {
std::string gcode(pstr);
try {
getCommandPtr()->setFromGCode(gcode);
}
catch (const Base::Exception& e) {
PyErr_SetString(PyExc_ValueError, e.what());
return nullptr;
}
Py_INCREF(Py_None);
return Py_None;
}
throw Py::TypeError("Argument must be a string");
}
// Placement attribute get/set
Py::Object CommandPy::getPlacement(void) const
{
return Py::asObject(new Base::PlacementPy(new Base::Placement(getCommandPtr()->getPlacement())));
}
void CommandPy::setPlacement(Py::Object arg)
{
union PyType_Object pyType = {&(Base::PlacementPy::Type)};
Py::Type PlacementType(pyType.o);
if(arg.isType(PlacementType)) {
getCommandPtr()->setFromPlacement( *static_cast<Base::PlacementPy*>((*arg))->getPlacementPtr() );
} else
throw Py::TypeError("Argument must be a placement");
}
PyObject* CommandPy::transform(PyObject *args)
{
PyObject *placement;
if ( PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &placement) ) {
Base::PlacementPy *p = static_cast<Base::PlacementPy*>(placement);
Path::Command trCmd = getCommandPtr()->transform( *p->getPlacementPtr() );
return new CommandPy(new Path::Command(trCmd));
} else
throw Py::TypeError("Argument must be a placement");
}
// custom attributes get/set
PyObject *CommandPy::getCustomAttributes(const char* attr) const
{
std::string satt(attr);
if (satt.length() == 1) {
if (isalpha(satt[0])) {
boost::to_upper(satt);
if (getCommandPtr()->Parameters.count(satt)) {
return PyFloat_FromDouble(getCommandPtr()->Parameters[satt]);
}
Py_INCREF(Py_None);
return Py_None;
}
}
return 0;
}
int CommandPy::setCustomAttributes(const char* attr, PyObject* obj)
{
std::string satt(attr);
if (satt.length() == 1) {
if (isalpha(satt[0])) {
boost::to_upper(satt);
double cvalue;
#if PY_MAJOR_VERSION >= 3
if (PyObject_TypeCheck(obj,&(PyLong_Type))) {
cvalue = (double)PyLong_AsLong(obj);
#else
if (PyObject_TypeCheck(obj,&(PyInt_Type))) {
cvalue = (double)PyInt_AsLong(obj);
#endif
} else if (PyObject_TypeCheck(obj,&(PyFloat_Type))) {
cvalue = PyFloat_AsDouble(obj);
} else {
return 0;
}
getCommandPtr()->Parameters[satt]=cvalue;
return 1;
}
}
return 0;
}

View File

@@ -1,256 +1,256 @@
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <BRep_Builder.hxx>
# include <TopoDS_Compound.hxx>
#endif
#include "FeatureArea.h"
#include "FeatureAreaPy.h"
#include <App/DocumentObjectPy.h>
#include <Base/Placement.h>
#include <Mod/Part/App/PartFeature.h>
FC_LOG_LEVEL_INIT("Path.Area",true,true)
using namespace Path;
PROPERTY_SOURCE(Path::FeatureArea, Part::Feature)
PARAM_ENUM_STRING_DECLARE(static const char *Enums,AREA_PARAMS_ALL)
FeatureArea::FeatureArea()
:myInited(false)
{
ADD_PROPERTY(Sources,(0));
ADD_PROPERTY(WorkPlane,(TopoDS_Shape()));
PARAM_PROP_ADD("Area",AREA_PARAMS_OPCODE);
PARAM_PROP_ADD("Area",AREA_PARAMS_BASE);
PARAM_PROP_ADD("Offset",AREA_PARAMS_OFFSET);
PARAM_PROP_ADD("Offset", AREA_PARAMS_OFFSET_CONF);
PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET);
PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET_CONF);
PARAM_PROP_ADD("Section",AREA_PARAMS_SECTION);
PARAM_PROP_ADD("libarea",AREA_PARAMS_CAREA);
PARAM_PROP_SET_ENUM(Enums,AREA_PARAMS_ALL);
PocketMode.setValue((long)0);
}
FeatureArea::~FeatureArea()
{
}
Area &FeatureArea::getArea() {
if(!myInited) execute();
return myArea;
}
App::DocumentObjectExecReturn *FeatureArea::execute(void)
{
myInited = true;
std::vector<App::DocumentObject*> links = Sources.getValues();
if (links.empty())
return new App::DocumentObjectExecReturn("No shapes linked");
for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
if (!(*it && (*it)->isDerivedFrom(Part::Feature::getClassTypeId())))
return new App::DocumentObjectExecReturn("Linked object is not a Part object (has no Shape).");
TopoDS_Shape shape = static_cast<Part::Feature*>(*it)->Shape.getShape().getShape();
if (shape.IsNull())
return new App::DocumentObjectExecReturn("Linked shape object is empty");
}
FC_TIME_INIT(t);
AreaParams params;
#define AREA_PROP_GET(_param) \
params.PARAM_FNAME(_param) = PARAM_FNAME(_param).getValue();
PARAM_FOREACH(AREA_PROP_GET,AREA_PARAMS_CONF)
myArea.clean(true);
myArea.setParams(params);
TopoDS_Shape workPlane = WorkPlane.getShape().getShape();
myArea.setPlane(workPlane);
for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
myArea.add(static_cast<Part::Feature*>(*it)->Shape.getShape().getShape(),
PARAM_PROP_ARGS(AREA_PARAMS_OPCODE));
}
myShapes.clear();
if(myArea.getSectionCount()==0)
myShapes.push_back(myArea.getShape(-1));
else {
myShapes.reserve(myArea.getSectionCount());
for(int i=0;i<(int)myArea.getSectionCount();++i)
myShapes.push_back(myArea.getShape(i));
}
bool hasShape = false;
if(myShapes.empty())
Shape.setValue(TopoDS_Shape());
else{
// compound is built even if there is only one shape to save the
// trouble of messing around with placement
BRep_Builder builder;
TopoDS_Compound compound;
builder.MakeCompound(compound);
for(auto &shape : myShapes) {
if(shape.IsNull()) continue;
hasShape = true;
builder.Add(compound,shape);
}
Shape.setValue(compound);
}
FC_TIME_LOG(t,"feature execute");
if(!hasShape)
return new App::DocumentObjectExecReturn("no output shape");
return DocumentObject::StdReturn;
}
const std::vector<TopoDS_Shape> &FeatureArea::getShapes() {
getArea();
return myShapes;
}
short FeatureArea::mustExecute(void) const
{
if(myInited && !myArea.isBuilt())
return 1;
return Part::Feature::mustExecute();
}
PyObject *FeatureArea::getPyObject()
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new FeatureAreaPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
// FeatureAreaView -------------------------------------------------------------
//
PROPERTY_SOURCE(Path::FeatureAreaView, Part::Feature)
FeatureAreaView::FeatureAreaView()
{
ADD_PROPERTY(Source,(0));
ADD_PROPERTY_TYPE(SectionIndex,(0),"Section",App::Prop_None,"The start index of the section to show, negative value for reverse index from bottom");
ADD_PROPERTY_TYPE(SectionCount,(1),"Section",App::Prop_None,"Number of sections to show, 0 to show all section starting from SectionIndex");
}
std::list<TopoDS_Shape> FeatureAreaView::getShapes() {
std::list<TopoDS_Shape> shapes;
App::DocumentObject* pObj = Source.getValue();
if (!pObj) return shapes;
if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId()))
return shapes;
auto all_shapes = static_cast<FeatureArea*>(pObj)->getShapes();
if(all_shapes.empty())
return shapes;
int index=SectionIndex.getValue(),count=SectionCount.getValue();
if(index<0) {
index += ((int)all_shapes.size());
if(index<0) return shapes;
if(count<=0 || index+1-count<0) {
count = index+1;
index = 0;
}else
index -= count-1;
}else if(index >= (int)all_shapes.size())
return shapes;
if(count<=0) count = all_shapes.size();
count += index;
if(count>(int)all_shapes.size())
count = all_shapes.size();
for(int i=index;i<count;++i)
shapes.push_back(all_shapes[i]);
return shapes;
}
App::DocumentObjectExecReturn *FeatureAreaView::execute(void)
{
App::DocumentObject* pObj = Source.getValue();
if (!pObj)
return new App::DocumentObjectExecReturn("No shape linked");
if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId()))
return new App::DocumentObjectExecReturn("Linked object is not a FeatureArea");
bool hasShape = false;
std::list<TopoDS_Shape> shapes = getShapes();
if(shapes.empty())
Shape.setValue(TopoDS_Shape());
else{
BRep_Builder builder;
TopoDS_Compound compound;
builder.MakeCompound(compound);
for(auto &shape : shapes) {
if(shape.IsNull()) continue;
hasShape = true;
builder.Add(compound,shape);
}
Shape.setValue(compound);
}
if(!hasShape)
return new App::DocumentObjectExecReturn("no output shape");
return DocumentObject::StdReturn;
}
// Python feature ---------------------------------------------------------
namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaPython, Path::FeatureArea)
PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaViewPython, Path::FeatureAreaView)
template<> const char* Path::FeatureAreaPython::getViewProviderName(void) const {
return "PathGui::ViewProviderAreaPython";
}
template<> const char* Path::FeatureAreaViewPython::getViewProviderName(void) const {
return "PathGui::ViewProviderAreaViewPython";
}
/// @endcond
// explicit template instantiation
template class PathExport FeaturePythonT<Path::FeatureArea>;
}
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <BRep_Builder.hxx>
# include <TopoDS_Compound.hxx>
#endif
#include "FeatureArea.h"
#include "FeatureAreaPy.h"
#include <App/DocumentObjectPy.h>
#include <Base/Placement.h>
#include <Mod/Part/App/PartFeature.h>
FC_LOG_LEVEL_INIT("Path.Area",true,true)
using namespace Path;
PROPERTY_SOURCE(Path::FeatureArea, Part::Feature)
PARAM_ENUM_STRING_DECLARE(static const char *Enums,AREA_PARAMS_ALL)
FeatureArea::FeatureArea()
:myInited(false)
{
ADD_PROPERTY(Sources,(0));
ADD_PROPERTY(WorkPlane,(TopoDS_Shape()));
PARAM_PROP_ADD("Area",AREA_PARAMS_OPCODE);
PARAM_PROP_ADD("Area",AREA_PARAMS_BASE);
PARAM_PROP_ADD("Offset",AREA_PARAMS_OFFSET);
PARAM_PROP_ADD("Offset", AREA_PARAMS_OFFSET_CONF);
PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET);
PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET_CONF);
PARAM_PROP_ADD("Section",AREA_PARAMS_SECTION);
PARAM_PROP_ADD("libarea",AREA_PARAMS_CAREA);
PARAM_PROP_SET_ENUM(Enums,AREA_PARAMS_ALL);
PocketMode.setValue((long)0);
}
FeatureArea::~FeatureArea()
{
}
Area &FeatureArea::getArea() {
if(!myInited) execute();
return myArea;
}
App::DocumentObjectExecReturn *FeatureArea::execute(void)
{
myInited = true;
std::vector<App::DocumentObject*> links = Sources.getValues();
if (links.empty())
return new App::DocumentObjectExecReturn("No shapes linked");
for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
if (!(*it && (*it)->isDerivedFrom(Part::Feature::getClassTypeId())))
return new App::DocumentObjectExecReturn("Linked object is not a Part object (has no Shape).");
TopoDS_Shape shape = static_cast<Part::Feature*>(*it)->Shape.getShape().getShape();
if (shape.IsNull())
return new App::DocumentObjectExecReturn("Linked shape object is empty");
}
FC_TIME_INIT(t);
AreaParams params;
#define AREA_PROP_GET(_param) \
params.PARAM_FNAME(_param) = PARAM_FNAME(_param).getValue();
PARAM_FOREACH(AREA_PROP_GET,AREA_PARAMS_CONF)
myArea.clean(true);
myArea.setParams(params);
TopoDS_Shape workPlane = WorkPlane.getShape().getShape();
myArea.setPlane(workPlane);
for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
myArea.add(static_cast<Part::Feature*>(*it)->Shape.getShape().getShape(),
PARAM_PROP_ARGS(AREA_PARAMS_OPCODE));
}
myShapes.clear();
if(myArea.getSectionCount()==0)
myShapes.push_back(myArea.getShape(-1));
else {
myShapes.reserve(myArea.getSectionCount());
for(int i=0;i<(int)myArea.getSectionCount();++i)
myShapes.push_back(myArea.getShape(i));
}
bool hasShape = false;
if(myShapes.empty())
Shape.setValue(TopoDS_Shape());
else{
// compound is built even if there is only one shape to save the
// trouble of messing around with placement
BRep_Builder builder;
TopoDS_Compound compound;
builder.MakeCompound(compound);
for(auto &shape : myShapes) {
if(shape.IsNull()) continue;
hasShape = true;
builder.Add(compound,shape);
}
Shape.setValue(compound);
}
FC_TIME_LOG(t,"feature execute");
if(!hasShape)
return new App::DocumentObjectExecReturn("no output shape");
return DocumentObject::StdReturn;
}
const std::vector<TopoDS_Shape> &FeatureArea::getShapes() {
getArea();
return myShapes;
}
short FeatureArea::mustExecute(void) const
{
if(myInited && !myArea.isBuilt())
return 1;
return Part::Feature::mustExecute();
}
PyObject *FeatureArea::getPyObject()
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new FeatureAreaPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
// FeatureAreaView -------------------------------------------------------------
//
PROPERTY_SOURCE(Path::FeatureAreaView, Part::Feature)
FeatureAreaView::FeatureAreaView()
{
ADD_PROPERTY(Source,(0));
ADD_PROPERTY_TYPE(SectionIndex,(0),"Section",App::Prop_None,"The start index of the section to show, negative value for reverse index from bottom");
ADD_PROPERTY_TYPE(SectionCount,(1),"Section",App::Prop_None,"Number of sections to show, 0 to show all section starting from SectionIndex");
}
std::list<TopoDS_Shape> FeatureAreaView::getShapes() {
std::list<TopoDS_Shape> shapes;
App::DocumentObject* pObj = Source.getValue();
if (!pObj) return shapes;
if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId()))
return shapes;
auto all_shapes = static_cast<FeatureArea*>(pObj)->getShapes();
if(all_shapes.empty())
return shapes;
int index=SectionIndex.getValue(),count=SectionCount.getValue();
if(index<0) {
index += ((int)all_shapes.size());
if(index<0) return shapes;
if(count<=0 || index+1-count<0) {
count = index+1;
index = 0;
}else
index -= count-1;
}else if(index >= (int)all_shapes.size())
return shapes;
if(count<=0) count = all_shapes.size();
count += index;
if(count>(int)all_shapes.size())
count = all_shapes.size();
for(int i=index;i<count;++i)
shapes.push_back(all_shapes[i]);
return shapes;
}
App::DocumentObjectExecReturn *FeatureAreaView::execute(void)
{
App::DocumentObject* pObj = Source.getValue();
if (!pObj)
return new App::DocumentObjectExecReturn("No shape linked");
if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId()))
return new App::DocumentObjectExecReturn("Linked object is not a FeatureArea");
bool hasShape = false;
std::list<TopoDS_Shape> shapes = getShapes();
if(shapes.empty())
Shape.setValue(TopoDS_Shape());
else{
BRep_Builder builder;
TopoDS_Compound compound;
builder.MakeCompound(compound);
for(auto &shape : shapes) {
if(shape.IsNull()) continue;
hasShape = true;
builder.Add(compound,shape);
}
Shape.setValue(compound);
}
if(!hasShape)
return new App::DocumentObjectExecReturn("no output shape");
return DocumentObject::StdReturn;
}
// Python feature ---------------------------------------------------------
namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaPython, Path::FeatureArea)
PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaViewPython, Path::FeatureAreaView)
template<> const char* Path::FeatureAreaPython::getViewProviderName(void) const {
return "PathGui::ViewProviderAreaPython";
}
template<> const char* Path::FeatureAreaViewPython::getViewProviderName(void) const {
return "PathGui::ViewProviderAreaViewPython";
}
/// @endcond
// explicit template instantiation
template class PathExport FeaturePythonT<Path::FeatureArea>;
}

View File

@@ -1,100 +1,100 @@
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#ifndef PATH_FeatureArea_H
#define PATH_FeatureArea_H
#include <App/DocumentObject.h>
#include <App/GeoFeature.h>
#include <App/PropertyUnits.h>
#include <App/FeaturePython.h>
#include "Mod/Part/App/PartFeature.h"
#include "Area.h"
namespace Path
{
class PathExport FeatureArea : public Part::Feature
{
PROPERTY_HEADER(Path::FeatureArea);
public:
/// Constructor
FeatureArea(void);
virtual ~FeatureArea();
Area &getArea();
const std::vector<TopoDS_Shape> &getShapes();
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderArea";
}
virtual App::DocumentObjectExecReturn *execute(void);
virtual short mustExecute(void) const;
virtual PyObject *getPyObject(void);
App::PropertyLinkList Sources;
Part::PropertyPartShape WorkPlane;
PARAM_PROP_DECLARE(AREA_PARAMS_ALL)
void setWorkPlane(const TopoDS_Shape &shape) {
WorkPlane.setValue(shape);
myArea.setPlane(shape);
}
private:
Area myArea;
std::vector<TopoDS_Shape> myShapes;
bool myInited;
};
typedef App::FeaturePythonT<FeatureArea> FeatureAreaPython;
class PathExport FeatureAreaView : public Part::Feature
{
PROPERTY_HEADER(Path::FeatureAreaView);
public:
/// Constructor
FeatureAreaView(void);
std::list<TopoDS_Shape> getShapes();
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderAreaView";
}
virtual App::DocumentObjectExecReturn *execute(void);
App::PropertyLink Source;
App::PropertyInteger SectionIndex;
App::PropertyInteger SectionCount;
};
typedef App::FeaturePythonT<FeatureAreaView> FeatureAreaViewPython;
} //namespace Path
#endif // PATH_FeaturePath_H
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#ifndef PATH_FeatureArea_H
#define PATH_FeatureArea_H
#include <App/DocumentObject.h>
#include <App/GeoFeature.h>
#include <App/PropertyUnits.h>
#include <App/FeaturePython.h>
#include "Mod/Part/App/PartFeature.h"
#include "Area.h"
namespace Path
{
class PathExport FeatureArea : public Part::Feature
{
PROPERTY_HEADER(Path::FeatureArea);
public:
/// Constructor
FeatureArea(void);
virtual ~FeatureArea();
Area &getArea();
const std::vector<TopoDS_Shape> &getShapes();
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderArea";
}
virtual App::DocumentObjectExecReturn *execute(void);
virtual short mustExecute(void) const;
virtual PyObject *getPyObject(void);
App::PropertyLinkList Sources;
Part::PropertyPartShape WorkPlane;
PARAM_PROP_DECLARE(AREA_PARAMS_ALL)
void setWorkPlane(const TopoDS_Shape &shape) {
WorkPlane.setValue(shape);
myArea.setPlane(shape);
}
private:
Area myArea;
std::vector<TopoDS_Shape> myShapes;
bool myInited;
};
typedef App::FeaturePythonT<FeatureArea> FeatureAreaPython;
class PathExport FeatureAreaView : public Part::Feature
{
PROPERTY_HEADER(Path::FeatureAreaView);
public:
/// Constructor
FeatureAreaView(void);
std::list<TopoDS_Shape> getShapes();
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderAreaView";
}
virtual App::DocumentObjectExecReturn *execute(void);
App::PropertyLink Source;
App::PropertyInteger SectionIndex;
App::PropertyInteger SectionCount;
};
typedef App::FeaturePythonT<FeatureAreaView> FeatureAreaViewPython;
} //namespace Path
#endif // PATH_FeaturePath_H

View File

@@ -1,109 +1,109 @@
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#include <CXX/Objects.hxx>
#include <Mod/Part/App/TopoShapePy.h>
#include "FeatureArea.h"
// inclusion of the generated files (generated out of FeatureAreaPy.xml)
#include "FeatureAreaPy.h"
#include "FeatureAreaPy.cpp"
#include "AreaPy.h"
using namespace Path;
// returns a string which represent the object e.g. when printed in python
std::string FeatureAreaPy::representation(void) const
{
return std::string("<Path::FeatureArea>");
}
PyObject* FeatureAreaPy::getArea(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return NULL;
return new AreaPy(new Area(getFeatureAreaPtr()->getArea()));
}
PyObject* FeatureAreaPy::setParams(PyObject *args, PyObject *keywds)
{
static char *kwlist[] = {PARAM_FIELD_STRINGS(NAME,AREA_PARAMS_CONF),NULL};
//Declare variables defined in the NAME field of the CONF parameter list
PARAM_PY_DECLARE(PARAM_FNAME,AREA_PARAMS_CONF);
FeatureArea *feature = getFeatureAreaPtr();
#define AREA_SET(_param) \
PARAM_FNAME(_param) = \
PARAM_TYPED(PARAM_PY_CAST_,_param)(feature->PARAM_FNAME(_param).getValue());
//populate the CONF variables with values in properties
PARAM_FOREACH(AREA_SET,AREA_PARAMS_CONF)
//Parse arguments to overwrite CONF variables
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|" PARAM_PY_KWDS(AREA_PARAMS_CONF), kwlist,
PARAM_REF(PARAM_FNAME,AREA_PARAMS_CONF)))
return 0;
#define AREA_GET(_param) \
feature->PARAM_FNAME(_param).setValue(\
PARAM_TYPED(PARAM_CAST_PY_,_param)(PARAM_FNAME(_param)));
//populate properties with the CONF variables
PARAM_FOREACH(AREA_GET,AREA_PARAMS_CONF)
Py_INCREF(Py_None);
return Py_None;
}
Py::Object FeatureAreaPy::getWorkPlane(void) const {
return Part::shape2pyshape(getFeatureAreaPtr()->getArea().getPlane());
}
void FeatureAreaPy::setWorkPlane(Py::Object obj) {
PyObject* p = obj.ptr();
if (!PyObject_TypeCheck(p, &(Part::TopoShapePy::Type))) {
std::string error = std::string("type must be 'TopoShape', not ");
error += p->ob_type->tp_name;
throw Py::TypeError(error);
}
getFeatureAreaPtr()->setWorkPlane(
static_cast<Part::TopoShapePy*>(p)->getTopoShapePtr()->getShape());
}
PyObject *FeatureAreaPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int FeatureAreaPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#include <CXX/Objects.hxx>
#include <Mod/Part/App/TopoShapePy.h>
#include "FeatureArea.h"
// inclusion of the generated files (generated out of FeatureAreaPy.xml)
#include "FeatureAreaPy.h"
#include "FeatureAreaPy.cpp"
#include "AreaPy.h"
using namespace Path;
// returns a string which represent the object e.g. when printed in python
std::string FeatureAreaPy::representation(void) const
{
return std::string("<Path::FeatureArea>");
}
PyObject* FeatureAreaPy::getArea(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return NULL;
return new AreaPy(new Area(getFeatureAreaPtr()->getArea()));
}
PyObject* FeatureAreaPy::setParams(PyObject *args, PyObject *keywds)
{
static char *kwlist[] = {PARAM_FIELD_STRINGS(NAME,AREA_PARAMS_CONF),NULL};
//Declare variables defined in the NAME field of the CONF parameter list
PARAM_PY_DECLARE(PARAM_FNAME,AREA_PARAMS_CONF);
FeatureArea *feature = getFeatureAreaPtr();
#define AREA_SET(_param) \
PARAM_FNAME(_param) = \
PARAM_TYPED(PARAM_PY_CAST_,_param)(feature->PARAM_FNAME(_param).getValue());
//populate the CONF variables with values in properties
PARAM_FOREACH(AREA_SET,AREA_PARAMS_CONF)
//Parse arguments to overwrite CONF variables
if (!PyArg_ParseTupleAndKeywords(args, keywds,
"|" PARAM_PY_KWDS(AREA_PARAMS_CONF), kwlist,
PARAM_REF(PARAM_FNAME,AREA_PARAMS_CONF)))
return 0;
#define AREA_GET(_param) \
feature->PARAM_FNAME(_param).setValue(\
PARAM_TYPED(PARAM_CAST_PY_,_param)(PARAM_FNAME(_param)));
//populate properties with the CONF variables
PARAM_FOREACH(AREA_GET,AREA_PARAMS_CONF)
Py_INCREF(Py_None);
return Py_None;
}
Py::Object FeatureAreaPy::getWorkPlane(void) const {
return Part::shape2pyshape(getFeatureAreaPtr()->getArea().getPlane());
}
void FeatureAreaPy::setWorkPlane(Py::Object obj) {
PyObject* p = obj.ptr();
if (!PyObject_TypeCheck(p, &(Part::TopoShapePy::Type))) {
std::string error = std::string("type must be 'TopoShape', not ");
error += p->ob_type->tp_name;
throw Py::TypeError(error);
}
getFeatureAreaPtr()->setWorkPlane(
static_cast<Part::TopoShapePy*>(p)->getTopoShapePtr()->getShape());
}
PyObject *FeatureAreaPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int FeatureAreaPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}

View File

@@ -1,78 +1,78 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include "FeaturePath.h"
#include <App/DocumentObjectPy.h>
#include <Base/Placement.h>
using namespace Path;
PROPERTY_SOURCE(Path::Feature, App::GeoFeature)
Feature::Feature()
{
ADD_PROPERTY_TYPE(Path,(Path::Toolpath()),"Base",App::Prop_None,"The path data of this feature");
}
Feature::~Feature()
{
}
short Feature::mustExecute(void) const
{
return App::GeoFeature::mustExecute();
}
PyObject *Feature::getPyObject()
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new App::DocumentObjectPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
void Feature::onChanged(const App::Property* prop)
{
App::GeoFeature::onChanged(prop);
}
// Python Path feature ---------------------------------------------------------
namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeaturePython, Path::Feature)
template<> const char* Path::FeaturePython::getViewProviderName(void) const {
return "PathGui::ViewProviderPathPython";
}
/// @endcond
// explicit template instantiation
template class PathExport FeaturePythonT<Path::Feature>;
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include "FeaturePath.h"
#include <App/DocumentObjectPy.h>
#include <Base/Placement.h>
using namespace Path;
PROPERTY_SOURCE(Path::Feature, App::GeoFeature)
Feature::Feature()
{
ADD_PROPERTY_TYPE(Path,(Path::Toolpath()),"Base",App::Prop_None,"The path data of this feature");
}
Feature::~Feature()
{
}
short Feature::mustExecute(void) const
{
return App::GeoFeature::mustExecute();
}
PyObject *Feature::getPyObject()
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new App::DocumentObjectPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
void Feature::onChanged(const App::Property* prop)
{
App::GeoFeature::onChanged(prop);
}
// Python Path feature ---------------------------------------------------------
namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeaturePython, Path::Feature)
template<> const char* Path::FeaturePython::getViewProviderName(void) const {
return "PathGui::ViewProviderPathPython";
}
/// @endcond
// explicit template instantiation
template class PathExport FeaturePythonT<Path::Feature>;
}

View File

@@ -1,72 +1,72 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_FeaturePath_H
#define PATH_FeaturePath_H
#include <App/DocumentObject.h>
#include <App/GeoFeature.h>
#include <App/PropertyFile.h>
#include <App/PropertyGeo.h>
#include <App/FeaturePython.h>
#include "Path.h"
#include "PropertyPath.h"
namespace Path
{
class PathExport Feature : public App::GeoFeature
{
PROPERTY_HEADER(Path::Feature);
public:
/// Constructor
Feature(void);
virtual ~Feature();
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderPath";
}
virtual App::DocumentObjectExecReturn *execute(void) {
return App::DocumentObject::StdReturn;
}
virtual short mustExecute(void) const;
virtual PyObject *getPyObject(void);
PropertyPath Path;
protected:
/// get called by the container when a property has changed
virtual void onChanged (const App::Property* prop);
};
typedef App::FeaturePythonT<Feature> FeaturePython;
} //namespace Path
#endif // PATH_FeaturePath_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_FeaturePath_H
#define PATH_FeaturePath_H
#include <App/DocumentObject.h>
#include <App/GeoFeature.h>
#include <App/PropertyFile.h>
#include <App/PropertyGeo.h>
#include <App/FeaturePython.h>
#include "Path.h"
#include "PropertyPath.h"
namespace Path
{
class PathExport Feature : public App::GeoFeature
{
PROPERTY_HEADER(Path::Feature);
public:
/// Constructor
Feature(void);
virtual ~Feature();
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderPath";
}
virtual App::DocumentObjectExecReturn *execute(void) {
return App::DocumentObject::StdReturn;
}
virtual short mustExecute(void) const;
virtual PyObject *getPyObject(void);
PropertyPath Path;
protected:
/// get called by the container when a property has changed
virtual void onChanged (const App::Property* prop);
};
typedef App::FeaturePythonT<Feature> FeaturePython;
} //namespace Path
#endif // PATH_FeaturePath_H

View File

@@ -1,131 +1,131 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include "FeaturePathCompound.h"
#include "Command.h"
#include "Path.h"
#include "FeaturePathCompoundPy.h"
#include <App/FeaturePythonPyImp.h>
using namespace Path;
using namespace App;
PROPERTY_SOURCE(Path::FeatureCompound, Path::Feature)
FeatureCompound::FeatureCompound()
{
ADD_PROPERTY_TYPE( Group, (0), "Base",Prop_None,"Ordered list of paths to combine");
ADD_PROPERTY_TYPE( UsePlacements, (false), "Base",Prop_None,"Specifies if the placements of children must be computed");
}
FeatureCompound::~FeatureCompound()
{
}
App::DocumentObjectExecReturn *FeatureCompound::execute(void)
{
const std::vector<DocumentObject*> &Paths = Group.getValues();
Path::Toolpath result;
for (std::vector<DocumentObject*>::const_iterator it= Paths.begin();it!=Paths.end();++it) {
if ((*it)->getTypeId().isDerivedFrom(Path::Feature::getClassTypeId())){
const std::vector<Command*> &cmds = static_cast<Path::Feature*>(*it)->Path.getValue().getCommands();
const Base::Placement pl = static_cast<Path::Feature*>(*it)->Placement.getValue();
for (std::vector<Command*>::const_iterator it2= cmds.begin();it2!=cmds.end();++it2) {
if (UsePlacements.getValue() == true) {
result.addCommand((*it2)->transform(pl));
} else {
result.addCommand(**it2);
}
}
} else {
return new App::DocumentObjectExecReturn("Not all objects in group are paths!");
}
}
result.setCenter(Path.getValue().getCenter());
Path.setValue(result);
return App::DocumentObject::StdReturn;
}
bool FeatureCompound::hasObject(const DocumentObject* obj) const
{
const std::vector<DocumentObject*>& grp = Group.getValues();
for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
if (*it == obj)
return true;
}
return false;
}
void FeatureCompound::addObject(DocumentObject* obj)
{
if (!hasObject(obj)) {
std::vector<DocumentObject*> grp = Group.getValues();
grp.push_back(obj);
Group.setValues(grp);
}
}
void FeatureCompound::removeObject(DocumentObject* obj)
{
std::vector<DocumentObject*> grp = Group.getValues();
for (std::vector<DocumentObject*>::iterator it = grp.begin(); it != grp.end(); ++it) {
if (*it == obj) {
grp.erase(it);
Group.setValues(grp);
break;
}
}
}
PyObject *FeatureCompound::getPyObject()
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new FeaturePathCompoundPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
// Python Path Compound feature ---------------------------------------------------------
namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeatureCompoundPython, Path::FeatureCompound)
template<> const char* Path::FeatureCompoundPython::getViewProviderName(void) const {
return "PathGui::ViewProviderPathCompoundPython";
}
/// @endcond
// explicit template instantiation
template class PathExport FeaturePythonT<Path::FeatureCompound>;
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include "FeaturePathCompound.h"
#include "Command.h"
#include "Path.h"
#include "FeaturePathCompoundPy.h"
#include <App/FeaturePythonPyImp.h>
using namespace Path;
using namespace App;
PROPERTY_SOURCE(Path::FeatureCompound, Path::Feature)
FeatureCompound::FeatureCompound()
{
ADD_PROPERTY_TYPE( Group, (0), "Base",Prop_None,"Ordered list of paths to combine");
ADD_PROPERTY_TYPE( UsePlacements, (false), "Base",Prop_None,"Specifies if the placements of children must be computed");
}
FeatureCompound::~FeatureCompound()
{
}
App::DocumentObjectExecReturn *FeatureCompound::execute(void)
{
const std::vector<DocumentObject*> &Paths = Group.getValues();
Path::Toolpath result;
for (std::vector<DocumentObject*>::const_iterator it= Paths.begin();it!=Paths.end();++it) {
if ((*it)->getTypeId().isDerivedFrom(Path::Feature::getClassTypeId())){
const std::vector<Command*> &cmds = static_cast<Path::Feature*>(*it)->Path.getValue().getCommands();
const Base::Placement pl = static_cast<Path::Feature*>(*it)->Placement.getValue();
for (std::vector<Command*>::const_iterator it2= cmds.begin();it2!=cmds.end();++it2) {
if (UsePlacements.getValue() == true) {
result.addCommand((*it2)->transform(pl));
} else {
result.addCommand(**it2);
}
}
} else {
return new App::DocumentObjectExecReturn("Not all objects in group are paths!");
}
}
result.setCenter(Path.getValue().getCenter());
Path.setValue(result);
return App::DocumentObject::StdReturn;
}
bool FeatureCompound::hasObject(const DocumentObject* obj) const
{
const std::vector<DocumentObject*>& grp = Group.getValues();
for (std::vector<DocumentObject*>::const_iterator it = grp.begin(); it != grp.end(); ++it) {
if (*it == obj)
return true;
}
return false;
}
void FeatureCompound::addObject(DocumentObject* obj)
{
if (!hasObject(obj)) {
std::vector<DocumentObject*> grp = Group.getValues();
grp.push_back(obj);
Group.setValues(grp);
}
}
void FeatureCompound::removeObject(DocumentObject* obj)
{
std::vector<DocumentObject*> grp = Group.getValues();
for (std::vector<DocumentObject*>::iterator it = grp.begin(); it != grp.end(); ++it) {
if (*it == obj) {
grp.erase(it);
Group.setValues(grp);
break;
}
}
}
PyObject *FeatureCompound::getPyObject()
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new FeaturePathCompoundPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
// Python Path Compound feature ---------------------------------------------------------
namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeatureCompoundPython, Path::FeatureCompound)
template<> const char* Path::FeatureCompoundPython::getViewProviderName(void) const {
return "PathGui::ViewProviderPathCompoundPython";
}
/// @endcond
// explicit template instantiation
template class PathExport FeaturePythonT<Path::FeatureCompound>;
}

View File

@@ -1,72 +1,72 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_FeatureCompound_H
#define PATH_FeatureCompound_H
#include <App/GeoFeature.h>
#include <App/PropertyFile.h>
#include <App/PropertyGeo.h>
#include <App/PropertyUnits.h>
#include "Path.h"
#include "FeaturePath.h"
#include "PropertyPath.h"
namespace Path
{
class PathExport FeatureCompound : public Path::Feature
{
PROPERTY_HEADER(Path::Feature);
public:
/// Constructor
FeatureCompound(void);
virtual ~FeatureCompound();
App::PropertyLinkList Group;
App::PropertyBool UsePlacements;
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderPathCompound";
}
virtual App::DocumentObjectExecReturn *execute(void);
/// Checks whether the object \a obj is part of this group.
bool hasObject(const DocumentObject* obj) const;
/// Adds an object to this group.
void addObject(DocumentObject* obj);
/// Removes an object from this group.
void removeObject(DocumentObject* obj);
virtual PyObject *getPyObject(void);
};
typedef App::FeaturePythonT<FeatureCompound> FeatureCompoundPython;
} //namespace Path
#endif // PATH_FeatureCompound_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_FeatureCompound_H
#define PATH_FeatureCompound_H
#include <App/GeoFeature.h>
#include <App/PropertyFile.h>
#include <App/PropertyGeo.h>
#include <App/PropertyUnits.h>
#include "Path.h"
#include "FeaturePath.h"
#include "PropertyPath.h"
namespace Path
{
class PathExport FeatureCompound : public Path::Feature
{
PROPERTY_HEADER(Path::Feature);
public:
/// Constructor
FeatureCompound(void);
virtual ~FeatureCompound();
App::PropertyLinkList Group;
App::PropertyBool UsePlacements;
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderPathCompound";
}
virtual App::DocumentObjectExecReturn *execute(void);
/// Checks whether the object \a obj is part of this group.
bool hasObject(const DocumentObject* obj) const;
/// Adds an object to this group.
void addObject(DocumentObject* obj);
/// Removes an object from this group.
void removeObject(DocumentObject* obj);
virtual PyObject *getPyObject(void);
};
typedef App::FeaturePythonT<FeatureCompound> FeatureCompoundPython;
} //namespace Path
#endif // PATH_FeatureCompound_H

View File

@@ -1,28 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="DocumentObjectPy"
Name="FeaturePathCompoundPy"
Twin="FeaturePathCompound"
TwinPointer="FeatureCompound"
Include="Mod/Path/App/FeaturePathCompound.h"
Namespace="Path"
FatherInclude="App/DocumentObjectPy.h"
FatherNamespace="App">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>This class handles Path Compound features</UserDocu>
</Documentation>
<Methode Name="addObject">
<Documentation>
<UserDocu>Add an object to the group</UserDocu>
</Documentation>
</Methode>
<Methode Name="removeObject">
<Documentation>
<UserDocu>Remove an object from the group</UserDocu>
</Documentation>
</Methode>
<CustomAttributes />
</PythonExport>
</GenerateModel>
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="DocumentObjectPy"
Name="FeaturePathCompoundPy"
Twin="FeaturePathCompound"
TwinPointer="FeatureCompound"
Include="Mod/Path/App/FeaturePathCompound.h"
Namespace="Path"
FatherInclude="App/DocumentObjectPy.h"
FatherNamespace="App">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>This class handles Path Compound features</UserDocu>
</Documentation>
<Methode Name="addObject">
<Documentation>
<UserDocu>Add an object to the group</UserDocu>
</Documentation>
</Methode>
<Methode Name="removeObject">
<Documentation>
<UserDocu>Remove an object from the group</UserDocu>
</Documentation>
</Methode>
<CustomAttributes />
</PythonExport>
</GenerateModel>

View File

@@ -1,139 +1,139 @@
/***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "FeaturePathCompound.h"
#include <CXX/Objects.hxx>
// inclusion of the generated files (generated out of FeaturePathCompoundPy.xml)
#include "FeaturePathCompoundPy.h"
#include "FeaturePathCompoundPy.cpp"
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string FeaturePathCompoundPy::representation(void) const
{
return std::string("<Path::FeatureCompound>");
}
PyObject* FeaturePathCompoundPy::addObject(PyObject *args)
{
PyObject *object;
if (!PyArg_ParseTuple(args, "O!", &(DocumentObjectPy::Type), &object)) // convert args: Python->C
return NULL; // NULL triggers exception
DocumentObjectPy* docObj = static_cast<DocumentObjectPy*>(object);
if (!docObj->getDocumentObjectPtr() || !docObj->getDocumentObjectPtr()->getNameInDocument()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot add an invalid object");
return NULL;
}
if (docObj->getDocumentObjectPtr()->getDocument() != getFeaturePathCompoundPtr()->getDocument()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot add an object from another document to this group");
return NULL;
}
if (docObj->getDocumentObjectPtr() == this->getFeaturePathCompoundPtr()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot add a group object to itself");
return NULL;
}
FeatureCompound* comp = getFeaturePathCompoundPtr();
if (comp->getTypeId().isDerivedFrom(Path::FeatureCompoundPython::getClassTypeId())) {
FeatureCompoundPython* comppy = static_cast<FeatureCompoundPython*>(comp);
App::Property* proxy = comppy->getPropertyByName("Proxy");
if (proxy && proxy->getTypeId() == App::PropertyPythonObject::getClassTypeId()) {
Py::Object vp = static_cast<App::PropertyPythonObject*>(proxy)->getValue();
if (vp.hasAttr(std::string("addObject"))) {
Py::Callable method(vp.getAttr(std::string("addObject")));
// check to which method this belongs to avoid an infinite recursion
if (method.getAttr(std::string("__self__")) != Py::Object(this)) {
Py::Tuple args(1);
args[0] = Py::Object(object);
method.apply(args);
Py_Return;
}
}
}
}
comp->addObject(docObj->getDocumentObjectPtr());
Py_Return;
}
PyObject* FeaturePathCompoundPy::removeObject(PyObject *args)
{
PyObject *object;
if (!PyArg_ParseTuple(args, "O!", &(DocumentObjectPy::Type), &object)) // convert args: Python->C
return NULL; // NULL triggers exception
DocumentObjectPy* docObj = static_cast<DocumentObjectPy*>(object);
if (!docObj->getDocumentObjectPtr() || !docObj->getDocumentObjectPtr()->getNameInDocument()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot remove an invalid object");
return NULL;
}
if (docObj->getDocumentObjectPtr()->getDocument() != getFeaturePathCompoundPtr()->getDocument()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot remove an object from another document from this group");
return NULL;
}
FeatureCompound* comp = getFeaturePathCompoundPtr();
if (comp->getTypeId().isDerivedFrom(Path::FeatureCompoundPython::getClassTypeId())) {
FeatureCompoundPython* comppy = static_cast<FeatureCompoundPython*>(comp);
App::Property* proxy = comppy->getPropertyByName("Proxy");
if (proxy && proxy->getTypeId() == App::PropertyPythonObject::getClassTypeId()) {
Py::Object vp = static_cast<App::PropertyPythonObject*>(proxy)->getValue();
if (vp.hasAttr(std::string("removeObject"))) {
Py::Callable method(vp.getAttr(std::string("removeObject")));
// check to which method this belongs to avoid an infinite recursion
if (method.getAttr(std::string("__self__")) != Py::Object(this)) {
Py::Tuple args(1);
args[0] = Py::Object(object);
method.apply(args);
Py_Return;
}
}
}
}
comp->removeObject(docObj->getDocumentObjectPtr());
Py_Return;
}
PyObject *FeaturePathCompoundPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int FeaturePathCompoundPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
/***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "FeaturePathCompound.h"
#include <CXX/Objects.hxx>
// inclusion of the generated files (generated out of FeaturePathCompoundPy.xml)
#include "FeaturePathCompoundPy.h"
#include "FeaturePathCompoundPy.cpp"
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string FeaturePathCompoundPy::representation(void) const
{
return std::string("<Path::FeatureCompound>");
}
PyObject* FeaturePathCompoundPy::addObject(PyObject *args)
{
PyObject *object;
if (!PyArg_ParseTuple(args, "O!", &(DocumentObjectPy::Type), &object)) // convert args: Python->C
return NULL; // NULL triggers exception
DocumentObjectPy* docObj = static_cast<DocumentObjectPy*>(object);
if (!docObj->getDocumentObjectPtr() || !docObj->getDocumentObjectPtr()->getNameInDocument()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot add an invalid object");
return NULL;
}
if (docObj->getDocumentObjectPtr()->getDocument() != getFeaturePathCompoundPtr()->getDocument()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot add an object from another document to this group");
return NULL;
}
if (docObj->getDocumentObjectPtr() == this->getFeaturePathCompoundPtr()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot add a group object to itself");
return NULL;
}
FeatureCompound* comp = getFeaturePathCompoundPtr();
if (comp->getTypeId().isDerivedFrom(Path::FeatureCompoundPython::getClassTypeId())) {
FeatureCompoundPython* comppy = static_cast<FeatureCompoundPython*>(comp);
App::Property* proxy = comppy->getPropertyByName("Proxy");
if (proxy && proxy->getTypeId() == App::PropertyPythonObject::getClassTypeId()) {
Py::Object vp = static_cast<App::PropertyPythonObject*>(proxy)->getValue();
if (vp.hasAttr(std::string("addObject"))) {
Py::Callable method(vp.getAttr(std::string("addObject")));
// check to which method this belongs to avoid an infinite recursion
if (method.getAttr(std::string("__self__")) != Py::Object(this)) {
Py::Tuple args(1);
args[0] = Py::Object(object);
method.apply(args);
Py_Return;
}
}
}
}
comp->addObject(docObj->getDocumentObjectPtr());
Py_Return;
}
PyObject* FeaturePathCompoundPy::removeObject(PyObject *args)
{
PyObject *object;
if (!PyArg_ParseTuple(args, "O!", &(DocumentObjectPy::Type), &object)) // convert args: Python->C
return NULL; // NULL triggers exception
DocumentObjectPy* docObj = static_cast<DocumentObjectPy*>(object);
if (!docObj->getDocumentObjectPtr() || !docObj->getDocumentObjectPtr()->getNameInDocument()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot remove an invalid object");
return NULL;
}
if (docObj->getDocumentObjectPtr()->getDocument() != getFeaturePathCompoundPtr()->getDocument()) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot remove an object from another document from this group");
return NULL;
}
FeatureCompound* comp = getFeaturePathCompoundPtr();
if (comp->getTypeId().isDerivedFrom(Path::FeatureCompoundPython::getClassTypeId())) {
FeatureCompoundPython* comppy = static_cast<FeatureCompoundPython*>(comp);
App::Property* proxy = comppy->getPropertyByName("Proxy");
if (proxy && proxy->getTypeId() == App::PropertyPythonObject::getClassTypeId()) {
Py::Object vp = static_cast<App::PropertyPythonObject*>(proxy)->getValue();
if (vp.hasAttr(std::string("removeObject"))) {
Py::Callable method(vp.getAttr(std::string("removeObject")));
// check to which method this belongs to avoid an infinite recursion
if (method.getAttr(std::string("__self__")) != Py::Object(this)) {
Py::Tuple args(1);
args[0] = Py::Object(object);
method.apply(args);
Py_Return;
}
}
}
}
comp->removeObject(docObj->getDocumentObjectPtr());
Py_Return;
}
PyObject *FeaturePathCompoundPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int FeaturePathCompoundPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}

View File

@@ -1,110 +1,110 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
/*
* Copyright (c) 2017 Zheng, Lei <realthunder.dev@gmail.com>
*/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <TopoDS.hxx>
# include <TopoDS_Shape.hxx>
# include <TopoDS_Edge.hxx>
# include <TopExp_Explorer.hxx>
# include <Standard_Failure.hxx>
# include <Standard_Version.hxx>
# include <BRepBuilderAPI_MakeWire.hxx>
#endif
#include "FeaturePathShape.h"
#include "Command.h"
#include <App/DocumentObjectPy.h>
#include <Base/Placement.h>
#include <Mod/Part/App/TopoShape.h>
#include <Mod/Part/App/PartFeature.h>
#include "FeatureArea.h"
using namespace Path;
PROPERTY_SOURCE(Path::FeatureShape, Path::Feature)
PARAM_ENUM_STRING_DECLARE(static const char *Enums,AREA_PARAMS_PATH)
FeatureShape::FeatureShape()
{
ADD_PROPERTY(Sources,(0));
ADD_PROPERTY_TYPE(StartPoint,(Base::Vector3d()),"Path",App::Prop_None,"Feed start position");
ADD_PROPERTY_TYPE(UseStartPoint,(false),"Path",App::Prop_None,"Enable feed start position");
PARAM_PROP_ADD("Path",AREA_PARAMS_PATH);
PARAM_PROP_SET_ENUM(Enums,AREA_PARAMS_PATH);
}
FeatureShape::~FeatureShape()
{
}
App::DocumentObjectExecReturn *FeatureShape::execute(void)
{
Toolpath path;
std::vector<App::DocumentObject*> links = Sources.getValues();
if (links.empty()) {
Path.setValue(path);
return new App::DocumentObjectExecReturn("No shapes linked");
}
const Base::Vector3d &v = StartPoint.getValue();
gp_Pnt pstart(v.x,v.y,v.z);
std::list<TopoDS_Shape> shapes;
for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
if (!(*it && (*it)->isDerivedFrom(Part::Feature::getClassTypeId())))
continue;
const TopoDS_Shape &shape = static_cast<Part::Feature*>(*it)->Shape.getShape().getShape();
if (shape.IsNull())
continue;
shapes.push_back(shape);
}
Area::toPath(path,shapes,UseStartPoint.getValue()?&pstart:0,0,PARAM_PROP_ARGS(AREA_PARAMS_PATH));
Path.setValue(path);
return App::DocumentObject::StdReturn;
}
// Python Path Shape feature ---------------------------------------------------------
namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeatureShapePython, Path::FeatureShape)
template<> const char* Path::FeatureShapePython::getViewProviderName(void) const {
return "PathGui::ViewProviderPathShape";
}
/// @endcond
// explicit template instantiation
template class PathExport FeaturePythonT<Path::FeatureShape>;
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
/*
* Copyright (c) 2017 Zheng, Lei <realthunder.dev@gmail.com>
*/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <TopoDS.hxx>
# include <TopoDS_Shape.hxx>
# include <TopoDS_Edge.hxx>
# include <TopExp_Explorer.hxx>
# include <Standard_Failure.hxx>
# include <Standard_Version.hxx>
# include <BRepBuilderAPI_MakeWire.hxx>
#endif
#include "FeaturePathShape.h"
#include "Command.h"
#include <App/DocumentObjectPy.h>
#include <Base/Placement.h>
#include <Mod/Part/App/TopoShape.h>
#include <Mod/Part/App/PartFeature.h>
#include "FeatureArea.h"
using namespace Path;
PROPERTY_SOURCE(Path::FeatureShape, Path::Feature)
PARAM_ENUM_STRING_DECLARE(static const char *Enums,AREA_PARAMS_PATH)
FeatureShape::FeatureShape()
{
ADD_PROPERTY(Sources,(0));
ADD_PROPERTY_TYPE(StartPoint,(Base::Vector3d()),"Path",App::Prop_None,"Feed start position");
ADD_PROPERTY_TYPE(UseStartPoint,(false),"Path",App::Prop_None,"Enable feed start position");
PARAM_PROP_ADD("Path",AREA_PARAMS_PATH);
PARAM_PROP_SET_ENUM(Enums,AREA_PARAMS_PATH);
}
FeatureShape::~FeatureShape()
{
}
App::DocumentObjectExecReturn *FeatureShape::execute(void)
{
Toolpath path;
std::vector<App::DocumentObject*> links = Sources.getValues();
if (links.empty()) {
Path.setValue(path);
return new App::DocumentObjectExecReturn("No shapes linked");
}
const Base::Vector3d &v = StartPoint.getValue();
gp_Pnt pstart(v.x,v.y,v.z);
std::list<TopoDS_Shape> shapes;
for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
if (!(*it && (*it)->isDerivedFrom(Part::Feature::getClassTypeId())))
continue;
const TopoDS_Shape &shape = static_cast<Part::Feature*>(*it)->Shape.getShape().getShape();
if (shape.IsNull())
continue;
shapes.push_back(shape);
}
Area::toPath(path,shapes,UseStartPoint.getValue()?&pstart:0,0,PARAM_PROP_ARGS(AREA_PARAMS_PATH));
Path.setValue(path);
return App::DocumentObject::StdReturn;
}
// Python Path Shape feature ---------------------------------------------------------
namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeatureShapePython, Path::FeatureShape)
template<> const char* Path::FeatureShapePython::getViewProviderName(void) const {
return "PathGui::ViewProviderPathShape";
}
/// @endcond
// explicit template instantiation
template class PathExport FeaturePythonT<Path::FeatureShape>;
}

View File

@@ -1,80 +1,80 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
/*
* Copyright (c) 2017 Zheng, Lei <realthunder.dev@gmail.com>
*/
#ifndef PATH_FeaturePathShape_H
#define PATH_FeaturePathShape_H
#include <App/DocumentObject.h>
#include <App/GeoFeature.h>
#include <App/PropertyGeo.h>
#include <App/FeaturePython.h>
#include "Mod/Part/App/PropertyTopoShape.h"
#include "PropertyPath.h"
#include "FeaturePath.h"
#include "FeatureArea.h"
#include "Area.h"
namespace Path
{
class PathExport FeatureShape : public Path::Feature
{
PROPERTY_HEADER(Path::FeatureShape);
public:
/// Constructor
FeatureShape(void);
virtual ~FeatureShape();
// Part::PropertyPartShape Shape;
App::PropertyLinkList Sources;
App::PropertyVector StartPoint;
App::PropertyBool UseStartPoint;
PARAM_PROP_DECLARE(AREA_PARAMS_PATH)
//@{
/// recalculate the feature
virtual App::DocumentObjectExecReturn *execute(void);
//@}
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderPathShape";
}
protected:
/// get called by the container when a property has changed
//virtual void onChanged (const App::Property* prop);
};
typedef App::FeaturePythonT<FeatureShape> FeatureShapePython;
} //namespace Path
#endif // PATH_FeaturePathShape_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
/*
* Copyright (c) 2017 Zheng, Lei <realthunder.dev@gmail.com>
*/
#ifndef PATH_FeaturePathShape_H
#define PATH_FeaturePathShape_H
#include <App/DocumentObject.h>
#include <App/GeoFeature.h>
#include <App/PropertyGeo.h>
#include <App/FeaturePython.h>
#include "Mod/Part/App/PropertyTopoShape.h"
#include "PropertyPath.h"
#include "FeaturePath.h"
#include "FeatureArea.h"
#include "Area.h"
namespace Path
{
class PathExport FeatureShape : public Path::Feature
{
PROPERTY_HEADER(Path::FeatureShape);
public:
/// Constructor
FeatureShape(void);
virtual ~FeatureShape();
// Part::PropertyPartShape Shape;
App::PropertyLinkList Sources;
App::PropertyVector StartPoint;
App::PropertyBool UseStartPoint;
PARAM_PROP_DECLARE(AREA_PARAMS_PATH)
//@{
/// recalculate the feature
virtual App::DocumentObjectExecReturn *execute(void);
//@}
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
return "PathGui::ViewProviderPathShape";
}
protected:
/// get called by the container when a property has changed
//virtual void onChanged (const App::Property* prop);
};
typedef App::FeaturePythonT<FeatureShape> FeatureShapePython;
} //namespace Path
#endif // PATH_FeaturePathShape_H

View File

@@ -1,498 +1,498 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/regex.hpp>
#endif
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Stream.h>
#include <Base/Exception.h>
#include <Base/Console.h>
// KDL stuff - at the moment, not used
//#include "Mod/Robot/App/kdl_cp/path_line.hpp"
//#include "Mod/Robot/App/kdl_cp/path_circle.hpp"
//#include "Mod/Robot/App/kdl_cp/rotational_interpolation_sa.hpp"
//#include "Mod/Robot/App/kdl_cp/utilities/error.h"
#include "Path.h"
#include <Mod/Path/App/PathSegmentWalker.h>
using namespace Path;
using namespace Base;
TYPESYSTEM_SOURCE(Path::Toolpath , Base::Persistence)
Toolpath::Toolpath()
{
}
Toolpath::Toolpath(const Toolpath& otherPath)
: vpcCommands(otherPath.vpcCommands.size())
, center(otherPath.center)
{
*this = otherPath;
recalculate();
}
Toolpath::~Toolpath()
{
clear();
}
Toolpath &Toolpath::operator=(const Toolpath& otherPath)
{
if (this == &otherPath)
return *this;
clear();
vpcCommands.resize(otherPath.vpcCommands.size());
int i = 0;
for (std::vector<Command*>::const_iterator it=otherPath.vpcCommands.begin();it!=otherPath.vpcCommands.end();++it,i++) {
vpcCommands[i] = new Command(**it);
}
center = otherPath.center;
recalculate();
return *this;
}
void Toolpath::clear(void)
{
for(std::vector<Command*>::iterator it = vpcCommands.begin();it!=vpcCommands.end();++it)
delete ( *it );
vpcCommands.clear();
recalculate();
}
void Toolpath::addCommand(const Command &Cmd)
{
Command *tmp = new Command(Cmd);
vpcCommands.push_back(tmp);
recalculate();
}
void Toolpath::insertCommand(const Command &Cmd, int pos)
{
if (pos == -1) {
addCommand(Cmd);
} else if (pos <= static_cast<int>(vpcCommands.size())) {
Command *tmp = new Command(Cmd);
vpcCommands.insert(vpcCommands.begin()+pos,tmp);
} else {
throw Base::IndexError("Index not in range");
}
recalculate();
}
void Toolpath::deleteCommand(int pos)
{
if (pos == -1) {
//delete(*vpcCommands.rbegin()); // causes crash
vpcCommands.pop_back();
} else if (pos <= static_cast<int>(vpcCommands.size())) {
vpcCommands.erase (vpcCommands.begin()+pos);
} else {
throw Base::IndexError("Index not in range");
}
recalculate();
}
double Toolpath::getLength()
{
if(vpcCommands.size()==0)
return 0;
double l = 0;
Vector3d last(0,0,0);
Vector3d next;
for(std::vector<Command*>::const_iterator it = vpcCommands.begin();it!=vpcCommands.end();++it) {
std::string name = (*it)->Name;
next = (*it)->getPlacement(last).getPosition();
if ( (name == "G0") || (name == "G00") || (name == "G1") || (name == "G01") ) {
// straight line
l += (next - last).Length();
last = next;
} else if ( (name == "G2") || (name == "G02") || (name == "G3") || (name == "G03") ) {
// arc
Vector3d center = (*it)->getCenter();
double radius = (last - center).Length();
double angle = (next - center).GetAngle(last - center);
l += angle * radius;
last = next;
}
}
return l;
}
double Toolpath::getCycleTime(double hFeed, double vFeed, double hRapid, double vRapid)
{
// check the feedrates are set
if ((hFeed == 0) || (vFeed == 0)){
Base::Console().Warning("Feed Rate Error: Check Tool Controllers have Feed Rates");
return 0;
}
if (hRapid == 0){
hRapid = hFeed;
}
if (vRapid == 0){
vRapid = vFeed;
}
if(vpcCommands.size()==0)
return 0;
double l = 0;
double time = 0;
bool verticalMove = false;
Vector3d last(0,0,0);
Vector3d next;
for(std::vector<Command*>::const_iterator it = vpcCommands.begin();it!=vpcCommands.end();++it) {
std::string name = (*it)->Name;
float feedrate = (*it)->getParam("F");
l = 0;
verticalMove = false;
feedrate = hFeed;
next = (*it)->getPlacement(last).getPosition();
if (last.z != next.z){
verticalMove = true;
feedrate = vFeed;
}
if ((name == "G0") || (name == "G00")){
// Rapid Move
l += (next - last).Length();
feedrate = hRapid;
if(verticalMove){
feedrate = vRapid;
}
}else if ((name == "G1") || (name == "G01")) {
// Feed Move
l += (next - last).Length();
}else if ((name == "G2") || (name == "G02") || (name == "G3") || (name == "G03") ) {
// Arc Move
Vector3d center = (*it)->getCenter();
double radius = (last - center).Length();
double angle = (next - center).GetAngle(last - center);
l += angle * radius;
}
time += l / feedrate;
last = next;
}
return time;
}
class BoundBoxSegmentVisitor : public PathSegmentVisitor
{
public:
BoundBoxSegmentVisitor()
{ }
virtual void g0(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque<Base::Vector3d> &pts)
{
(void)id;
processPt(last);
processPts(pts);
processPt(next);
}
virtual void g1(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque<Base::Vector3d> &pts)
{
(void)id;
processPt(last);
processPts(pts);
processPt(next);
}
virtual void g23(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque<Base::Vector3d> &pts, const Base::Vector3d &center)
{
(void)id;
(void)center;
processPt(last);
processPts(pts);
processPt(next);
}
virtual void g8x(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque<Base::Vector3d> &pts,
const std::deque<Base::Vector3d> &p, const std::deque<Base::Vector3d> &q)
{
(void)id;
(void)q; // always within the bounds of p
processPt(last);
processPts(pts);
processPts(p);
processPt(next);
}
virtual void g38(int id, const Base::Vector3d &last, const Base::Vector3d &next)
{
(void)id;
processPt(last);
processPt(next);
}
Base::BoundBox3d bb;
private:
void processPts(const std::deque<Base::Vector3d> &pts) {
for (std::deque<Base::Vector3d>::const_iterator it=pts.begin(); pts.end() != it; ++it) {
processPt(*it);
}
}
void processPt(const Base::Vector3d &pt) {
bb.MaxX = std::max(bb.MaxX, pt.x);
bb.MinX = std::min(bb.MinX, pt.x);
bb.MaxY = std::max(bb.MaxY, pt.y);
bb.MinY = std::min(bb.MinY, pt.y);
bb.MaxZ = std::max(bb.MaxZ, pt.z);
bb.MinZ = std::min(bb.MinZ, pt.z);
}
};
Base::BoundBox3d Toolpath::getBoundBox() const
{
BoundBoxSegmentVisitor visitor;
PathSegmentWalker walker(*this);
walker.walk(visitor, Vector3d(0, 0, 0));
return visitor.bb;
}
static void bulkAddCommand(const std::string &gcodestr, std::vector<Command*> &commands, bool &inches)
{
Command *cmd = new Command();
cmd->setFromGCode(gcodestr);
if ("G20" == cmd->Name) {
inches = true;
delete cmd;
} else if ("G21" == cmd->Name) {
inches = false;
delete cmd;
} else {
if (inches) {
cmd->scaleBy(25.4);
}
commands.push_back(cmd);
}
}
void Toolpath::setFromGCode(const std::string instr)
{
clear();
// remove comments
//boost::regex e("\\(.*?\\)");
//std::string str = boost::regex_replace(instr, e, "");
std::string str(instr);
// split input string by () or G or M commands
std::string mode = "command";
std::size_t found = str.find_first_of("(gGmM");
int last = -1;
bool inches = false;
while (found != std::string::npos)
{
if (str[found] == '(') {
// start of comment
if ( (last > -1) && (mode == "command") ) {
// before opening a comment, add the last found command
std::string gcodestr = str.substr(last, found-last);
bulkAddCommand(gcodestr, vpcCommands, inches);
}
mode = "comment";
last = found;
found = str.find_first_of(')', found+1);
} else if (str[found] == ')') {
// end of comment
std::string gcodestr = str.substr(last, found-last+1);
bulkAddCommand(gcodestr, vpcCommands, inches);
last = -1;
found = str.find_first_of("(gGmM", found+1);
mode = "command";
} else if (mode == "command") {
// command
if (last > -1) {
std::string gcodestr = str.substr(last, found-last);
bulkAddCommand(gcodestr, vpcCommands, inches);
}
last = found;
found = str.find_first_of("(gGmM", found+1);
}
}
// add the last command found, if any
if (last > -1) {
if (mode == "command") {
std::string gcodestr = str.substr(last,std::string::npos);
bulkAddCommand(gcodestr, vpcCommands, inches);
}
}
recalculate();
}
std::string Toolpath::toGCode(void) const
{
std::string result;
for (std::vector<Command*>::const_iterator it=vpcCommands.begin();it!=vpcCommands.end();++it) {
result += (*it)->toGCode();
result += "\n";
}
return result;
}
void Toolpath::recalculate(void) // recalculates the path cache
{
if(vpcCommands.size()==0)
return;
// TODO recalculate the KDL stuff. At the moment, this is unused.
#if 0
// delete the old and create a new one
if(pcPath)
delete (pcPath);
pcPath = new KDL::Path_Composite();
KDL::Path *tempPath;
KDL::Frame Last;
try {
// handle the first waypoint differently
bool first=true;
for(std::vector<Command*>::const_iterator it = vpcCommands.begin();it!=vpcCommands.end();++it) {
if(first){
Last = toFrame((*it)->getPlacement());
first = false;
}else{
Base::Placement p = (*it)->getPlacement();
KDL::Frame Next = toFrame(p);
std::string name = (*it)->Name;
Vector3d zaxis(0,0,1);
if ( (name == "G0") || (name == "G1") || (name == "G01") ) {
// line segment
tempPath = new KDL::Path_Line(Last, Next, new KDL::RotationalInterpolation_SingleAxis(), 1.0, true);
pcPath->Add(tempPath);
Last = Next;
} else if ( (name == "G2") || (name == "G02") ) {
// clockwise arc
Vector3d fcenter = (*it)->getCenter();
KDL::Vector center(fcenter.x,fcenter.y,fcenter.z);
Vector3d fnorm;
p.getRotation().multVec(zaxis,fnorm);
KDL::Vector norm(fnorm.x,fnorm.y,fnorm.z);
Vector3d fstart = toPlacement(Last).getPosition();
Vector3d fend = toPlacement(Last).getPosition();
Rotation frot(fstart-fcenter,fend-fcenter);
double q0,q1,q2,q3;
frot.getValue(q0,q1,q2,q3);
KDL::Rotation rot;
rot.Quaternion(q0,q1,q2,q3);
tempPath = new KDL::Path_Circle(Last, center, norm, rot, 0.0, new KDL::RotationalInterpolation_SingleAxis(), 1.0, true);
pcPath->Add(tempPath);
Last = Next;
}
}
}
} catch (KDL::Error &e) {
throw Base::RuntimeError(e.Description());
}
#endif
}
// reimplemented from base class
unsigned int Toolpath::getMemSize (void) const
{
return toGCode().size();
}
void Toolpath::setCenter(const Base::Vector3d &c)
{
center = c;
recalculate();
}
static void saveCenter(Writer &writer, const Base::Vector3d &center)
{
writer.Stream() << writer.ind() << "<Center x=\"" << center.x << "\" y=\"" << center.y << "\" z=\"" << center.z << "\"/>" << std::endl;
}
void Toolpath::Save (Writer &writer) const
{
if (writer.isForceXML()) {
writer.Stream() << writer.ind() << "<Path count=\"" << getSize() << "\" version=\"" << SchemaVersion << "\">" << std::endl;
writer.incInd();
saveCenter(writer, center);
for(unsigned int i = 0; i < getSize(); i++) {
vpcCommands[i]->Save(writer);
}
writer.decInd();
} else {
writer.Stream() << writer.ind()
<< "<Path file=\"" << writer.addFile((writer.ObjectName+".nc").c_str(), this) << "\" version=\"" << SchemaVersion << "\">" << std::endl;
writer.incInd();
saveCenter(writer, center);
writer.decInd();
}
writer.Stream() << writer.ind() << "</Path>" << std::endl;
}
void Toolpath::SaveDocFile (Base::Writer &writer) const
{
if (toGCode().empty())
return;
writer.Stream() << toGCode();
}
void Toolpath::Restore(XMLReader &reader)
{
reader.readElement("Path");
std::string file (reader.getAttribute("file") );
if (!file.empty()) {
// initiate a file read
reader.addFile(file.c_str(),this);
}
}
void Toolpath::RestoreDocFile(Base::Reader &reader)
{
std::string gcode;
std::string line;
while (reader >> line) {
gcode += line;
gcode += " ";
}
setFromGCode(gcode);
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/regex.hpp>
#endif
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Stream.h>
#include <Base/Exception.h>
#include <Base/Console.h>
// KDL stuff - at the moment, not used
//#include "Mod/Robot/App/kdl_cp/path_line.hpp"
//#include "Mod/Robot/App/kdl_cp/path_circle.hpp"
//#include "Mod/Robot/App/kdl_cp/rotational_interpolation_sa.hpp"
//#include "Mod/Robot/App/kdl_cp/utilities/error.h"
#include "Path.h"
#include <Mod/Path/App/PathSegmentWalker.h>
using namespace Path;
using namespace Base;
TYPESYSTEM_SOURCE(Path::Toolpath , Base::Persistence)
Toolpath::Toolpath()
{
}
Toolpath::Toolpath(const Toolpath& otherPath)
: vpcCommands(otherPath.vpcCommands.size())
, center(otherPath.center)
{
*this = otherPath;
recalculate();
}
Toolpath::~Toolpath()
{
clear();
}
Toolpath &Toolpath::operator=(const Toolpath& otherPath)
{
if (this == &otherPath)
return *this;
clear();
vpcCommands.resize(otherPath.vpcCommands.size());
int i = 0;
for (std::vector<Command*>::const_iterator it=otherPath.vpcCommands.begin();it!=otherPath.vpcCommands.end();++it,i++) {
vpcCommands[i] = new Command(**it);
}
center = otherPath.center;
recalculate();
return *this;
}
void Toolpath::clear(void)
{
for(std::vector<Command*>::iterator it = vpcCommands.begin();it!=vpcCommands.end();++it)
delete ( *it );
vpcCommands.clear();
recalculate();
}
void Toolpath::addCommand(const Command &Cmd)
{
Command *tmp = new Command(Cmd);
vpcCommands.push_back(tmp);
recalculate();
}
void Toolpath::insertCommand(const Command &Cmd, int pos)
{
if (pos == -1) {
addCommand(Cmd);
} else if (pos <= static_cast<int>(vpcCommands.size())) {
Command *tmp = new Command(Cmd);
vpcCommands.insert(vpcCommands.begin()+pos,tmp);
} else {
throw Base::IndexError("Index not in range");
}
recalculate();
}
void Toolpath::deleteCommand(int pos)
{
if (pos == -1) {
//delete(*vpcCommands.rbegin()); // causes crash
vpcCommands.pop_back();
} else if (pos <= static_cast<int>(vpcCommands.size())) {
vpcCommands.erase (vpcCommands.begin()+pos);
} else {
throw Base::IndexError("Index not in range");
}
recalculate();
}
double Toolpath::getLength()
{
if(vpcCommands.size()==0)
return 0;
double l = 0;
Vector3d last(0,0,0);
Vector3d next;
for(std::vector<Command*>::const_iterator it = vpcCommands.begin();it!=vpcCommands.end();++it) {
std::string name = (*it)->Name;
next = (*it)->getPlacement(last).getPosition();
if ( (name == "G0") || (name == "G00") || (name == "G1") || (name == "G01") ) {
// straight line
l += (next - last).Length();
last = next;
} else if ( (name == "G2") || (name == "G02") || (name == "G3") || (name == "G03") ) {
// arc
Vector3d center = (*it)->getCenter();
double radius = (last - center).Length();
double angle = (next - center).GetAngle(last - center);
l += angle * radius;
last = next;
}
}
return l;
}
double Toolpath::getCycleTime(double hFeed, double vFeed, double hRapid, double vRapid)
{
// check the feedrates are set
if ((hFeed == 0) || (vFeed == 0)){
Base::Console().Warning("Feed Rate Error: Check Tool Controllers have Feed Rates");
return 0;
}
if (hRapid == 0){
hRapid = hFeed;
}
if (vRapid == 0){
vRapid = vFeed;
}
if(vpcCommands.size()==0)
return 0;
double l = 0;
double time = 0;
bool verticalMove = false;
Vector3d last(0,0,0);
Vector3d next;
for(std::vector<Command*>::const_iterator it = vpcCommands.begin();it!=vpcCommands.end();++it) {
std::string name = (*it)->Name;
float feedrate = (*it)->getParam("F");
l = 0;
verticalMove = false;
feedrate = hFeed;
next = (*it)->getPlacement(last).getPosition();
if (last.z != next.z){
verticalMove = true;
feedrate = vFeed;
}
if ((name == "G0") || (name == "G00")){
// Rapid Move
l += (next - last).Length();
feedrate = hRapid;
if(verticalMove){
feedrate = vRapid;
}
}else if ((name == "G1") || (name == "G01")) {
// Feed Move
l += (next - last).Length();
}else if ((name == "G2") || (name == "G02") || (name == "G3") || (name == "G03") ) {
// Arc Move
Vector3d center = (*it)->getCenter();
double radius = (last - center).Length();
double angle = (next - center).GetAngle(last - center);
l += angle * radius;
}
time += l / feedrate;
last = next;
}
return time;
}
class BoundBoxSegmentVisitor : public PathSegmentVisitor
{
public:
BoundBoxSegmentVisitor()
{ }
virtual void g0(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque<Base::Vector3d> &pts)
{
(void)id;
processPt(last);
processPts(pts);
processPt(next);
}
virtual void g1(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque<Base::Vector3d> &pts)
{
(void)id;
processPt(last);
processPts(pts);
processPt(next);
}
virtual void g23(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque<Base::Vector3d> &pts, const Base::Vector3d &center)
{
(void)id;
(void)center;
processPt(last);
processPts(pts);
processPt(next);
}
virtual void g8x(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque<Base::Vector3d> &pts,
const std::deque<Base::Vector3d> &p, const std::deque<Base::Vector3d> &q)
{
(void)id;
(void)q; // always within the bounds of p
processPt(last);
processPts(pts);
processPts(p);
processPt(next);
}
virtual void g38(int id, const Base::Vector3d &last, const Base::Vector3d &next)
{
(void)id;
processPt(last);
processPt(next);
}
Base::BoundBox3d bb;
private:
void processPts(const std::deque<Base::Vector3d> &pts) {
for (std::deque<Base::Vector3d>::const_iterator it=pts.begin(); pts.end() != it; ++it) {
processPt(*it);
}
}
void processPt(const Base::Vector3d &pt) {
bb.MaxX = std::max(bb.MaxX, pt.x);
bb.MinX = std::min(bb.MinX, pt.x);
bb.MaxY = std::max(bb.MaxY, pt.y);
bb.MinY = std::min(bb.MinY, pt.y);
bb.MaxZ = std::max(bb.MaxZ, pt.z);
bb.MinZ = std::min(bb.MinZ, pt.z);
}
};
Base::BoundBox3d Toolpath::getBoundBox() const
{
BoundBoxSegmentVisitor visitor;
PathSegmentWalker walker(*this);
walker.walk(visitor, Vector3d(0, 0, 0));
return visitor.bb;
}
static void bulkAddCommand(const std::string &gcodestr, std::vector<Command*> &commands, bool &inches)
{
Command *cmd = new Command();
cmd->setFromGCode(gcodestr);
if ("G20" == cmd->Name) {
inches = true;
delete cmd;
} else if ("G21" == cmd->Name) {
inches = false;
delete cmd;
} else {
if (inches) {
cmd->scaleBy(25.4);
}
commands.push_back(cmd);
}
}
void Toolpath::setFromGCode(const std::string instr)
{
clear();
// remove comments
//boost::regex e("\\(.*?\\)");
//std::string str = boost::regex_replace(instr, e, "");
std::string str(instr);
// split input string by () or G or M commands
std::string mode = "command";
std::size_t found = str.find_first_of("(gGmM");
int last = -1;
bool inches = false;
while (found != std::string::npos)
{
if (str[found] == '(') {
// start of comment
if ( (last > -1) && (mode == "command") ) {
// before opening a comment, add the last found command
std::string gcodestr = str.substr(last, found-last);
bulkAddCommand(gcodestr, vpcCommands, inches);
}
mode = "comment";
last = found;
found = str.find_first_of(')', found+1);
} else if (str[found] == ')') {
// end of comment
std::string gcodestr = str.substr(last, found-last+1);
bulkAddCommand(gcodestr, vpcCommands, inches);
last = -1;
found = str.find_first_of("(gGmM", found+1);
mode = "command";
} else if (mode == "command") {
// command
if (last > -1) {
std::string gcodestr = str.substr(last, found-last);
bulkAddCommand(gcodestr, vpcCommands, inches);
}
last = found;
found = str.find_first_of("(gGmM", found+1);
}
}
// add the last command found, if any
if (last > -1) {
if (mode == "command") {
std::string gcodestr = str.substr(last,std::string::npos);
bulkAddCommand(gcodestr, vpcCommands, inches);
}
}
recalculate();
}
std::string Toolpath::toGCode(void) const
{
std::string result;
for (std::vector<Command*>::const_iterator it=vpcCommands.begin();it!=vpcCommands.end();++it) {
result += (*it)->toGCode();
result += "\n";
}
return result;
}
void Toolpath::recalculate(void) // recalculates the path cache
{
if(vpcCommands.size()==0)
return;
// TODO recalculate the KDL stuff. At the moment, this is unused.
#if 0
// delete the old and create a new one
if(pcPath)
delete (pcPath);
pcPath = new KDL::Path_Composite();
KDL::Path *tempPath;
KDL::Frame Last;
try {
// handle the first waypoint differently
bool first=true;
for(std::vector<Command*>::const_iterator it = vpcCommands.begin();it!=vpcCommands.end();++it) {
if(first){
Last = toFrame((*it)->getPlacement());
first = false;
}else{
Base::Placement p = (*it)->getPlacement();
KDL::Frame Next = toFrame(p);
std::string name = (*it)->Name;
Vector3d zaxis(0,0,1);
if ( (name == "G0") || (name == "G1") || (name == "G01") ) {
// line segment
tempPath = new KDL::Path_Line(Last, Next, new KDL::RotationalInterpolation_SingleAxis(), 1.0, true);
pcPath->Add(tempPath);
Last = Next;
} else if ( (name == "G2") || (name == "G02") ) {
// clockwise arc
Vector3d fcenter = (*it)->getCenter();
KDL::Vector center(fcenter.x,fcenter.y,fcenter.z);
Vector3d fnorm;
p.getRotation().multVec(zaxis,fnorm);
KDL::Vector norm(fnorm.x,fnorm.y,fnorm.z);
Vector3d fstart = toPlacement(Last).getPosition();
Vector3d fend = toPlacement(Last).getPosition();
Rotation frot(fstart-fcenter,fend-fcenter);
double q0,q1,q2,q3;
frot.getValue(q0,q1,q2,q3);
KDL::Rotation rot;
rot.Quaternion(q0,q1,q2,q3);
tempPath = new KDL::Path_Circle(Last, center, norm, rot, 0.0, new KDL::RotationalInterpolation_SingleAxis(), 1.0, true);
pcPath->Add(tempPath);
Last = Next;
}
}
}
} catch (KDL::Error &e) {
throw Base::RuntimeError(e.Description());
}
#endif
}
// reimplemented from base class
unsigned int Toolpath::getMemSize (void) const
{
return toGCode().size();
}
void Toolpath::setCenter(const Base::Vector3d &c)
{
center = c;
recalculate();
}
static void saveCenter(Writer &writer, const Base::Vector3d &center)
{
writer.Stream() << writer.ind() << "<Center x=\"" << center.x << "\" y=\"" << center.y << "\" z=\"" << center.z << "\"/>" << std::endl;
}
void Toolpath::Save (Writer &writer) const
{
if (writer.isForceXML()) {
writer.Stream() << writer.ind() << "<Path count=\"" << getSize() << "\" version=\"" << SchemaVersion << "\">" << std::endl;
writer.incInd();
saveCenter(writer, center);
for(unsigned int i = 0; i < getSize(); i++) {
vpcCommands[i]->Save(writer);
}
writer.decInd();
} else {
writer.Stream() << writer.ind()
<< "<Path file=\"" << writer.addFile((writer.ObjectName+".nc").c_str(), this) << "\" version=\"" << SchemaVersion << "\">" << std::endl;
writer.incInd();
saveCenter(writer, center);
writer.decInd();
}
writer.Stream() << writer.ind() << "</Path>" << std::endl;
}
void Toolpath::SaveDocFile (Base::Writer &writer) const
{
if (toGCode().empty())
return;
writer.Stream() << toGCode();
}
void Toolpath::Restore(XMLReader &reader)
{
reader.readElement("Path");
std::string file (reader.getAttribute("file") );
if (!file.empty()) {
// initiate a file read
reader.addFile(file.c_str(),this);
}
}
void Toolpath::RestoreDocFile(Base::Reader &reader)
{
std::string gcode;
std::string line;
while (reader >> line) {
gcode += line;
gcode += " ";
}
setFromGCode(gcode);
}

View File

@@ -1,105 +1,105 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_Path_H
#define PATH_Path_H
#include "Command.h"
//#include "Mod/Robot/App/kdl_cp/path_composite.hpp"
//#include "Mod/Robot/App/kdl_cp/frames_io.hpp"
#include <Base/BoundBox.h>
#include <Base/Persistence.h>
#include <Base/Vector3D.h>
namespace Path
{
/** The representation of a CNC Toolpath */
class PathExport Toolpath : public Base::Persistence
{
TYPESYSTEM_HEADER();
public:
Toolpath();
Toolpath(const Toolpath&);
~Toolpath();
Toolpath &operator=(const Toolpath&);
// from base class
virtual unsigned int getMemSize (void) const;
virtual void Save (Base::Writer &/*writer*/) const;
virtual void Restore(Base::XMLReader &/*reader*/);
void SaveDocFile (Base::Writer &writer) const;
void RestoreDocFile(Base::Reader &reader);
// interface
void clear(void); // clears the internal data
void addCommand(const Command &Cmd); // adds a command at the end
void insertCommand(const Command &Cmd, int); // inserts a command
void deleteCommand(int); // deletes a command
double getLength(void); // return the Length (mm) of the Path
double getCycleTime(double, double, double, double); // return the Cycle Time (s) of the Path
void recalculate(void); // recalculates the points
void setFromGCode(const std::string); // sets the path from the contents of the given GCode string
std::string toGCode(void) const; // gets a gcode string representation from the Path
Base::BoundBox3d getBoundBox(void) const;
// shortcut functions
unsigned int getSize(void) const { return vpcCommands.size(); }
const std::vector<Command*> &getCommands(void) const { return vpcCommands; }
const Command &getCommand(unsigned int pos) const { return *vpcCommands[pos]; }
// support for rotation
const Base::Vector3d& getCenter() const { return center; }
void setCenter(const Base::Vector3d &c);
static const int SchemaVersion = 2;
protected:
std::vector<Command*> vpcCommands;
Base::Vector3d center;
//KDL::Path_Composite *pcPath;
/*
inline KDL::Frame toFrame(const Base::Placement &To){
return KDL::Frame(KDL::Rotation::Quaternion(To.getRotation()[0],
To.getRotation()[1],
To.getRotation()[2],
To.getRotation()[3]),
KDL::Vector(To.getPosition()[0],
To.getPosition()[1],
To.getPosition()[2]));
}
inline Base::Placement toPlacement(const KDL::Frame &To){
double x,y,z,w;
To.M.GetQuaternion(x,y,z,w);
return Base::Placement(Base::Vector3d(To.p[0],To.p[1],To.p[2]),Base::Rotation(x,y,z,w));
} */
};
} //namespace Path
#endif // PATH_Path_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_Path_H
#define PATH_Path_H
#include "Command.h"
//#include "Mod/Robot/App/kdl_cp/path_composite.hpp"
//#include "Mod/Robot/App/kdl_cp/frames_io.hpp"
#include <Base/BoundBox.h>
#include <Base/Persistence.h>
#include <Base/Vector3D.h>
namespace Path
{
/** The representation of a CNC Toolpath */
class PathExport Toolpath : public Base::Persistence
{
TYPESYSTEM_HEADER();
public:
Toolpath();
Toolpath(const Toolpath&);
~Toolpath();
Toolpath &operator=(const Toolpath&);
// from base class
virtual unsigned int getMemSize (void) const;
virtual void Save (Base::Writer &/*writer*/) const;
virtual void Restore(Base::XMLReader &/*reader*/);
void SaveDocFile (Base::Writer &writer) const;
void RestoreDocFile(Base::Reader &reader);
// interface
void clear(void); // clears the internal data
void addCommand(const Command &Cmd); // adds a command at the end
void insertCommand(const Command &Cmd, int); // inserts a command
void deleteCommand(int); // deletes a command
double getLength(void); // return the Length (mm) of the Path
double getCycleTime(double, double, double, double); // return the Cycle Time (s) of the Path
void recalculate(void); // recalculates the points
void setFromGCode(const std::string); // sets the path from the contents of the given GCode string
std::string toGCode(void) const; // gets a gcode string representation from the Path
Base::BoundBox3d getBoundBox(void) const;
// shortcut functions
unsigned int getSize(void) const { return vpcCommands.size(); }
const std::vector<Command*> &getCommands(void) const { return vpcCommands; }
const Command &getCommand(unsigned int pos) const { return *vpcCommands[pos]; }
// support for rotation
const Base::Vector3d& getCenter() const { return center; }
void setCenter(const Base::Vector3d &c);
static const int SchemaVersion = 2;
protected:
std::vector<Command*> vpcCommands;
Base::Vector3d center;
//KDL::Path_Composite *pcPath;
/*
inline KDL::Frame toFrame(const Base::Placement &To){
return KDL::Frame(KDL::Rotation::Quaternion(To.getRotation()[0],
To.getRotation()[1],
To.getRotation()[2],
To.getRotation()[3]),
KDL::Vector(To.getPosition()[0],
To.getPosition()[1],
To.getPosition()[2]));
}
inline Base::Placement toPlacement(const KDL::Frame &To){
double x,y,z,w;
To.M.GetQuaternion(x,y,z,w);
return Base::Placement(Base::Vector3d(To.p[0],To.p[1],To.p[2]),Base::Rotation(x,y,z,w));
} */
};
} //namespace Path
#endif // PATH_Path_H

View File

@@ -1,91 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="PersistencePy"
Name="PathPy"
Twin="Toolpath"
TwinPointer="Toolpath"
Include="Mod/Path/App/Path.h"
Namespace="Path"
FatherInclude="Base/PersistencePy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>Path([commands]): Represents a basic Gcode path
commands (optional) is a list of Path commands</UserDocu>
</Documentation>
<Attribute Name="Length" ReadOnly="true">
<Documentation>
<UserDocu>the total length of this path in mm</UserDocu>
</Documentation>
<Parameter Name="Length" Type="Float"/>
</Attribute>
<Attribute Name="Size" ReadOnly="true">
<Documentation>
<UserDocu>the number of commands in this path</UserDocu>
</Documentation>
<Parameter Name="Size" Type="Long"/>
</Attribute>
<Attribute Name="Commands" ReadOnly="false">
<Documentation>
<UserDocu>the list of commands of this path</UserDocu>
</Documentation>
<Parameter Name="Commands" Type="List"/>
</Attribute>
<Attribute Name="Center" ReadOnly="false">
<Documentation>
<UserDocu>the center position for all rotational parameters</UserDocu>
</Documentation>
<Parameter Name="Center" Type="Object"/>
</Attribute>
<Attribute Name="BoundBox" ReadOnly="true">
<Documentation>
<UserDocu>the extent of this path</UserDocu>
</Documentation>
<Parameter Name="BoundBox" Type="Object"/>
</Attribute>
<Methode Name="addCommands">
<Documentation>
<UserDocu>adds a command or a list of commands at the end of the path</UserDocu>
</Documentation>
</Methode>
<Methode Name="insertCommand">
<Documentation>
<UserDocu>insertCommand(Command,[int]):
adds a command at the given position or at the end of the path</UserDocu>
</Documentation>
</Methode>
<Methode Name="deleteCommand">
<Documentation>
<UserDocu>deleteCommand([int]):
deletes the command found at the given position or from the end of the path</UserDocu>
</Documentation>
</Methode>
<Methode Name="setFromGCode">
<Documentation>
<UserDocu>sets the contents of the path from a gcode string</UserDocu>
</Documentation>
</Methode>
<Methode Name="toGCode" Const="true">
<Documentation>
<UserDocu>returns a gcode string representing the path</UserDocu>
</Documentation>
</Methode>
<Methode Name="copy" Const="true">
<Documentation>
<UserDocu>returns a copy of this path</UserDocu>
</Documentation>
</Methode>
<Methode Name="getCycleTime" Const="true">
<Documentation>
<UserDocu>return the cycle time estimation for this path in s</UserDocu>
</Documentation>
</Methode>
<!--<ClassDeclarations>
bool touched;
</ClassDeclarations>-->
</PythonExport>
</GenerateModel>
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="PersistencePy"
Name="PathPy"
Twin="Toolpath"
TwinPointer="Toolpath"
Include="Mod/Path/App/Path.h"
Namespace="Path"
FatherInclude="Base/PersistencePy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>Path([commands]): Represents a basic Gcode path
commands (optional) is a list of Path commands</UserDocu>
</Documentation>
<Attribute Name="Length" ReadOnly="true">
<Documentation>
<UserDocu>the total length of this path in mm</UserDocu>
</Documentation>
<Parameter Name="Length" Type="Float"/>
</Attribute>
<Attribute Name="Size" ReadOnly="true">
<Documentation>
<UserDocu>the number of commands in this path</UserDocu>
</Documentation>
<Parameter Name="Size" Type="Long"/>
</Attribute>
<Attribute Name="Commands" ReadOnly="false">
<Documentation>
<UserDocu>the list of commands of this path</UserDocu>
</Documentation>
<Parameter Name="Commands" Type="List"/>
</Attribute>
<Attribute Name="Center" ReadOnly="false">
<Documentation>
<UserDocu>the center position for all rotational parameters</UserDocu>
</Documentation>
<Parameter Name="Center" Type="Object"/>
</Attribute>
<Attribute Name="BoundBox" ReadOnly="true">
<Documentation>
<UserDocu>the extent of this path</UserDocu>
</Documentation>
<Parameter Name="BoundBox" Type="Object"/>
</Attribute>
<Methode Name="addCommands">
<Documentation>
<UserDocu>adds a command or a list of commands at the end of the path</UserDocu>
</Documentation>
</Methode>
<Methode Name="insertCommand">
<Documentation>
<UserDocu>insertCommand(Command,[int]):
adds a command at the given position or at the end of the path</UserDocu>
</Documentation>
</Methode>
<Methode Name="deleteCommand">
<Documentation>
<UserDocu>deleteCommand([int]):
deletes the command found at the given position or from the end of the path</UserDocu>
</Documentation>
</Methode>
<Methode Name="setFromGCode">
<Documentation>
<UserDocu>sets the contents of the path from a gcode string</UserDocu>
</Documentation>
</Methode>
<Methode Name="toGCode" Const="true">
<Documentation>
<UserDocu>returns a gcode string representing the path</UserDocu>
</Documentation>
</Methode>
<Methode Name="copy" Const="true">
<Documentation>
<UserDocu>returns a copy of this path</UserDocu>
</Documentation>
</Methode>
<Methode Name="getCycleTime" Const="true">
<Documentation>
<UserDocu>return the cycle time estimation for this path in s</UserDocu>
</Documentation>
</Methode>
<!--<ClassDeclarations>
bool touched;
</ClassDeclarations>-->
</PythonExport>
</GenerateModel>

View File

@@ -1,240 +1,240 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "Mod/Path/App/Path.h"
// inclusion of the generated files (generated out of PathPy.xml)
#include "PathPy.h"
#include "PathPy.cpp"
#include "Base/BoundBoxPy.h"
#include "Base/GeometryPyCXX.h"
#include "CommandPy.h"
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string PathPy::representation(void) const
{
std::stringstream str;
str.precision(5);
str << "Path [ ";
str << "size:" << getToolpathPtr()->getSize() << " ";
str << "length:" << getToolpathPtr()->getLength();
str << " ]";
return str.str();
}
PyObject *PathPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
// create a new instance of PathPy and the Twin object
return new PathPy(new Toolpath);
}
// constructor method
int PathPy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
PyObject *pcObj=0;
char *gcode;
if (PyArg_ParseTuple(args, "|O!", &(PyList_Type), &pcObj)) {
if (pcObj) {
Py::List list(pcObj);
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::CommandPy::Type))) {
Path::Command &cmd = *static_cast<Path::CommandPy*>((*it).ptr())->getCommandPtr();
getToolpathPtr()->addCommand(cmd);
} else {
PyErr_SetString(PyExc_TypeError, "The list must contain only Path Commands");
return -1;
}
}
}
return 0;
}
PyErr_Clear(); // set by PyArg_ParseTuple()
if (PyArg_ParseTuple(args, "|s", &gcode)) {
getToolpathPtr()->setFromGCode(gcode);
return 0;
}
PyErr_SetString(PyExc_TypeError, "Argument must be a list of commands or a gcode string");
return -1;
}
// Commands get/set
Py::List PathPy::getCommands(void) const
{
Py::List list;
for(unsigned int i = 0; i < getToolpathPtr()->getSize(); i++)
list.append(Py::asObject(new Path::CommandPy(new Path::Command(getToolpathPtr()->getCommand(i)))));
return list;
}
void PathPy::setCommands(Py::List list)
{
getToolpathPtr()->clear();
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::CommandPy::Type))) {
Path::Command &cmd = *static_cast<Path::CommandPy*>((*it).ptr())->getCommandPtr();
getToolpathPtr()->addCommand(cmd);
} else {
throw Py::TypeError("The list can only contain Path Commands");
}
}
}
Py::Object PathPy::getCenter(void) const
{
return Py::Vector(getToolpathPtr()->getCenter());
}
void PathPy::setCenter(Py::Object obj)
{
getToolpathPtr()->setCenter(Py::Vector(obj).toVector());
}
// read-only attributes
Py::Float PathPy::getLength(void) const
{
return Py::Float(getToolpathPtr()->getLength());
}
Py::Long PathPy::getSize(void) const
{
return Py::Long((long)getToolpathPtr()->getSize());
}
Py::Object PathPy::getBoundBox(void) const
{
return Py::BoundingBox(getToolpathPtr()->getBoundBox());
}
// specific methods
PyObject* PathPy::copy(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* PathPy::addCommands(PyObject * args)
{
PyObject* o;
if (PyArg_ParseTuple(args, "O!", &(Path::CommandPy::Type), &o)) {
Path::Command &cmd = *static_cast<Path::CommandPy*>(o)->getCommandPtr();
getToolpathPtr()->addCommand(cmd);
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
//Py_Return;
}
PyErr_Clear();
if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &o)) {
Py::List list(o);
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::CommandPy::Type))) {
Path::Command &cmd = *static_cast<Path::CommandPy*>((*it).ptr())->getCommandPtr();
getToolpathPtr()->addCommand(cmd);
}
}
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - command or list of commands expected");
}
PyObject* PathPy::insertCommand(PyObject * args)
{
PyObject* o;
int pos = -1;
if (PyArg_ParseTuple(args, "O!|i", &(Path::CommandPy::Type), &o, &pos)) {
Path::Command &cmd = *static_cast<Path::CommandPy*>(o)->getCommandPtr();
getToolpathPtr()->insertCommand(cmd,pos);
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected command and optional integer");
}
PyObject* PathPy::deleteCommand(PyObject * args)
{
int pos = -1;
if (PyArg_ParseTuple(args, "|i", &pos)) {
getToolpathPtr()->deleteCommand(pos);
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected an integer (optional)");
}
PyObject* PathPy::getCycleTime(PyObject * args)
{
double hFeed, vFeed, hRapid, vRapid;
if (PyArg_ParseTuple(args, "dddd", &hFeed, &vFeed, &hRapid, &vRapid)){
return PyFloat_FromDouble(getToolpathPtr()->getCycleTime(hFeed, vFeed, hRapid, vRapid));
}
return 0;
}
// GCode methods
PyObject* PathPy::toGCode(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
std::string result = getToolpathPtr()->toGCode();
#if PY_MAJOR_VERSION >= 3
return PyUnicode_FromString(result.c_str());
#else
return PyString_FromString(result.c_str());
#endif
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* PathPy::setFromGCode(PyObject * args)
{
char *pstr=0;
if (PyArg_ParseTuple(args, "s", &pstr)) {
std::string gcode(pstr);
getToolpathPtr()->setFromGCode(gcode);
Py_INCREF(Py_None);
return Py_None;
}
throw Py::TypeError("Argument must be a string");
}
// custom attributes get/set
PyObject *PathPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int PathPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "Mod/Path/App/Path.h"
// inclusion of the generated files (generated out of PathPy.xml)
#include "PathPy.h"
#include "PathPy.cpp"
#include "Base/BoundBoxPy.h"
#include "Base/GeometryPyCXX.h"
#include "CommandPy.h"
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string PathPy::representation(void) const
{
std::stringstream str;
str.precision(5);
str << "Path [ ";
str << "size:" << getToolpathPtr()->getSize() << " ";
str << "length:" << getToolpathPtr()->getLength();
str << " ]";
return str.str();
}
PyObject *PathPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
// create a new instance of PathPy and the Twin object
return new PathPy(new Toolpath);
}
// constructor method
int PathPy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
PyObject *pcObj=0;
char *gcode;
if (PyArg_ParseTuple(args, "|O!", &(PyList_Type), &pcObj)) {
if (pcObj) {
Py::List list(pcObj);
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::CommandPy::Type))) {
Path::Command &cmd = *static_cast<Path::CommandPy*>((*it).ptr())->getCommandPtr();
getToolpathPtr()->addCommand(cmd);
} else {
PyErr_SetString(PyExc_TypeError, "The list must contain only Path Commands");
return -1;
}
}
}
return 0;
}
PyErr_Clear(); // set by PyArg_ParseTuple()
if (PyArg_ParseTuple(args, "|s", &gcode)) {
getToolpathPtr()->setFromGCode(gcode);
return 0;
}
PyErr_SetString(PyExc_TypeError, "Argument must be a list of commands or a gcode string");
return -1;
}
// Commands get/set
Py::List PathPy::getCommands(void) const
{
Py::List list;
for(unsigned int i = 0; i < getToolpathPtr()->getSize(); i++)
list.append(Py::asObject(new Path::CommandPy(new Path::Command(getToolpathPtr()->getCommand(i)))));
return list;
}
void PathPy::setCommands(Py::List list)
{
getToolpathPtr()->clear();
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::CommandPy::Type))) {
Path::Command &cmd = *static_cast<Path::CommandPy*>((*it).ptr())->getCommandPtr();
getToolpathPtr()->addCommand(cmd);
} else {
throw Py::TypeError("The list can only contain Path Commands");
}
}
}
Py::Object PathPy::getCenter(void) const
{
return Py::Vector(getToolpathPtr()->getCenter());
}
void PathPy::setCenter(Py::Object obj)
{
getToolpathPtr()->setCenter(Py::Vector(obj).toVector());
}
// read-only attributes
Py::Float PathPy::getLength(void) const
{
return Py::Float(getToolpathPtr()->getLength());
}
Py::Long PathPy::getSize(void) const
{
return Py::Long((long)getToolpathPtr()->getSize());
}
Py::Object PathPy::getBoundBox(void) const
{
return Py::BoundingBox(getToolpathPtr()->getBoundBox());
}
// specific methods
PyObject* PathPy::copy(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* PathPy::addCommands(PyObject * args)
{
PyObject* o;
if (PyArg_ParseTuple(args, "O!", &(Path::CommandPy::Type), &o)) {
Path::Command &cmd = *static_cast<Path::CommandPy*>(o)->getCommandPtr();
getToolpathPtr()->addCommand(cmd);
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
//Py_Return;
}
PyErr_Clear();
if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &o)) {
Py::List list(o);
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::CommandPy::Type))) {
Path::Command &cmd = *static_cast<Path::CommandPy*>((*it).ptr())->getCommandPtr();
getToolpathPtr()->addCommand(cmd);
}
}
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - command or list of commands expected");
}
PyObject* PathPy::insertCommand(PyObject * args)
{
PyObject* o;
int pos = -1;
if (PyArg_ParseTuple(args, "O!|i", &(Path::CommandPy::Type), &o, &pos)) {
Path::Command &cmd = *static_cast<Path::CommandPy*>(o)->getCommandPtr();
getToolpathPtr()->insertCommand(cmd,pos);
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected command and optional integer");
}
PyObject* PathPy::deleteCommand(PyObject * args)
{
int pos = -1;
if (PyArg_ParseTuple(args, "|i", &pos)) {
getToolpathPtr()->deleteCommand(pos);
return new PathPy(new Path::Toolpath(*getToolpathPtr()));
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected an integer (optional)");
}
PyObject* PathPy::getCycleTime(PyObject * args)
{
double hFeed, vFeed, hRapid, vRapid;
if (PyArg_ParseTuple(args, "dddd", &hFeed, &vFeed, &hRapid, &vRapid)){
return PyFloat_FromDouble(getToolpathPtr()->getCycleTime(hFeed, vFeed, hRapid, vRapid));
}
return 0;
}
// GCode methods
PyObject* PathPy::toGCode(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
std::string result = getToolpathPtr()->toGCode();
#if PY_MAJOR_VERSION >= 3
return PyUnicode_FromString(result.c_str());
#else
return PyString_FromString(result.c_str());
#endif
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* PathPy::setFromGCode(PyObject * args)
{
char *pstr=0;
if (PyArg_ParseTuple(args, "s", &pstr)) {
std::string gcode(pstr);
getToolpathPtr()->setFromGCode(gcode);
Py_INCREF(Py_None);
return Py_None;
}
throw Py::TypeError("Argument must be a string");
}
// custom attributes get/set
PyObject *PathPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int PathPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}

View File

@@ -1,24 +1,24 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"

View File

@@ -1,133 +1,133 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_PRECOMPILED_H
#define PATH_PRECOMPILED_H
#include <FCConfig.h>
// Exporting of App classes
#ifdef FC_OS_WIN32
# define PathExport __declspec(dllexport)
//# define RobotExport __declspec(dllexport) uncomment this to use KDL
# define PartExport __declspec(dllimport)
# define BaseExport __declspec(dllimport)
#else // for Linux
# define PathExport
//# define RobotExport uncomment this to use KDL
# define PartExport
# define BaseExport
#endif
#ifdef _PreComp_
// standard
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <assert.h>
#include <string>
#include <map>
#include <vector>
#include <set>
#include <bitset>
#include <cctype>
#include <cinttypes>
#include <iomanip>
// Python
#include <Python.h>
// Boost
#include <boost/version.hpp>
#include <boost/config.hpp>
#if defined(BOOST_MSVC) && (BOOST_VERSION == 105500)
// for fixing issue https://svn.boost.org/trac/boost/ticket/9332
# include "boost_fix/intrusive/detail/memory_util.hpp"
# include "boost_fix/container/detail/memory_util.hpp"
#endif
#include <boost/geometry.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
//OCC
#include <BRepLib.hxx>
#include <BRep_Builder.hxx>
#include <BRep_Tool.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <BRepBuilderAPI_FindPlane.hxx>
#include <BRepLib_FindSurface.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepTools.hxx>
#include <BRepTools_WireExplorer.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopExp.hxx>
#include <TopExp_Explorer.hxx>
#include <GeomAbs_JoinType.hxx>
#include <Geom_Circle.hxx>
#include <Geom_Ellipse.hxx>
#include <Geom_Line.hxx>
#include <Geom_Plane.hxx>
#include <Standard_Failure.hxx>
#include <gp_Circ.hxx>
#include <gp_GTrsf.hxx>
#include <Standard_Version.hxx>
#include <GCPnts_QuasiUniformDeflection.hxx>
#include <GCPnts_UniformDeflection.hxx>
#include <GCPnts_UniformAbscissa.hxx>
#include <BRepBndLib.hxx>
#include <BRepLib_MakeFace.hxx>
#include <Bnd_Box.hxx>
#include <BRepBuilderAPI_Copy.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <BRepExtrema_DistShapeShape.hxx>
#include <HLRBRep.hxx>
#include <HLRBRep_Algo.hxx>
#include <HLRBRep_HLRToShape.hxx>
#include <HLRAlgo_Projector.hxx>
#include <ShapeFix_ShapeTolerance.hxx>
#include <ShapeExtend_WireData.hxx>
#include <ShapeFix_Wire.hxx>
#include <ShapeAnalysis_FreeBounds.hxx>
#include <TopTools_HSequenceOfShape.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Edge.hxx>
#endif // _PreComp_
#endif
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_PRECOMPILED_H
#define PATH_PRECOMPILED_H
#include <FCConfig.h>
// Exporting of App classes
#ifdef FC_OS_WIN32
# define PathExport __declspec(dllexport)
//# define RobotExport __declspec(dllexport) uncomment this to use KDL
# define PartExport __declspec(dllimport)
# define BaseExport __declspec(dllimport)
#else // for Linux
# define PathExport
//# define RobotExport uncomment this to use KDL
# define PartExport
# define BaseExport
#endif
#ifdef _PreComp_
// standard
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <assert.h>
#include <string>
#include <map>
#include <vector>
#include <set>
#include <bitset>
#include <cctype>
#include <cinttypes>
#include <iomanip>
// Python
#include <Python.h>
// Boost
#include <boost/version.hpp>
#include <boost/config.hpp>
#if defined(BOOST_MSVC) && (BOOST_VERSION == 105500)
// for fixing issue https://svn.boost.org/trac/boost/ticket/9332
# include "boost_fix/intrusive/detail/memory_util.hpp"
# include "boost_fix/container/detail/memory_util.hpp"
#endif
#include <boost/geometry.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
//OCC
#include <BRepLib.hxx>
#include <BRep_Builder.hxx>
#include <BRep_Tool.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <BRepBuilderAPI_FindPlane.hxx>
#include <BRepLib_FindSurface.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepTools.hxx>
#include <BRepTools_WireExplorer.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopExp.hxx>
#include <TopExp_Explorer.hxx>
#include <GeomAbs_JoinType.hxx>
#include <Geom_Circle.hxx>
#include <Geom_Ellipse.hxx>
#include <Geom_Line.hxx>
#include <Geom_Plane.hxx>
#include <Standard_Failure.hxx>
#include <gp_Circ.hxx>
#include <gp_GTrsf.hxx>
#include <Standard_Version.hxx>
#include <GCPnts_QuasiUniformDeflection.hxx>
#include <GCPnts_UniformDeflection.hxx>
#include <GCPnts_UniformAbscissa.hxx>
#include <BRepBndLib.hxx>
#include <BRepLib_MakeFace.hxx>
#include <Bnd_Box.hxx>
#include <BRepBuilderAPI_Copy.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <BRepExtrema_DistShapeShape.hxx>
#include <HLRBRep.hxx>
#include <HLRBRep_Algo.hxx>
#include <HLRBRep_HLRToShape.hxx>
#include <HLRAlgo_Projector.hxx>
#include <ShapeFix_ShapeTolerance.hxx>
#include <ShapeExtend_WireData.hxx>
#include <ShapeFix_Wire.hxx>
#include <ShapeAnalysis_FreeBounds.hxx>
#include <TopTools_HSequenceOfShape.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Edge.hxx>
#endif // _PreComp_
#endif

View File

@@ -1,161 +1,161 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#endif
#include <App/DocumentObject.h>
#include <App/PropertyContainer.h>
#include <Base/Console.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/Stream.h>
#include "PropertyPath.h"
#include "PathPy.h"
using namespace Path;
TYPESYSTEM_SOURCE(Path::PropertyPath, App::Property)
PropertyPath::PropertyPath()
{
}
PropertyPath::~PropertyPath()
{
}
void PropertyPath::setValue(const Toolpath& pa)
{
aboutToSetValue();
_Path = pa;
hasSetValue();
}
const Toolpath &PropertyPath::getValue(void)const
{
return _Path;
}
PyObject *PropertyPath::getPyObject(void)
{
return new PathPy(new Toolpath(_Path));
}
void PropertyPath::setPyObject(PyObject *value)
{
if (PyObject_TypeCheck(value, &(PathPy::Type))) {
PathPy *pcObject = static_cast<PathPy*>(value);
setValue(*pcObject->getToolpathPtr());
}
else {
std::string error = std::string("type must be 'Path', not ");
error += value->ob_type->tp_name;
throw Base::TypeError(error);
}
}
App::Property *PropertyPath::Copy(void) const
{
PropertyPath *prop = new PropertyPath();
prop->_Path = this->_Path;
return prop;
}
void PropertyPath::Paste(const App::Property &from)
{
aboutToSetValue();
_Path = dynamic_cast<const PropertyPath&>(from)._Path;
hasSetValue();
}
unsigned int PropertyPath::getMemSize (void) const
{
return _Path.getMemSize();
}
void PropertyPath::Save (Base::Writer &writer) const
{
_Path.Save(writer);
}
void PropertyPath::Restore(Base::XMLReader &reader)
{
reader.readElement("Path");
std::string file (reader.getAttribute("file") );
if (!file.empty()) {
// initiate a file read
reader.addFile(file.c_str(),this);
}
if (reader.hasAttribute("version")) {
int version = reader.getAttributeAsInteger("version");
if (version >= Toolpath::SchemaVersion) {
reader.readElement("Center");
double x = reader.getAttributeAsFloat("x");
double y = reader.getAttributeAsFloat("y");
double z = reader.getAttributeAsFloat("z");
Base::Vector3d center(x, y, z);
_Path.setCenter(center);
}
}
}
void PropertyPath::SaveDocFile (Base::Writer &) const
{
// does nothing
}
void PropertyPath::RestoreDocFile(Base::Reader &reader)
{
App::PropertyContainer *container = getContainer();
App::DocumentObject *obj = 0;
if (container->isDerivedFrom(App::DocumentObject::getClassTypeId())) {
obj = static_cast<App::DocumentObject*>(container);
}
if (obj) {
obj->setStatus(App::ObjectStatus::Restore, true);
}
aboutToSetValue();
_Path.RestoreDocFile(reader);
hasSetValue();
if (obj) {
obj->setStatus(App::ObjectStatus::Restore, false);
}
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#endif
#include <App/DocumentObject.h>
#include <App/PropertyContainer.h>
#include <Base/Console.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/Stream.h>
#include "PropertyPath.h"
#include "PathPy.h"
using namespace Path;
TYPESYSTEM_SOURCE(Path::PropertyPath, App::Property)
PropertyPath::PropertyPath()
{
}
PropertyPath::~PropertyPath()
{
}
void PropertyPath::setValue(const Toolpath& pa)
{
aboutToSetValue();
_Path = pa;
hasSetValue();
}
const Toolpath &PropertyPath::getValue(void)const
{
return _Path;
}
PyObject *PropertyPath::getPyObject(void)
{
return new PathPy(new Toolpath(_Path));
}
void PropertyPath::setPyObject(PyObject *value)
{
if (PyObject_TypeCheck(value, &(PathPy::Type))) {
PathPy *pcObject = static_cast<PathPy*>(value);
setValue(*pcObject->getToolpathPtr());
}
else {
std::string error = std::string("type must be 'Path', not ");
error += value->ob_type->tp_name;
throw Base::TypeError(error);
}
}
App::Property *PropertyPath::Copy(void) const
{
PropertyPath *prop = new PropertyPath();
prop->_Path = this->_Path;
return prop;
}
void PropertyPath::Paste(const App::Property &from)
{
aboutToSetValue();
_Path = dynamic_cast<const PropertyPath&>(from)._Path;
hasSetValue();
}
unsigned int PropertyPath::getMemSize (void) const
{
return _Path.getMemSize();
}
void PropertyPath::Save (Base::Writer &writer) const
{
_Path.Save(writer);
}
void PropertyPath::Restore(Base::XMLReader &reader)
{
reader.readElement("Path");
std::string file (reader.getAttribute("file") );
if (!file.empty()) {
// initiate a file read
reader.addFile(file.c_str(),this);
}
if (reader.hasAttribute("version")) {
int version = reader.getAttributeAsInteger("version");
if (version >= Toolpath::SchemaVersion) {
reader.readElement("Center");
double x = reader.getAttributeAsFloat("x");
double y = reader.getAttributeAsFloat("y");
double z = reader.getAttributeAsFloat("z");
Base::Vector3d center(x, y, z);
_Path.setCenter(center);
}
}
}
void PropertyPath::SaveDocFile (Base::Writer &) const
{
// does nothing
}
void PropertyPath::RestoreDocFile(Base::Reader &reader)
{
App::PropertyContainer *container = getContainer();
App::DocumentObject *obj = 0;
if (container->isDerivedFrom(App::DocumentObject::getClassTypeId())) {
obj = static_cast<App::DocumentObject*>(container);
}
if (obj) {
obj->setStatus(App::ObjectStatus::Restore, true);
}
aboutToSetValue();
_Path.RestoreDocFile(reader);
hasSetValue();
if (obj) {
obj->setStatus(App::ObjectStatus::Restore, false);
}
}

View File

@@ -1,77 +1,77 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PROPERTYPATH_H
#define PROPERTYPATH_H
#include "Path.h"
#include <App/Property.h>
namespace Path
{
/** The path property class. */
class PathExport PropertyPath : public App::Property
{
TYPESYSTEM_HEADER();
public:
PropertyPath();
~PropertyPath();
/** @name Getter/setter */
//@{
/// set the part shape
void setValue(const Toolpath&);
/// get the part shape
const Toolpath &getValue(void) const;
//@}
/** @name Python interface */
//@{
PyObject* getPyObject(void);
void setPyObject(PyObject *value);
//@}
/** @name Save/restore */
//@{
void Save (Base::Writer &writer) const;
void Restore(Base::XMLReader &reader);
void SaveDocFile (Base::Writer &writer) const;
void RestoreDocFile(Base::Reader &reader);
App::Property *Copy(void) const;
void Paste(const App::Property &from);
unsigned int getMemSize (void) const;
//@}
private:
Toolpath _Path;
};
} //namespace Path
#endif // PROPERTYPATH_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PROPERTYPATH_H
#define PROPERTYPATH_H
#include "Path.h"
#include <App/Property.h>
namespace Path
{
/** The path property class. */
class PathExport PropertyPath : public App::Property
{
TYPESYSTEM_HEADER();
public:
PropertyPath();
~PropertyPath();
/** @name Getter/setter */
//@{
/// set the part shape
void setValue(const Toolpath&);
/// get the part shape
const Toolpath &getValue(void) const;
//@}
/** @name Python interface */
//@{
PyObject* getPyObject(void);
void setPyObject(PyObject *value);
//@}
/** @name Save/restore */
//@{
void Save (Base::Writer &writer) const;
void Restore(Base::XMLReader &reader);
void SaveDocFile (Base::Writer &writer) const;
void RestoreDocFile(Base::Reader &reader);
App::Property *Copy(void) const;
void Paste(const App::Property &from);
unsigned int getMemSize (void) const;
//@}
private:
Toolpath _Path;
};
} //namespace Path
#endif // PROPERTYPATH_H

View File

@@ -1,116 +1,116 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#endif
#include <Base/Console.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/Stream.h>
#include "PropertyTool.h"
#include "ToolPy.h"
using namespace Path;
TYPESYSTEM_SOURCE(Path::PropertyTool, App::Property)
PropertyTool::PropertyTool()
{
}
PropertyTool::~PropertyTool()
{
}
void PropertyTool::setValue(const Tool& tt)
{
aboutToSetValue();
_Tool = tt;
hasSetValue();
}
const Tool &PropertyTool::getValue(void)const
{
return _Tool;
}
PyObject *PropertyTool::getPyObject(void)
{
return new ToolPy(new Tool(_Tool));
}
void PropertyTool::setPyObject(PyObject *value)
{
if (PyObject_TypeCheck(value, &(ToolPy::Type))) {
ToolPy *pcObject = static_cast<ToolPy*>(value);
setValue(*pcObject->getToolPtr());
}
else {
std::string error = std::string("type must be 'Tool', not ");
error += value->ob_type->tp_name;
throw Base::TypeError(error);
}
}
App::Property *PropertyTool::Copy(void) const
{
PropertyTool *prop = new PropertyTool();
prop->_Tool = this->_Tool;
return prop;
}
void PropertyTool::Paste(const App::Property &from)
{
aboutToSetValue();
_Tool = dynamic_cast<const PropertyTool&>(from)._Tool;
hasSetValue();
}
unsigned int PropertyTool::getMemSize (void) const
{
return _Tool.getMemSize();
}
void PropertyTool::Save (Base::Writer &writer) const
{
_Tool.Save(writer);
}
void PropertyTool::Restore(Base::XMLReader &reader)
{
Path::Tool temp;
temp.Restore(reader);
setValue(temp);
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#endif
#include <Base/Console.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/Stream.h>
#include "PropertyTool.h"
#include "ToolPy.h"
using namespace Path;
TYPESYSTEM_SOURCE(Path::PropertyTool, App::Property)
PropertyTool::PropertyTool()
{
}
PropertyTool::~PropertyTool()
{
}
void PropertyTool::setValue(const Tool& tt)
{
aboutToSetValue();
_Tool = tt;
hasSetValue();
}
const Tool &PropertyTool::getValue(void)const
{
return _Tool;
}
PyObject *PropertyTool::getPyObject(void)
{
return new ToolPy(new Tool(_Tool));
}
void PropertyTool::setPyObject(PyObject *value)
{
if (PyObject_TypeCheck(value, &(ToolPy::Type))) {
ToolPy *pcObject = static_cast<ToolPy*>(value);
setValue(*pcObject->getToolPtr());
}
else {
std::string error = std::string("type must be 'Tool', not ");
error += value->ob_type->tp_name;
throw Base::TypeError(error);
}
}
App::Property *PropertyTool::Copy(void) const
{
PropertyTool *prop = new PropertyTool();
prop->_Tool = this->_Tool;
return prop;
}
void PropertyTool::Paste(const App::Property &from)
{
aboutToSetValue();
_Tool = dynamic_cast<const PropertyTool&>(from)._Tool;
hasSetValue();
}
unsigned int PropertyTool::getMemSize (void) const
{
return _Tool.getMemSize();
}
void PropertyTool::Save (Base::Writer &writer) const
{
_Tool.Save(writer);
}
void PropertyTool::Restore(Base::XMLReader &reader)
{
Path::Tool temp;
temp.Restore(reader);
setValue(temp);
}

View File

@@ -1,75 +1,75 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PROPERTYTOOL_H
#define PROPERTYTOOL_H
#include "Tool.h"
#include <App/Property.h>
namespace Path
{
/** The tool property class. */
class PathExport PropertyTool : public App::Property
{
TYPESYSTEM_HEADER();
public:
PropertyTool();
~PropertyTool();
/** @name Getter/setter */
//@{
/// set the part shape
void setValue(const Tool&);
/// get the part shape
const Tool &getValue(void) const;
//@}
/** @name Python interface */
//@{
PyObject* getPyObject(void);
void setPyObject(PyObject *value);
//@}
/** @name Save/restore */
//@{
void Save (Base::Writer &writer) const;
void Restore(Base::XMLReader &reader);
App::Property *Copy(void) const;
void Paste(const App::Property &from);
unsigned int getMemSize (void) const;
//@}
private:
Tool _Tool;
};
} //namespace Path
#endif // PROPERTYTOOL_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PROPERTYTOOL_H
#define PROPERTYTOOL_H
#include "Tool.h"
#include <App/Property.h>
namespace Path
{
/** The tool property class. */
class PathExport PropertyTool : public App::Property
{
TYPESYSTEM_HEADER();
public:
PropertyTool();
~PropertyTool();
/** @name Getter/setter */
//@{
/// set the part shape
void setValue(const Tool&);
/// get the part shape
const Tool &getValue(void) const;
//@}
/** @name Python interface */
//@{
PyObject* getPyObject(void);
void setPyObject(PyObject *value);
//@}
/** @name Save/restore */
//@{
void Save (Base::Writer &writer) const;
void Restore(Base::XMLReader &reader);
App::Property *Copy(void) const;
void Paste(const App::Property &from);
unsigned int getMemSize (void) const;
//@}
private:
Tool _Tool;
};
} //namespace Path
#endif // PROPERTYTOOL_H

View File

@@ -1,116 +1,116 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#endif
#include <Base/Console.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/Stream.h>
#include "PropertyTooltable.h"
#include "TooltablePy.h"
using namespace Path;
TYPESYSTEM_SOURCE(Path::PropertyTooltable, App::Property)
PropertyTooltable::PropertyTooltable()
{
}
PropertyTooltable::~PropertyTooltable()
{
}
void PropertyTooltable::setValue(const Tooltable& tt)
{
aboutToSetValue();
_Tooltable = tt;
hasSetValue();
}
const Tooltable &PropertyTooltable::getValue(void)const
{
return _Tooltable;
}
PyObject *PropertyTooltable::getPyObject(void)
{
return new TooltablePy(new Tooltable(_Tooltable));
}
void PropertyTooltable::setPyObject(PyObject *value)
{
if (PyObject_TypeCheck(value, &(TooltablePy::Type))) {
TooltablePy *pcObject = static_cast<TooltablePy*>(value);
setValue(*pcObject->getTooltablePtr());
}
else {
std::string error = std::string("type must be 'Tooltable', not ");
error += value->ob_type->tp_name;
throw Base::TypeError(error);
}
}
App::Property *PropertyTooltable::Copy(void) const
{
PropertyTooltable *prop = new PropertyTooltable();
prop->_Tooltable = this->_Tooltable;
return prop;
}
void PropertyTooltable::Paste(const App::Property &from)
{
aboutToSetValue();
_Tooltable = dynamic_cast<const PropertyTooltable&>(from)._Tooltable;
hasSetValue();
}
unsigned int PropertyTooltable::getMemSize (void) const
{
return _Tooltable.getMemSize();
}
void PropertyTooltable::Save (Base::Writer &writer) const
{
_Tooltable.Save(writer);
}
void PropertyTooltable::Restore(Base::XMLReader &reader)
{
Path::Tooltable temp;
temp.Restore(reader);
setValue(temp);
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#endif
#include <Base/Console.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/Stream.h>
#include "PropertyTooltable.h"
#include "TooltablePy.h"
using namespace Path;
TYPESYSTEM_SOURCE(Path::PropertyTooltable, App::Property)
PropertyTooltable::PropertyTooltable()
{
}
PropertyTooltable::~PropertyTooltable()
{
}
void PropertyTooltable::setValue(const Tooltable& tt)
{
aboutToSetValue();
_Tooltable = tt;
hasSetValue();
}
const Tooltable &PropertyTooltable::getValue(void)const
{
return _Tooltable;
}
PyObject *PropertyTooltable::getPyObject(void)
{
return new TooltablePy(new Tooltable(_Tooltable));
}
void PropertyTooltable::setPyObject(PyObject *value)
{
if (PyObject_TypeCheck(value, &(TooltablePy::Type))) {
TooltablePy *pcObject = static_cast<TooltablePy*>(value);
setValue(*pcObject->getTooltablePtr());
}
else {
std::string error = std::string("type must be 'Tooltable', not ");
error += value->ob_type->tp_name;
throw Base::TypeError(error);
}
}
App::Property *PropertyTooltable::Copy(void) const
{
PropertyTooltable *prop = new PropertyTooltable();
prop->_Tooltable = this->_Tooltable;
return prop;
}
void PropertyTooltable::Paste(const App::Property &from)
{
aboutToSetValue();
_Tooltable = dynamic_cast<const PropertyTooltable&>(from)._Tooltable;
hasSetValue();
}
unsigned int PropertyTooltable::getMemSize (void) const
{
return _Tooltable.getMemSize();
}
void PropertyTooltable::Save (Base::Writer &writer) const
{
_Tooltable.Save(writer);
}
void PropertyTooltable::Restore(Base::XMLReader &reader)
{
Path::Tooltable temp;
temp.Restore(reader);
setValue(temp);
}

View File

@@ -1,75 +1,75 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PROPERTYTOOLTABLE_H
#define PROPERTYTOOLTABLE_H
#include "Tooltable.h"
#include <App/Property.h>
namespace Path
{
/** The tooltable property class. */
class PathExport PropertyTooltable : public App::Property
{
TYPESYSTEM_HEADER();
public:
PropertyTooltable();
~PropertyTooltable();
/** @name Getter/setter */
//@{
/// set the part shape
void setValue(const Tooltable&);
/// get the part shape
const Tooltable &getValue(void) const;
//@}
/** @name Python interface */
//@{
PyObject* getPyObject(void);
void setPyObject(PyObject *value);
//@}
/** @name Save/restore */
//@{
void Save (Base::Writer &writer) const;
void Restore(Base::XMLReader &reader);
App::Property *Copy(void) const;
void Paste(const App::Property &from);
unsigned int getMemSize (void) const;
//@}
private:
Tooltable _Tooltable;
};
} //namespace Path
#endif // PROPERTYTOOLTABLE_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PROPERTYTOOLTABLE_H
#define PROPERTYTOOLTABLE_H
#include "Tooltable.h"
#include <App/Property.h>
namespace Path
{
/** The tooltable property class. */
class PathExport PropertyTooltable : public App::Property
{
TYPESYSTEM_HEADER();
public:
PropertyTooltable();
~PropertyTooltable();
/** @name Getter/setter */
//@{
/// set the part shape
void setValue(const Tooltable&);
/// get the part shape
const Tooltable &getValue(void) const;
//@}
/** @name Python interface */
//@{
PyObject* getPyObject(void);
void setPyObject(PyObject *value);
//@}
/** @name Save/restore */
//@{
void Save (Base::Writer &writer) const;
void Restore(Base::XMLReader &reader);
App::Property *Copy(void) const;
void Paste(const App::Property &from);
unsigned int getMemSize (void) const;
//@}
private:
Tooltable _Tooltable;
};
} //namespace Path
#endif // PROPERTYTOOLTABLE_H

View File

@@ -1,258 +1,258 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include "Tool.h"
using namespace Base;
using namespace Path;
TYPESYSTEM_SOURCE(Path::Tool , Base::Persistence)
// Constructors & destructors
Tool::Tool(const char* name,
ToolType type,
ToolMaterial /*material*/,
double diameter,
double lengthoffset,
double flatradius,
double cornerradius,
double cuttingedgeangle,
double cuttingedgeheight)
:Name(name),Type(type),Material(MATUNDEFINED),Diameter(diameter),LengthOffset(lengthoffset),
FlatRadius(flatradius),CornerRadius(cornerradius),CuttingEdgeAngle(cuttingedgeangle),
CuttingEdgeHeight(cuttingedgeheight)
{
}
Tool::Tool()
{
Type = UNDEFINED;
Material = MATUNDEFINED;
Diameter = 0;
LengthOffset = 0;
FlatRadius = 0;
CornerRadius = 0;
CuttingEdgeAngle = 180;
CuttingEdgeHeight = 0;
}
Tool::~Tool()
{
}
// Reimplemented from base class
unsigned int Tool::getMemSize (void) const
{
return 0;
}
void Tool::Save (Writer &writer) const
{
writer.Stream() << writer.ind() << "<Tool "
<< "name=\"" << encodeAttribute(Name) << "\" "
<< "diameter=\"" << Diameter << "\" "
<< "length=\"" << LengthOffset << "\" "
<< "flat=\"" << FlatRadius << "\" "
<< "corner=\"" << CornerRadius << "\" "
<< "angle=\"" << CuttingEdgeAngle << "\" "
<< "height=\"" << CuttingEdgeHeight << "\" "
<< "type=\"" << TypeName(Type) << "\" "
<< "mat=\"" << MaterialName(Material) << "\" "
<< "/>" << std::endl;
}
void Tool::Restore(XMLReader &reader)
{
reader.readElement("Tool");
Name = reader.getAttribute("name");
Diameter = reader.hasAttribute("diameter") ? (double) reader.getAttributeAsFloat("diameter") : 0.0;
LengthOffset = reader.hasAttribute("length") ? (double) reader.getAttributeAsFloat("length") : 0.0;
FlatRadius = reader.hasAttribute("flat") ? (double) reader.getAttributeAsFloat("flat") : 0.0;
CornerRadius = reader.hasAttribute("corner") ? (double) reader.getAttributeAsFloat("corner") : 0.0;
CuttingEdgeAngle = reader.hasAttribute("angle") ? (double) reader.getAttributeAsFloat("angle") : 180.0;
CuttingEdgeHeight = reader.hasAttribute("height") ? (double) reader.getAttributeAsFloat("height") : 0.0;
std::string type = reader.hasAttribute("type") ? reader.getAttribute("type") : "";
std::string mat = reader.hasAttribute("mat") ? reader.getAttribute("mat") : "";
Type = getToolType(type);
Material = getToolMaterial(mat);
}
const std::vector<std::string> Tool::ToolTypes(void)
{
std::vector<std::string> toolTypes(13);
toolTypes[0] ="EndMill";
toolTypes[1] ="Drill";
toolTypes[2] ="CenterDrill";
toolTypes[3] ="CounterSink";
toolTypes[4] ="CounterBore";
toolTypes[5] ="FlyCutter";
toolTypes[6] ="Reamer";
toolTypes[7] ="Tap";
toolTypes[8] ="SlotCutter";
toolTypes[9] ="BallEndMill";
toolTypes[10] ="ChamferMill";
toolTypes[11] ="CornerRound";
toolTypes[12] ="Engraver";
return toolTypes;
}
const std::vector<std::string> Tool::ToolMaterials(void)
{
std::vector<std::string> toolMat(7);
toolMat[0] ="Carbide";
toolMat[1] ="HighSpeedSteel";
toolMat[2] ="HighCarbonToolSteel";
toolMat[3] ="CastAlloy";
toolMat[4] ="Ceramics";
toolMat[5] ="Diamond";
toolMat[6] ="Sialon";
return toolMat;
}
Tool::ToolType Tool::getToolType(std::string type)
{
Tool::ToolType Type;
if(type=="EndMill")
Type = Tool::ENDMILL;
else if(type=="Drill")
Type = Tool::DRILL;
else if(type=="CenterDrill")
Type = Tool::CENTERDRILL;
else if(type=="CounterSink")
Type = Tool::COUNTERSINK;
else if(type=="CounterBore")
Type = Tool::COUNTERBORE;
else if(type=="FlyCutter")
Type = Tool::FLYCUTTER;
else if(type=="Reamer")
Type = Tool::REAMER;
else if(type=="Tap")
Type = Tool::TAP;
else if(type=="SlotCutter")
Type = Tool::SLOTCUTTER;
else if(type=="BallEndMill")
Type = Tool::BALLENDMILL;
else if(type=="ChamferMill")
Type = Tool::CHAMFERMILL;
else if(type=="CornerRound")
Type = Tool::CORNERROUND;
else if(type=="Engraver")
Type = Tool::ENGRAVER;
else
Type = Tool::UNDEFINED;
return Type;
}
Tool::ToolMaterial Tool::getToolMaterial(std::string mat)
{
Tool::ToolMaterial Material;
if(mat=="Carbide")
Material = Tool::CARBIDE;
else if(mat=="HighSpeedSteel")
Material = Tool::HIGHSPEEDSTEEL;
else if(mat=="HighCarbonToolSteel")
Material = Tool::HIGHCARBONTOOLSTEEL;
else if(mat=="CastAlloy")
Material = Tool::CASTALLOY;
else if(mat=="Ceramics")
Material = Tool::CERAMICS;
else if(mat=="Diamond")
Material = Tool::DIAMOND;
else if(mat=="Sialon")
Material = Tool::SIALON;
else
Material = Tool::MATUNDEFINED;
return Material;
}
const char* Tool::TypeName(Tool::ToolType typ) {
switch (typ) {
case Tool::DRILL:
return "Drill";
case Tool::CENTERDRILL:
return "CenterDrill";
case Tool::COUNTERSINK:
return "CounterSink";
case Tool::COUNTERBORE:
return "CounterBore";
case Tool::FLYCUTTER:
return "FlyCutter";
case Tool::REAMER:
return "Reamer";
case Tool::TAP:
return "Tap";
case Tool::ENDMILL:
return "EndMill";
case Tool::SLOTCUTTER:
return "SlotCutter";
case Tool::BALLENDMILL:
return "BallEndMill";
case Tool::CHAMFERMILL:
return "ChamferMill";
case Tool::CORNERROUND:
return "CornerRound";
case Tool::ENGRAVER:
return "Engraver";
case Tool::UNDEFINED:
return "Undefined";
}
return "Undefined";
}
const char* Tool::MaterialName(Tool::ToolMaterial mat)
{
switch (mat) {
case Tool::HIGHSPEEDSTEEL:
return "HighSpeedSteel";
case Tool::CARBIDE:
return "Carbide";
case Tool::HIGHCARBONTOOLSTEEL:
return "HighCarbonToolSteel";
case Tool::CASTALLOY:
return "CastAlloy";
case Tool::CERAMICS:
return "Ceramics";
case Tool::DIAMOND:
return "Diamond";
case Tool::SIALON:
return "Sialon";
case Tool::MATUNDEFINED:
return "Undefined";
}
return "Undefined";
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include "Tool.h"
using namespace Base;
using namespace Path;
TYPESYSTEM_SOURCE(Path::Tool , Base::Persistence)
// Constructors & destructors
Tool::Tool(const char* name,
ToolType type,
ToolMaterial /*material*/,
double diameter,
double lengthoffset,
double flatradius,
double cornerradius,
double cuttingedgeangle,
double cuttingedgeheight)
:Name(name),Type(type),Material(MATUNDEFINED),Diameter(diameter),LengthOffset(lengthoffset),
FlatRadius(flatradius),CornerRadius(cornerradius),CuttingEdgeAngle(cuttingedgeangle),
CuttingEdgeHeight(cuttingedgeheight)
{
}
Tool::Tool()
{
Type = UNDEFINED;
Material = MATUNDEFINED;
Diameter = 0;
LengthOffset = 0;
FlatRadius = 0;
CornerRadius = 0;
CuttingEdgeAngle = 180;
CuttingEdgeHeight = 0;
}
Tool::~Tool()
{
}
// Reimplemented from base class
unsigned int Tool::getMemSize (void) const
{
return 0;
}
void Tool::Save (Writer &writer) const
{
writer.Stream() << writer.ind() << "<Tool "
<< "name=\"" << encodeAttribute(Name) << "\" "
<< "diameter=\"" << Diameter << "\" "
<< "length=\"" << LengthOffset << "\" "
<< "flat=\"" << FlatRadius << "\" "
<< "corner=\"" << CornerRadius << "\" "
<< "angle=\"" << CuttingEdgeAngle << "\" "
<< "height=\"" << CuttingEdgeHeight << "\" "
<< "type=\"" << TypeName(Type) << "\" "
<< "mat=\"" << MaterialName(Material) << "\" "
<< "/>" << std::endl;
}
void Tool::Restore(XMLReader &reader)
{
reader.readElement("Tool");
Name = reader.getAttribute("name");
Diameter = reader.hasAttribute("diameter") ? (double) reader.getAttributeAsFloat("diameter") : 0.0;
LengthOffset = reader.hasAttribute("length") ? (double) reader.getAttributeAsFloat("length") : 0.0;
FlatRadius = reader.hasAttribute("flat") ? (double) reader.getAttributeAsFloat("flat") : 0.0;
CornerRadius = reader.hasAttribute("corner") ? (double) reader.getAttributeAsFloat("corner") : 0.0;
CuttingEdgeAngle = reader.hasAttribute("angle") ? (double) reader.getAttributeAsFloat("angle") : 180.0;
CuttingEdgeHeight = reader.hasAttribute("height") ? (double) reader.getAttributeAsFloat("height") : 0.0;
std::string type = reader.hasAttribute("type") ? reader.getAttribute("type") : "";
std::string mat = reader.hasAttribute("mat") ? reader.getAttribute("mat") : "";
Type = getToolType(type);
Material = getToolMaterial(mat);
}
const std::vector<std::string> Tool::ToolTypes(void)
{
std::vector<std::string> toolTypes(13);
toolTypes[0] ="EndMill";
toolTypes[1] ="Drill";
toolTypes[2] ="CenterDrill";
toolTypes[3] ="CounterSink";
toolTypes[4] ="CounterBore";
toolTypes[5] ="FlyCutter";
toolTypes[6] ="Reamer";
toolTypes[7] ="Tap";
toolTypes[8] ="SlotCutter";
toolTypes[9] ="BallEndMill";
toolTypes[10] ="ChamferMill";
toolTypes[11] ="CornerRound";
toolTypes[12] ="Engraver";
return toolTypes;
}
const std::vector<std::string> Tool::ToolMaterials(void)
{
std::vector<std::string> toolMat(7);
toolMat[0] ="Carbide";
toolMat[1] ="HighSpeedSteel";
toolMat[2] ="HighCarbonToolSteel";
toolMat[3] ="CastAlloy";
toolMat[4] ="Ceramics";
toolMat[5] ="Diamond";
toolMat[6] ="Sialon";
return toolMat;
}
Tool::ToolType Tool::getToolType(std::string type)
{
Tool::ToolType Type;
if(type=="EndMill")
Type = Tool::ENDMILL;
else if(type=="Drill")
Type = Tool::DRILL;
else if(type=="CenterDrill")
Type = Tool::CENTERDRILL;
else if(type=="CounterSink")
Type = Tool::COUNTERSINK;
else if(type=="CounterBore")
Type = Tool::COUNTERBORE;
else if(type=="FlyCutter")
Type = Tool::FLYCUTTER;
else if(type=="Reamer")
Type = Tool::REAMER;
else if(type=="Tap")
Type = Tool::TAP;
else if(type=="SlotCutter")
Type = Tool::SLOTCUTTER;
else if(type=="BallEndMill")
Type = Tool::BALLENDMILL;
else if(type=="ChamferMill")
Type = Tool::CHAMFERMILL;
else if(type=="CornerRound")
Type = Tool::CORNERROUND;
else if(type=="Engraver")
Type = Tool::ENGRAVER;
else
Type = Tool::UNDEFINED;
return Type;
}
Tool::ToolMaterial Tool::getToolMaterial(std::string mat)
{
Tool::ToolMaterial Material;
if(mat=="Carbide")
Material = Tool::CARBIDE;
else if(mat=="HighSpeedSteel")
Material = Tool::HIGHSPEEDSTEEL;
else if(mat=="HighCarbonToolSteel")
Material = Tool::HIGHCARBONTOOLSTEEL;
else if(mat=="CastAlloy")
Material = Tool::CASTALLOY;
else if(mat=="Ceramics")
Material = Tool::CERAMICS;
else if(mat=="Diamond")
Material = Tool::DIAMOND;
else if(mat=="Sialon")
Material = Tool::SIALON;
else
Material = Tool::MATUNDEFINED;
return Material;
}
const char* Tool::TypeName(Tool::ToolType typ) {
switch (typ) {
case Tool::DRILL:
return "Drill";
case Tool::CENTERDRILL:
return "CenterDrill";
case Tool::COUNTERSINK:
return "CounterSink";
case Tool::COUNTERBORE:
return "CounterBore";
case Tool::FLYCUTTER:
return "FlyCutter";
case Tool::REAMER:
return "Reamer";
case Tool::TAP:
return "Tap";
case Tool::ENDMILL:
return "EndMill";
case Tool::SLOTCUTTER:
return "SlotCutter";
case Tool::BALLENDMILL:
return "BallEndMill";
case Tool::CHAMFERMILL:
return "ChamferMill";
case Tool::CORNERROUND:
return "CornerRound";
case Tool::ENGRAVER:
return "Engraver";
case Tool::UNDEFINED:
return "Undefined";
}
return "Undefined";
}
const char* Tool::MaterialName(Tool::ToolMaterial mat)
{
switch (mat) {
case Tool::HIGHSPEEDSTEEL:
return "HighSpeedSteel";
case Tool::CARBIDE:
return "Carbide";
case Tool::HIGHCARBONTOOLSTEEL:
return "HighCarbonToolSteel";
case Tool::CASTALLOY:
return "CastAlloy";
case Tool::CERAMICS:
return "Ceramics";
case Tool::DIAMOND:
return "Diamond";
case Tool::SIALON:
return "Sialon";
case Tool::MATUNDEFINED:
return "Undefined";
}
return "Undefined";
}

View File

@@ -1,104 +1,104 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_TOOL_H
#define PATH_TOOL_H
#include <vector>
#include <string>
#include <map>
#include <Base/Persistence.h>
namespace Path
{
/** The representation of a single tool */
class PathExport Tool : public Base::Persistence
{
TYPESYSTEM_HEADER();
public:
enum ToolType {
UNDEFINED,
DRILL,
CENTERDRILL,
COUNTERSINK,
COUNTERBORE,
FLYCUTTER,
REAMER,
TAP,
ENDMILL,
SLOTCUTTER,
BALLENDMILL,
CHAMFERMILL,
CORNERROUND,
ENGRAVER };
enum ToolMaterial {
MATUNDEFINED,
HIGHSPEEDSTEEL,
HIGHCARBONTOOLSTEEL,
CASTALLOY,
CARBIDE,
CERAMICS,
DIAMOND,
SIALON };
//constructors
Tool();
Tool(const char* name,
ToolType type=Tool::UNDEFINED,
ToolMaterial material=Tool::MATUNDEFINED,
double diameter=10.0,
double lengthoffset=100,
double flatradius=0,
double cornerradius=0,
double cuttingedgeangle=0,
double cuttingedgeheight=0);
~Tool();
// from base class
virtual unsigned int getMemSize (void) const;
virtual void Save (Base::Writer &/*writer*/) const;
virtual void Restore(Base::XMLReader &/*reader*/);
// attributes
std::string Name;
ToolType Type;
ToolMaterial Material;
double Diameter;
double LengthOffset;
double FlatRadius;
double CornerRadius;
double CuttingEdgeAngle;
double CuttingEdgeHeight;
static const std::vector<std::string> ToolTypes(void);
static const std::vector<std::string> ToolMaterials(void);
static const char* TypeName(ToolType typ);
static ToolType getToolType(std::string type);
static ToolMaterial getToolMaterial(std::string mat);
static const char* MaterialName(ToolMaterial mat);
};
} //namespace Path
#endif // PATH_TOOL_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_TOOL_H
#define PATH_TOOL_H
#include <vector>
#include <string>
#include <map>
#include <Base/Persistence.h>
namespace Path
{
/** The representation of a single tool */
class PathExport Tool : public Base::Persistence
{
TYPESYSTEM_HEADER();
public:
enum ToolType {
UNDEFINED,
DRILL,
CENTERDRILL,
COUNTERSINK,
COUNTERBORE,
FLYCUTTER,
REAMER,
TAP,
ENDMILL,
SLOTCUTTER,
BALLENDMILL,
CHAMFERMILL,
CORNERROUND,
ENGRAVER };
enum ToolMaterial {
MATUNDEFINED,
HIGHSPEEDSTEEL,
HIGHCARBONTOOLSTEEL,
CASTALLOY,
CARBIDE,
CERAMICS,
DIAMOND,
SIALON };
//constructors
Tool();
Tool(const char* name,
ToolType type=Tool::UNDEFINED,
ToolMaterial material=Tool::MATUNDEFINED,
double diameter=10.0,
double lengthoffset=100,
double flatradius=0,
double cornerradius=0,
double cuttingedgeangle=0,
double cuttingedgeheight=0);
~Tool();
// from base class
virtual unsigned int getMemSize (void) const;
virtual void Save (Base::Writer &/*writer*/) const;
virtual void Restore(Base::XMLReader &/*reader*/);
// attributes
std::string Name;
ToolType Type;
ToolMaterial Material;
double Diameter;
double LengthOffset;
double FlatRadius;
double CornerRadius;
double CuttingEdgeAngle;
double CuttingEdgeHeight;
static const std::vector<std::string> ToolTypes(void);
static const std::vector<std::string> ToolMaterials(void);
static const char* TypeName(ToolType typ);
static ToolType getToolType(std::string type);
static ToolMaterial getToolMaterial(std::string mat);
static const char* MaterialName(ToolMaterial mat);
};
} //namespace Path
#endif // PATH_TOOL_H

View File

@@ -1,113 +1,113 @@
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="PersistencePy"
Name="ToolPy"
Twin="Tool"
TwinPointer="Tool"
Include="Mod/Path/App/Tool.h"
Namespace="Path"
FatherInclude="Base/PersistencePy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>The Tool objects holds the properties of a CNC tool.
optional attributes:
name: a user-defined name for this tool
tooltype: Drill, CenterDrill, CounterSink, CounterBore, Reamer, Tap, EndMill, SlotCutter, BallEndMill, ChamferMill, CornerRound, Engraver or Undefined
material: HighSpeedSteel, HighCarbonToolSteel, Carbide, CastAlloy, Ceramics, Diamond, Sialon or Undefined
diameter : the diameter of this tool
lengthOffset
flatRadius
cornerRadius
cuttingEdgeAngle
cuttingEdgeHeight</UserDocu>
</Documentation>
<Attribute Name="Name" ReadOnly="false">
<Documentation>
<UserDocu>the name of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="Name" Type="String"/>
</Attribute>
<Attribute Name="ToolType" ReadOnly="false">
<Documentation>
<UserDocu>the type of this tool: Drill, CenterDrill, CounterSink, CounterBore, Reamer, Tap,
EndMill, SlotCutter, BallEndMill, ChamferMill, CornerRound, Engraver or Undefined</UserDocu>
</Documentation>
<Parameter Name="ToolType" Type="String"/>
</Attribute>
<Attribute Name="Material" ReadOnly="false">
<Documentation>
<UserDocu>the material of this tool: Steel, Carbide, HighSpeedSteel,
HighCarbonToolSteel CastAlloy, Ceramics, Diamond, Sialon or Undefined</UserDocu>
</Documentation>
<Parameter Name="Material" Type="String"/>
</Attribute>
<Attribute Name="Diameter" ReadOnly="false">
<Documentation>
<UserDocu>the diameter of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="Diameter" Type="Float"/>
</Attribute>
<Attribute Name="LengthOffset" ReadOnly="false">
<Documentation>
<UserDocu>the length offset of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="LengthOffset" Type="Float"/>
</Attribute>
<Attribute Name="FlatRadius" ReadOnly="false">
<Documentation>
<UserDocu>the flat radius of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="FlatRadius" Type="Float"/>
</Attribute>
<Attribute Name="CornerRadius" ReadOnly="false">
<Documentation>
<UserDocu>the corner radius of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="CornerRadius" Type="Float"/>
</Attribute>
<Attribute Name="CuttingEdgeAngle" ReadOnly="false">
<Documentation>
<UserDocu>the cutting edge angle of this tool</UserDocu>
</Documentation>
<Parameter Name="CuttingEdgeAngle" Type="Float"/>
</Attribute>
<Attribute Name="CuttingEdgeHeight" ReadOnly="false">
<Documentation>
<UserDocu>the cutting edge height of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="CuttingEdgeHeight" Type="Float"/>
</Attribute>
<Methode Name="copy">
<Documentation>
<UserDocu>returns a copy of this tool</UserDocu>
</Documentation>
</Methode>
<Methode Name="getToolTypes">
<Documentation>
<UserDocu>returns all available tool types</UserDocu>
</Documentation>
</Methode>
<Methode Name="getToolMaterials">
<Documentation>
<UserDocu>returns all available tool materials</UserDocu>
</Documentation>
</Methode>
<Methode Name="setFromTemplate">
<Documentation>
<UserDocu>setFromTemplate(xmlString|dictionary) ... fills receiver with values from the template string or dictionary</UserDocu>
</Documentation>
</Methode>
<Methode Name="templateAttrs" Const="true">
<Documentation>
<UserDocu>templateAttrs() ... returns a dictionary with all attributes</UserDocu>
</Documentation>
</Methode>
<!--<ClassDeclarations>
bool touched;
</ClassDeclarations>-->
</PythonExport>
</GenerateModel>
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="PersistencePy"
Name="ToolPy"
Twin="Tool"
TwinPointer="Tool"
Include="Mod/Path/App/Tool.h"
Namespace="Path"
FatherInclude="Base/PersistencePy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>The Tool objects holds the properties of a CNC tool.
optional attributes:
name: a user-defined name for this tool
tooltype: Drill, CenterDrill, CounterSink, CounterBore, Reamer, Tap, EndMill, SlotCutter, BallEndMill, ChamferMill, CornerRound, Engraver or Undefined
material: HighSpeedSteel, HighCarbonToolSteel, Carbide, CastAlloy, Ceramics, Diamond, Sialon or Undefined
diameter : the diameter of this tool
lengthOffset
flatRadius
cornerRadius
cuttingEdgeAngle
cuttingEdgeHeight</UserDocu>
</Documentation>
<Attribute Name="Name" ReadOnly="false">
<Documentation>
<UserDocu>the name of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="Name" Type="String"/>
</Attribute>
<Attribute Name="ToolType" ReadOnly="false">
<Documentation>
<UserDocu>the type of this tool: Drill, CenterDrill, CounterSink, CounterBore, Reamer, Tap,
EndMill, SlotCutter, BallEndMill, ChamferMill, CornerRound, Engraver or Undefined</UserDocu>
</Documentation>
<Parameter Name="ToolType" Type="String"/>
</Attribute>
<Attribute Name="Material" ReadOnly="false">
<Documentation>
<UserDocu>the material of this tool: Steel, Carbide, HighSpeedSteel,
HighCarbonToolSteel CastAlloy, Ceramics, Diamond, Sialon or Undefined</UserDocu>
</Documentation>
<Parameter Name="Material" Type="String"/>
</Attribute>
<Attribute Name="Diameter" ReadOnly="false">
<Documentation>
<UserDocu>the diameter of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="Diameter" Type="Float"/>
</Attribute>
<Attribute Name="LengthOffset" ReadOnly="false">
<Documentation>
<UserDocu>the length offset of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="LengthOffset" Type="Float"/>
</Attribute>
<Attribute Name="FlatRadius" ReadOnly="false">
<Documentation>
<UserDocu>the flat radius of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="FlatRadius" Type="Float"/>
</Attribute>
<Attribute Name="CornerRadius" ReadOnly="false">
<Documentation>
<UserDocu>the corner radius of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="CornerRadius" Type="Float"/>
</Attribute>
<Attribute Name="CuttingEdgeAngle" ReadOnly="false">
<Documentation>
<UserDocu>the cutting edge angle of this tool</UserDocu>
</Documentation>
<Parameter Name="CuttingEdgeAngle" Type="Float"/>
</Attribute>
<Attribute Name="CuttingEdgeHeight" ReadOnly="false">
<Documentation>
<UserDocu>the cutting edge height of this tool in mm</UserDocu>
</Documentation>
<Parameter Name="CuttingEdgeHeight" Type="Float"/>
</Attribute>
<Methode Name="copy">
<Documentation>
<UserDocu>returns a copy of this tool</UserDocu>
</Documentation>
</Methode>
<Methode Name="getToolTypes">
<Documentation>
<UserDocu>returns all available tool types</UserDocu>
</Documentation>
</Methode>
<Methode Name="getToolMaterials">
<Documentation>
<UserDocu>returns all available tool materials</UserDocu>
</Documentation>
</Methode>
<Methode Name="setFromTemplate">
<Documentation>
<UserDocu>setFromTemplate(xmlString|dictionary) ... fills receiver with values from the template string or dictionary</UserDocu>
</Documentation>
</Methode>
<Methode Name="templateAttrs" Const="true">
<Documentation>
<UserDocu>templateAttrs() ... returns a dictionary with all attributes</UserDocu>
</Documentation>
</Methode>
<!--<ClassDeclarations>
bool touched;
</ClassDeclarations>-->
</PythonExport>
</GenerateModel>

View File

@@ -1,302 +1,302 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "Base/Reader.h"
#include "Mod/Path/App/Tool.h"
#include "Mod/Path/App/Tooltable.h"
// inclusion of the generated files (generated out of ToolPy.xml and TooltablePy.xml)
#include "ToolPy.h"
#include "ToolPy.cpp"
using namespace Path;
#if PY_MAJOR_VERSION >= 3
# define PYSTRING_FROMSTRING(str) PyUnicode_FromString(str)
# define PYINT_TYPE PyLong_Type
# define PYINT_FROMLONG(l) PyLong_FromLong(l)
# define PYINT_ASLONG(o) PyLong_AsLong(o)
#else
# define PYSTRING_FROMSTRING(str) PyString_FromString(str)
# define PYINT_TYPE PyInt_Type
# define PYINT_FROMLONG(l) PyInt_FromLong(l)
# define PYINT_ASLONG(o) PyInt_AsLong(o)
#endif
// returns a string which represents the object e.g. when printed in python
std::string ToolPy::representation(void) const
{
std::stringstream str;
str.precision(5);
str << "Tool ";
str << getToolPtr()->Name;
return str.str();
}
PyObject *ToolPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
// create a new instance of ToolPy and the Twin object
return new ToolPy(new Tool);
}
// constructor method
int ToolPy::PyInit(PyObject* args, PyObject* kwd)
{
char *name="Default tool";
char *type = "Undefined";
char *mat = "Undefined";
PyObject *dia = 0;
PyObject *len = 0;
PyObject *fla = 0;
PyObject *cor = 0;
PyObject *ang = 0;
PyObject *hei = 0;
int version = 1;
static char *kwlist[] = {"name", "tooltype", "material", "diameter", "lengthOffset", "flatRadius", "cornerRadius", "cuttingEdgeAngle", "cuttingEdgeHeight" , "version", NULL};
PyObject *dict = 0;
if (!kwd && (PyObject_TypeCheck(args, &PyDict_Type) || PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))) {
static PyObject *arg = PyTuple_New(0);
if (PyObject_TypeCheck(args, &PyDict_Type)) {
dict = args;
}
if (!PyArg_ParseTupleAndKeywords(arg, dict, "|sssOOOOOOi", kwlist, &name, &type, &mat, &dia, &len, &fla, &cor, &ang, &hei, &version)) {
return -1;
}
} else {
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwd, "|sssOOOOOO", kwlist, &name, &type, &mat, &dia, &len, &fla, &cor, &ang, &hei)) {
return -1;
}
}
if (1 != version) {
PyErr_SetString(PyExc_TypeError, "Unsupported Tool template version");
return -1;
}
getToolPtr()->Name = name;
std::string typeStr(type);
getToolPtr()->Type = Tool::getToolType(typeStr);
std::string matStr(mat);
getToolPtr()->Material = Tool::getToolMaterial(matStr);
getToolPtr()->Diameter = dia ? PyFloat_AsDouble(dia) : 0.0;
getToolPtr()->LengthOffset = len ? PyFloat_AsDouble(len) : 0.0;
getToolPtr()->FlatRadius = fla ? PyFloat_AsDouble(fla) : 0.0;
getToolPtr()->CornerRadius = cor ? PyFloat_AsDouble(cor) : 0.0;
getToolPtr()->CuttingEdgeAngle = ang ? PyFloat_AsDouble(ang) : 180.0;
getToolPtr()->CuttingEdgeHeight = hei ? PyFloat_AsDouble(hei) : 0.0;
return 0;
}
// attributes get/setters
Py::String ToolPy::getName(void) const
{
return Py::String(getToolPtr()->Name.c_str());
}
void ToolPy::setName(Py::String arg)
{
std::string name = arg.as_std_string();
getToolPtr()->Name = name;
}
Py::String ToolPy::getToolType(void) const
{
return Py::String(Tool::TypeName(getToolPtr()->Type));
}
void ToolPy::setToolType(Py::String arg)
{
std::string typeStr(arg.as_std_string());
getToolPtr()->Type = Tool::getToolType(typeStr);
}
Py::String ToolPy::getMaterial(void) const
{
return Py::String(Tool::MaterialName(getToolPtr()->Material));
}
void ToolPy::setMaterial(Py::String arg)
{
std::string matStr(arg.as_std_string());
getToolPtr()->Material = Tool::getToolMaterial(matStr);
}
Py::Float ToolPy::getDiameter(void) const
{
return Py::Float(getToolPtr()->Diameter);
}
void ToolPy::setDiameter(Py::Float arg)
{
getToolPtr()->Diameter = arg.operator double();
}
Py::Float ToolPy::getLengthOffset(void) const
{
return Py::Float(getToolPtr()->LengthOffset);
}
void ToolPy::setLengthOffset(Py::Float arg)
{
getToolPtr()->LengthOffset = arg.operator double();
}
Py::Float ToolPy::getFlatRadius(void) const
{
return Py::Float(getToolPtr()->FlatRadius);
}
void ToolPy::setFlatRadius(Py::Float arg)
{
getToolPtr()->FlatRadius = arg.operator double();
}
Py::Float ToolPy::getCornerRadius(void) const
{
return Py::Float(getToolPtr()->CornerRadius);
}
void ToolPy::setCornerRadius(Py::Float arg)
{
getToolPtr()->CornerRadius = arg.operator double();
}
Py::Float ToolPy::getCuttingEdgeAngle(void) const
{
return Py::Float(getToolPtr()->CuttingEdgeAngle);
}
void ToolPy::setCuttingEdgeAngle(Py::Float arg)
{
getToolPtr()->CuttingEdgeAngle = arg.operator double();
}
Py::Float ToolPy::getCuttingEdgeHeight(void) const
{
return Py::Float(getToolPtr()->CuttingEdgeHeight);
}
void ToolPy::setCuttingEdgeHeight(Py::Float arg)
{
getToolPtr()->CuttingEdgeHeight = arg.operator double();
}
// custom attributes get/set
PyObject *ToolPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int ToolPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
PyObject* ToolPy::copy(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
return new ToolPy(new Path::Tool(*getToolPtr()));
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* ToolPy::setFromTemplate(PyObject * args)
{
char *pstr = 0;
if (PyArg_ParseTuple(args, "s", &pstr)) {
// embed actual string in dummy tag so XMLReader can consume that on construction
std::ostringstream os;
os << "<snippet>" << pstr << "</snippet>";
std::istringstream is(os.str());
Base::XMLReader reader("", is);
getToolPtr()->Restore(reader);
Py_Return ;
}
PyErr_Clear();
if (!PyInit(args, 0)) {
Py_Return ;
}
PyErr_SetString(PyExc_TypeError, "argument must be a string or dictionary");
return 0;
}
PyObject* ToolPy::templateAttrs(PyObject * args)
{
if (!args || PyArg_ParseTuple(args, "")) {
PyObject *dict = PyDict_New();
PyDict_SetItemString(dict, "version", PYINT_FROMLONG(1));
PyDict_SetItemString(dict, "name", PYSTRING_FROMSTRING(getToolPtr()->Name.c_str()));
PyDict_SetItemString(dict, "tooltype",PYSTRING_FROMSTRING(Tool::TypeName(getToolPtr()->Type)));
PyDict_SetItemString(dict, "material", PYSTRING_FROMSTRING(Tool::MaterialName(getToolPtr()->Material)));
PyDict_SetItemString(dict, "diameter", PyFloat_FromDouble(getToolPtr()->Diameter));
PyDict_SetItemString(dict, "lengthOffset", PyFloat_FromDouble(getToolPtr()->LengthOffset));
PyDict_SetItemString(dict, "flatRadius", PyFloat_FromDouble(getToolPtr()->FlatRadius));
PyDict_SetItemString(dict, "cornerRadius", PyFloat_FromDouble(getToolPtr()->CornerRadius));
PyDict_SetItemString(dict, "cuttingEdgeAngle", PyFloat_FromDouble(getToolPtr()->CuttingEdgeAngle));
PyDict_SetItemString(dict, "cuttingEdgeHeight", PyFloat_FromDouble(getToolPtr()->CuttingEdgeHeight));
return dict;
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* ToolPy::getToolTypes(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
std::vector<std::string> toolTypes = Tool::ToolTypes();
PyObject *list = PyList_New(0);
for(unsigned i = 0; i != toolTypes.size(); i++) {
PyList_Append(list, PYSTRING_FROMSTRING(toolTypes[i].c_str()));
}
return list;
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* ToolPy::getToolMaterials(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
std::vector<std::string> toolMaterials = Tool::ToolMaterials();
PyObject *list = PyList_New(0);
for(unsigned i = 0; i != toolMaterials.size(); i++) {
PyList_Append(list, PYSTRING_FROMSTRING(toolMaterials[i].c_str()));
}
return list;
}
throw Py::TypeError("This method accepts no argument");
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "Base/Reader.h"
#include "Mod/Path/App/Tool.h"
#include "Mod/Path/App/Tooltable.h"
// inclusion of the generated files (generated out of ToolPy.xml and TooltablePy.xml)
#include "ToolPy.h"
#include "ToolPy.cpp"
using namespace Path;
#if PY_MAJOR_VERSION >= 3
# define PYSTRING_FROMSTRING(str) PyUnicode_FromString(str)
# define PYINT_TYPE PyLong_Type
# define PYINT_FROMLONG(l) PyLong_FromLong(l)
# define PYINT_ASLONG(o) PyLong_AsLong(o)
#else
# define PYSTRING_FROMSTRING(str) PyString_FromString(str)
# define PYINT_TYPE PyInt_Type
# define PYINT_FROMLONG(l) PyInt_FromLong(l)
# define PYINT_ASLONG(o) PyInt_AsLong(o)
#endif
// returns a string which represents the object e.g. when printed in python
std::string ToolPy::representation(void) const
{
std::stringstream str;
str.precision(5);
str << "Tool ";
str << getToolPtr()->Name;
return str.str();
}
PyObject *ToolPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
// create a new instance of ToolPy and the Twin object
return new ToolPy(new Tool);
}
// constructor method
int ToolPy::PyInit(PyObject* args, PyObject* kwd)
{
char *name="Default tool";
char *type = "Undefined";
char *mat = "Undefined";
PyObject *dia = 0;
PyObject *len = 0;
PyObject *fla = 0;
PyObject *cor = 0;
PyObject *ang = 0;
PyObject *hei = 0;
int version = 1;
static char *kwlist[] = {"name", "tooltype", "material", "diameter", "lengthOffset", "flatRadius", "cornerRadius", "cuttingEdgeAngle", "cuttingEdgeHeight" , "version", NULL};
PyObject *dict = 0;
if (!kwd && (PyObject_TypeCheck(args, &PyDict_Type) || PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))) {
static PyObject *arg = PyTuple_New(0);
if (PyObject_TypeCheck(args, &PyDict_Type)) {
dict = args;
}
if (!PyArg_ParseTupleAndKeywords(arg, dict, "|sssOOOOOOi", kwlist, &name, &type, &mat, &dia, &len, &fla, &cor, &ang, &hei, &version)) {
return -1;
}
} else {
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwd, "|sssOOOOOO", kwlist, &name, &type, &mat, &dia, &len, &fla, &cor, &ang, &hei)) {
return -1;
}
}
if (1 != version) {
PyErr_SetString(PyExc_TypeError, "Unsupported Tool template version");
return -1;
}
getToolPtr()->Name = name;
std::string typeStr(type);
getToolPtr()->Type = Tool::getToolType(typeStr);
std::string matStr(mat);
getToolPtr()->Material = Tool::getToolMaterial(matStr);
getToolPtr()->Diameter = dia ? PyFloat_AsDouble(dia) : 0.0;
getToolPtr()->LengthOffset = len ? PyFloat_AsDouble(len) : 0.0;
getToolPtr()->FlatRadius = fla ? PyFloat_AsDouble(fla) : 0.0;
getToolPtr()->CornerRadius = cor ? PyFloat_AsDouble(cor) : 0.0;
getToolPtr()->CuttingEdgeAngle = ang ? PyFloat_AsDouble(ang) : 180.0;
getToolPtr()->CuttingEdgeHeight = hei ? PyFloat_AsDouble(hei) : 0.0;
return 0;
}
// attributes get/setters
Py::String ToolPy::getName(void) const
{
return Py::String(getToolPtr()->Name.c_str());
}
void ToolPy::setName(Py::String arg)
{
std::string name = arg.as_std_string();
getToolPtr()->Name = name;
}
Py::String ToolPy::getToolType(void) const
{
return Py::String(Tool::TypeName(getToolPtr()->Type));
}
void ToolPy::setToolType(Py::String arg)
{
std::string typeStr(arg.as_std_string());
getToolPtr()->Type = Tool::getToolType(typeStr);
}
Py::String ToolPy::getMaterial(void) const
{
return Py::String(Tool::MaterialName(getToolPtr()->Material));
}
void ToolPy::setMaterial(Py::String arg)
{
std::string matStr(arg.as_std_string());
getToolPtr()->Material = Tool::getToolMaterial(matStr);
}
Py::Float ToolPy::getDiameter(void) const
{
return Py::Float(getToolPtr()->Diameter);
}
void ToolPy::setDiameter(Py::Float arg)
{
getToolPtr()->Diameter = arg.operator double();
}
Py::Float ToolPy::getLengthOffset(void) const
{
return Py::Float(getToolPtr()->LengthOffset);
}
void ToolPy::setLengthOffset(Py::Float arg)
{
getToolPtr()->LengthOffset = arg.operator double();
}
Py::Float ToolPy::getFlatRadius(void) const
{
return Py::Float(getToolPtr()->FlatRadius);
}
void ToolPy::setFlatRadius(Py::Float arg)
{
getToolPtr()->FlatRadius = arg.operator double();
}
Py::Float ToolPy::getCornerRadius(void) const
{
return Py::Float(getToolPtr()->CornerRadius);
}
void ToolPy::setCornerRadius(Py::Float arg)
{
getToolPtr()->CornerRadius = arg.operator double();
}
Py::Float ToolPy::getCuttingEdgeAngle(void) const
{
return Py::Float(getToolPtr()->CuttingEdgeAngle);
}
void ToolPy::setCuttingEdgeAngle(Py::Float arg)
{
getToolPtr()->CuttingEdgeAngle = arg.operator double();
}
Py::Float ToolPy::getCuttingEdgeHeight(void) const
{
return Py::Float(getToolPtr()->CuttingEdgeHeight);
}
void ToolPy::setCuttingEdgeHeight(Py::Float arg)
{
getToolPtr()->CuttingEdgeHeight = arg.operator double();
}
// custom attributes get/set
PyObject *ToolPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int ToolPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
PyObject* ToolPy::copy(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
return new ToolPy(new Path::Tool(*getToolPtr()));
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* ToolPy::setFromTemplate(PyObject * args)
{
char *pstr = 0;
if (PyArg_ParseTuple(args, "s", &pstr)) {
// embed actual string in dummy tag so XMLReader can consume that on construction
std::ostringstream os;
os << "<snippet>" << pstr << "</snippet>";
std::istringstream is(os.str());
Base::XMLReader reader("", is);
getToolPtr()->Restore(reader);
Py_Return ;
}
PyErr_Clear();
if (!PyInit(args, 0)) {
Py_Return ;
}
PyErr_SetString(PyExc_TypeError, "argument must be a string or dictionary");
return 0;
}
PyObject* ToolPy::templateAttrs(PyObject * args)
{
if (!args || PyArg_ParseTuple(args, "")) {
PyObject *dict = PyDict_New();
PyDict_SetItemString(dict, "version", PYINT_FROMLONG(1));
PyDict_SetItemString(dict, "name", PYSTRING_FROMSTRING(getToolPtr()->Name.c_str()));
PyDict_SetItemString(dict, "tooltype",PYSTRING_FROMSTRING(Tool::TypeName(getToolPtr()->Type)));
PyDict_SetItemString(dict, "material", PYSTRING_FROMSTRING(Tool::MaterialName(getToolPtr()->Material)));
PyDict_SetItemString(dict, "diameter", PyFloat_FromDouble(getToolPtr()->Diameter));
PyDict_SetItemString(dict, "lengthOffset", PyFloat_FromDouble(getToolPtr()->LengthOffset));
PyDict_SetItemString(dict, "flatRadius", PyFloat_FromDouble(getToolPtr()->FlatRadius));
PyDict_SetItemString(dict, "cornerRadius", PyFloat_FromDouble(getToolPtr()->CornerRadius));
PyDict_SetItemString(dict, "cuttingEdgeAngle", PyFloat_FromDouble(getToolPtr()->CuttingEdgeAngle));
PyDict_SetItemString(dict, "cuttingEdgeHeight", PyFloat_FromDouble(getToolPtr()->CuttingEdgeHeight));
return dict;
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* ToolPy::getToolTypes(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
std::vector<std::string> toolTypes = Tool::ToolTypes();
PyObject *list = PyList_New(0);
for(unsigned i = 0; i != toolTypes.size(); i++) {
PyList_Append(list, PYSTRING_FROMSTRING(toolTypes[i].c_str()));
}
return list;
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* ToolPy::getToolMaterials(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
std::vector<std::string> toolMaterials = Tool::ToolMaterials();
PyObject *list = PyList_New(0);
for(unsigned i = 0; i != toolMaterials.size(); i++) {
PyList_Append(list, PYSTRING_FROMSTRING(toolMaterials[i].c_str()));
}
return list;
}
throw Py::TypeError("This method accepts no argument");
}

View File

@@ -1,116 +1,116 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include "Tooltable.h"
using namespace Base;
using namespace Path;
TYPESYSTEM_SOURCE(Path::Tooltable , Base::Persistence)
Tooltable::Tooltable()
{
}
Tooltable::~Tooltable()
{
}
void Tooltable::addTool(const Tool &tool)
{
Tool *tmp = new Tool(tool);
if (!Tools.empty()) {
int max = 0;
for(std::map<int,Tool*>::const_iterator i = Tools.begin(); i != Tools.end(); ++i) {
int k = i->first;
if (k > max)
max = k;
}
Tools[max+1]= tmp;
} else
Tools[1] = tmp;
}
void Tooltable::setTool(const Tool &tool, int pos)
{
if (pos == -1) {
addTool(tool);
} else {
Tool *tmp = new Tool(tool);
Tools[pos] = tmp;
}
}
void Tooltable::deleteTool(int pos)
{
if (Tools.find(pos) != Tools.end()) {
Tools.erase(pos);
} else {
throw Base::IndexError("Index not found");
}
}
unsigned int Tooltable::getMemSize (void) const
{
return 0;
}
void Tooltable::Save (Writer &writer) const
{
writer.Stream() << writer.ind() << "<Tooltable count=\"" << getSize() <<"\">" << std::endl;
writer.incInd();
for(std::map<int,Tool*>::const_iterator i = Tools.begin(); i != Tools.end(); ++i) {
int k = i->first;
Tool *v = i->second;
writer.Stream() << writer.ind() << "<Toolslot number=\"" << k << "\">" << std::endl;
writer.incInd();
v->Save(writer);
writer.decInd();
writer.Stream() << writer.ind() << "</Toolslot>" << std::endl;
}
writer.decInd();
writer.Stream() << writer.ind() << "</Tooltable>" << std::endl ;
}
void Tooltable::Restore (XMLReader &reader)
{
Tools.clear();
reader.readElement("Tooltable");
int count = reader.getAttributeAsInteger("count");
for (int i = 0; i < count; i++) {
reader.readElement("Toolslot");
int id = reader.getAttributeAsInteger("number");
Tool *tmp = new Tool();
tmp->Restore(reader);
Tools[id] = tmp;
}
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include "Tooltable.h"
using namespace Base;
using namespace Path;
TYPESYSTEM_SOURCE(Path::Tooltable , Base::Persistence)
Tooltable::Tooltable()
{
}
Tooltable::~Tooltable()
{
}
void Tooltable::addTool(const Tool &tool)
{
Tool *tmp = new Tool(tool);
if (!Tools.empty()) {
int max = 0;
for(std::map<int,Tool*>::const_iterator i = Tools.begin(); i != Tools.end(); ++i) {
int k = i->first;
if (k > max)
max = k;
}
Tools[max+1]= tmp;
} else
Tools[1] = tmp;
}
void Tooltable::setTool(const Tool &tool, int pos)
{
if (pos == -1) {
addTool(tool);
} else {
Tool *tmp = new Tool(tool);
Tools[pos] = tmp;
}
}
void Tooltable::deleteTool(int pos)
{
if (Tools.find(pos) != Tools.end()) {
Tools.erase(pos);
} else {
throw Base::IndexError("Index not found");
}
}
unsigned int Tooltable::getMemSize (void) const
{
return 0;
}
void Tooltable::Save (Writer &writer) const
{
writer.Stream() << writer.ind() << "<Tooltable count=\"" << getSize() <<"\">" << std::endl;
writer.incInd();
for(std::map<int,Tool*>::const_iterator i = Tools.begin(); i != Tools.end(); ++i) {
int k = i->first;
Tool *v = i->second;
writer.Stream() << writer.ind() << "<Toolslot number=\"" << k << "\">" << std::endl;
writer.incInd();
v->Save(writer);
writer.decInd();
writer.Stream() << writer.ind() << "</Toolslot>" << std::endl;
}
writer.decInd();
writer.Stream() << writer.ind() << "</Tooltable>" << std::endl ;
}
void Tooltable::Restore (XMLReader &reader)
{
Tools.clear();
reader.readElement("Tooltable");
int count = reader.getAttributeAsInteger("count");
for (int i = 0; i < count; i++) {
reader.readElement("Toolslot");
int id = reader.getAttributeAsInteger("number");
Tool *tmp = new Tool();
tmp->Restore(reader);
Tools[id] = tmp;
}
}

View File

@@ -1,68 +1,68 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_TOOLTABLE_H
#define PATH_TOOLTABLE_H
#include <vector>
#include <string>
#include <map>
#include <Base/Persistence.h>
#include "Tool.h"
namespace Path
{ /** The representation of a table of tools */
class PathExport Tooltable : public Base::Persistence
{
TYPESYSTEM_HEADER();
public:
//constructors
Tooltable();
~Tooltable();
// from base class
virtual unsigned int getMemSize (void) const;
virtual void Save (Base::Writer &/*writer*/) const;
virtual void Restore(Base::XMLReader &/*reader*/);
// new functions
void addTool(const Tool &tool); // adds a tool at the end
void setTool(const Tool &tool, int); // inserts a tool
void deleteTool(int); // deletes a tool
// auto
unsigned int getSize(void) const {return Tools.size();}
const Tool &getTool(int pos) {return *Tools[pos];}
const std::map<int,Tool*> &getTools(void) const {return Tools;}
bool hasTool(int pos) const {return (Tools.count(pos) != 0);}
// attributes
std::map<int,Tool*> Tools;
int Version;
std::string Name;
};
} //namespace Path
#endif // PATH_TOOLTABLE_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_TOOLTABLE_H
#define PATH_TOOLTABLE_H
#include <vector>
#include <string>
#include <map>
#include <Base/Persistence.h>
#include "Tool.h"
namespace Path
{ /** The representation of a table of tools */
class PathExport Tooltable : public Base::Persistence
{
TYPESYSTEM_HEADER();
public:
//constructors
Tooltable();
~Tooltable();
// from base class
virtual unsigned int getMemSize (void) const;
virtual void Save (Base::Writer &/*writer*/) const;
virtual void Restore(Base::XMLReader &/*reader*/);
// new functions
void addTool(const Tool &tool); // adds a tool at the end
void setTool(const Tool &tool, int); // inserts a tool
void deleteTool(int); // deletes a tool
// auto
unsigned int getSize(void) const {return Tools.size();}
const Tool &getTool(int pos) {return *Tools[pos];}
const std::map<int,Tool*> &getTools(void) const {return Tools;}
bool hasTool(int pos) const {return (Tools.count(pos) != 0);}
// attributes
std::map<int,Tool*> Tools;
int Version;
std::string Name;
};
} //namespace Path
#endif // PATH_TOOLTABLE_H

View File

@@ -1,78 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="PersistencePy"
Name="TooltablePy"
Twin="Tooltable"
TwinPointer="Tooltable"
Include="Mod/Path/App/Tooltable.h"
Namespace="Path"
FatherInclude="Base/PersistencePy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>The Tooltable object holds a table of CNC tools</UserDocu>
</Documentation>
<Attribute Name="Name" ReadOnly="false">
<Documentation>
<UserDocu>the name of this tool table</UserDocu>
</Documentation>
<Parameter Name="Name" Type="String"/>
</Attribute>
<Attribute Name="Version" ReadOnly="false">
<Documentation>
<UserDocu>the version of this tooltable</UserDocu>
</Documentation>
<Parameter Name="Version" Type="Int"/>
</Attribute>
<Attribute Name="Tools" ReadOnly="false">
<Documentation>
<UserDocu>the dictionary of tools of this table</UserDocu>
</Documentation>
<Parameter Name="Tools" Type="Dict"/>
</Attribute>
<Methode Name="copy">
<Documentation>
<UserDocu>returns a copy of this tooltable</UserDocu>
</Documentation>
</Methode>
<Methode Name="addTools">
<Documentation>
<UserDocu>adds a tool or a list of tools at the end of the table</UserDocu>
</Documentation>
</Methode>
<Methode Name="getTool">
<Documentation>
<UserDocu>getTool(int):
returns the tool found at the given position, or None</UserDocu>
</Documentation>
</Methode>
<Methode Name="setTool">
<Documentation>
<UserDocu>setTool(int,tool):
adds a tool at the given position</UserDocu>
</Documentation>
</Methode>
<Methode Name="deleteTool">
<Documentation>
<UserDocu>deleteTool(int):
deletes the tool found at the given position</UserDocu>
</Documentation>
</Methode>
<!--<ClassDeclarations>
bool touched;
</ClassDeclarations>-->
<Methode Name="setFromTemplate">
<Documentation>
<UserDocu>setFromTemplate(dict) ... restores receiver from given template attribute dictionary</UserDocu>
</Documentation>
</Methode>
<Methode Name="templateAttrs" Const="true">
<Documentation>
<UserDocu>templateAttrs() ... returns a dictionary representing the receivers attributes for a template</UserDocu>
</Documentation>
</Methode>
</PythonExport>
</GenerateModel>
<?xml version="1.0" encoding="UTF-8"?>
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
<PythonExport
Father="PersistencePy"
Name="TooltablePy"
Twin="Tooltable"
TwinPointer="Tooltable"
Include="Mod/Path/App/Tooltable.h"
Namespace="Path"
FatherInclude="Base/PersistencePy.h"
FatherNamespace="Base"
Constructor="true"
Delete="true">
<Documentation>
<Author Licence="LGPL" Name="Yorik van Havre" EMail="yorik@uncreated.net" />
<UserDocu>The Tooltable object holds a table of CNC tools</UserDocu>
</Documentation>
<Attribute Name="Name" ReadOnly="false">
<Documentation>
<UserDocu>the name of this tool table</UserDocu>
</Documentation>
<Parameter Name="Name" Type="String"/>
</Attribute>
<Attribute Name="Version" ReadOnly="false">
<Documentation>
<UserDocu>the version of this tooltable</UserDocu>
</Documentation>
<Parameter Name="Version" Type="Int"/>
</Attribute>
<Attribute Name="Tools" ReadOnly="false">
<Documentation>
<UserDocu>the dictionary of tools of this table</UserDocu>
</Documentation>
<Parameter Name="Tools" Type="Dict"/>
</Attribute>
<Methode Name="copy">
<Documentation>
<UserDocu>returns a copy of this tooltable</UserDocu>
</Documentation>
</Methode>
<Methode Name="addTools">
<Documentation>
<UserDocu>adds a tool or a list of tools at the end of the table</UserDocu>
</Documentation>
</Methode>
<Methode Name="getTool">
<Documentation>
<UserDocu>getTool(int):
returns the tool found at the given position, or None</UserDocu>
</Documentation>
</Methode>
<Methode Name="setTool">
<Documentation>
<UserDocu>setTool(int,tool):
adds a tool at the given position</UserDocu>
</Documentation>
</Methode>
<Methode Name="deleteTool">
<Documentation>
<UserDocu>deleteTool(int):
deletes the tool found at the given position</UserDocu>
</Documentation>
</Methode>
<!--<ClassDeclarations>
bool touched;
</ClassDeclarations>-->
<Methode Name="setFromTemplate">
<Documentation>
<UserDocu>setFromTemplate(dict) ... restores receiver from given template attribute dictionary</UserDocu>
</Documentation>
</Methode>
<Methode Name="templateAttrs" Const="true">
<Documentation>
<UserDocu>templateAttrs() ... returns a dictionary representing the receivers attributes for a template</UserDocu>
</Documentation>
</Methode>
</PythonExport>
</GenerateModel>

View File

@@ -1,288 +1,288 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "Base/Reader.h"
#include "Mod/Path/App/Tool.h"
#include "Mod/Path/App/Tooltable.h"
// inclusion of the generated files (generated out of ToolPy.xml and TooltablePy.xml)
#include "ToolPy.h"
#include "TooltablePy.h"
#include "TooltablePy.cpp"
using namespace Path;
#if PY_MAJOR_VERSION >= 3
# define PYSTRING_FROMSTRING(str) PyUnicode_FromString(str)
# define PYINT_TYPE PyLong_Type
# define PYINT_FROMLONG(l) PyLong_FromLong(l)
# define PYINT_ASLONG(o) PyLong_AsLong(o)
#else
# define PYSTRING_FROMSTRING(str) PyString_FromString(str)
# define PYINT_TYPE PyInt_Type
# define PYINT_FROMLONG(l) PyInt_FromLong(l)
# define PYINT_ASLONG(o) PyInt_AsLong(o)
#endif
// returns a string which represents the object e.g. when printed in python
std::string TooltablePy::representation(void) const
{
std::stringstream str;
str.precision(5);
str << "Tooltable containing ";
str << getTooltablePtr()->getSize() << " tools";
return str.str();
}
PyObject *TooltablePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
return new TooltablePy(new Tooltable);
}
// constructor method
int TooltablePy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
//char *name="Tooltable";
//int version = 1;
if (PyArg_ParseTuple(args, "")) {
return 0;
}
PyErr_Clear(); // set by PyArg_ParseTuple()
PyObject *pcObj;
if (PyArg_ParseTuple(args, "O!", &(PyDict_Type), &pcObj)) {
try {
Py::Dict dict(pcObj);
setTools(dict);
} catch(...) {
PyErr_SetString(PyExc_TypeError, "The dictionary can only contain int:tool pairs");
return -1;
}
return 0;
}
PyErr_Clear(); // set by PyArg_ParseTuple()
if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &pcObj)) {
Py::List list(pcObj);
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::ToolPy::Type))) {
Path::Tool &tool = *static_cast<Path::ToolPy*>((*it).ptr())->getToolPtr();
getTooltablePtr()->addTool(tool);
}
}
return 0;
}
PyErr_SetString(PyExc_TypeError, "Argument must be either empty or a list or a dictionary");
return -1;
}
// Commands get/set
Py::Dict TooltablePy::getTools(void) const
{
PyObject *dict = PyDict_New();
for(std::map<int,Path::Tool*>::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) {
PyObject *tool = new Path::ToolPy(i->second);
PyDict_SetItem(dict,PYINT_FROMLONG(i->first),tool);
}
return Py::Dict(dict);
}
void TooltablePy::setTools(Py::Dict arg)
{
getTooltablePtr()->Tools.clear();
PyObject* dict_copy = PyDict_Copy(arg.ptr());
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(dict_copy, &pos, &key, &value)) {
if ( PyObject_TypeCheck(key,&(PYINT_TYPE)) && ((PyObject_TypeCheck(value, &(Path::ToolPy::Type))) || PyObject_TypeCheck(value, &PyDict_Type))) {
int ckey = (int)PYINT_ASLONG(key);
if (PyObject_TypeCheck(value, &(Path::ToolPy::Type))) {
Path::Tool &tool = *static_cast<Path::ToolPy*>(value)->getToolPtr();
getTooltablePtr()->setTool(tool, ckey);
} else {
PyErr_Clear();
Path::Tool *tool = new Path::Tool;
// The 'pyTool' object must be created on the heap otherwise Python
// will fail to properly track the reference counts and aborts
// in debug mode.
Path::ToolPy* pyTool = new Path::ToolPy(tool);
PyObject* success = pyTool->setFromTemplate(value);
if (!success) {
Py_DECREF(pyTool);
throw Py::Exception();
}
getTooltablePtr()->setTool(*tool, ckey);
Py_DECREF(pyTool);
Py_DECREF(success);
}
} else {
throw Py::TypeError("The dictionary can only contain int:tool pairs");
}
}
}
// specific methods
PyObject* TooltablePy::copy(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* TooltablePy::addTools(PyObject * args)
{
PyObject* o;
if (PyArg_ParseTuple(args, "O!", &(Path::ToolPy::Type), &o)) {
Path::Tool &tool = *static_cast<Path::ToolPy*>(o)->getToolPtr();
getTooltablePtr()->addTool(tool);
//return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
Py_INCREF(Py_None);
return Py_None;
}
PyErr_Clear();
if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &o)) {
Py::List list(o);
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::ToolPy::Type))) {
Path::Tool &tool = *static_cast<Path::ToolPy*>((*it).ptr())->getToolPtr();
getTooltablePtr()->addTool(tool);
}
}
//return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
Py_INCREF(Py_None);
return Py_None;
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - tool or list of tools expected");
}
PyObject* TooltablePy::setTool(PyObject * args)
{
PyObject* o;
int pos = -1;
if (PyArg_ParseTuple(args, "iO!", &pos, &(Path::ToolPy::Type), &o)) {
Path::Tool &tool = *static_cast<Path::ToolPy*>(o)->getToolPtr();
getTooltablePtr()->setTool(tool,pos);
//return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
Py_INCREF(Py_None);
return Py_None;
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected tool and optional integer");
}
PyObject* TooltablePy::getTool(PyObject * args)
{
int pos = -1;
if (PyArg_ParseTuple(args, "i", &pos)) {
if (getTooltablePtr()->hasTool(pos))
{
Path::Tool tool = getTooltablePtr()->getTool(pos);
return new ToolPy(new Path::Tool(tool));
}
else
{
Py_INCREF(Py_None);
return Py_None;
}
}
Py_Error(Base::BaseExceptionFreeCADError, "Argument must be integer");
}
PyObject* TooltablePy::deleteTool(PyObject * args)
{
int pos = -1;
if (PyArg_ParseTuple(args, "|i", &pos)) {
getTooltablePtr()->deleteTool(pos);
//return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
Py_INCREF(Py_None);
return Py_None;
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected an integer (optional)");
}
// custom attributes get/set
PyObject *TooltablePy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int TooltablePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
Py::Int TooltablePy::getVersion(void) const
{
return Py::Int(getTooltablePtr()->Version);
}
void TooltablePy::setVersion(Py::Int version) {
getTooltablePtr()->Version = version;
}
Py::String TooltablePy::getName(void) const
{
return Py::String(getTooltablePtr()->Name.c_str());
}
void TooltablePy::setName(Py::String arg)
{
std::string name = arg.as_std_string();
getTooltablePtr()->Name = name;
}
PyObject* TooltablePy::setFromTemplate(PyObject * args)
{
PyObject *dict = 0;
if (PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict)) {
Py::Dict d(dict);
setTools(d);
Py_Return ;
}
PyErr_SetString(PyExc_TypeError, "argument must be a dictionary returned from templateAttrs()");
return 0;
}
PyObject* TooltablePy::templateAttrs(PyObject * args)
{
(void)args;
PyObject *dict = PyDict_New();
for(std::map<int,Path::Tool*>::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) {
// The 'tool' object must be created on the heap otherwise Python
// will fail to properly track the reference counts and aborts
// in debug mode.
Path::ToolPy* tool = new Path::ToolPy(new Path::Tool(*i->second));
PyObject *attrs = tool->templateAttrs(0);
PyDict_SetItem(dict, PYINT_FROMLONG(i->first), attrs);
Py_DECREF(tool);
}
return dict;
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "Base/Reader.h"
#include "Mod/Path/App/Tool.h"
#include "Mod/Path/App/Tooltable.h"
// inclusion of the generated files (generated out of ToolPy.xml and TooltablePy.xml)
#include "ToolPy.h"
#include "TooltablePy.h"
#include "TooltablePy.cpp"
using namespace Path;
#if PY_MAJOR_VERSION >= 3
# define PYSTRING_FROMSTRING(str) PyUnicode_FromString(str)
# define PYINT_TYPE PyLong_Type
# define PYINT_FROMLONG(l) PyLong_FromLong(l)
# define PYINT_ASLONG(o) PyLong_AsLong(o)
#else
# define PYSTRING_FROMSTRING(str) PyString_FromString(str)
# define PYINT_TYPE PyInt_Type
# define PYINT_FROMLONG(l) PyInt_FromLong(l)
# define PYINT_ASLONG(o) PyInt_AsLong(o)
#endif
// returns a string which represents the object e.g. when printed in python
std::string TooltablePy::representation(void) const
{
std::stringstream str;
str.precision(5);
str << "Tooltable containing ";
str << getTooltablePtr()->getSize() << " tools";
return str.str();
}
PyObject *TooltablePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
return new TooltablePy(new Tooltable);
}
// constructor method
int TooltablePy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
//char *name="Tooltable";
//int version = 1;
if (PyArg_ParseTuple(args, "")) {
return 0;
}
PyErr_Clear(); // set by PyArg_ParseTuple()
PyObject *pcObj;
if (PyArg_ParseTuple(args, "O!", &(PyDict_Type), &pcObj)) {
try {
Py::Dict dict(pcObj);
setTools(dict);
} catch(...) {
PyErr_SetString(PyExc_TypeError, "The dictionary can only contain int:tool pairs");
return -1;
}
return 0;
}
PyErr_Clear(); // set by PyArg_ParseTuple()
if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &pcObj)) {
Py::List list(pcObj);
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::ToolPy::Type))) {
Path::Tool &tool = *static_cast<Path::ToolPy*>((*it).ptr())->getToolPtr();
getTooltablePtr()->addTool(tool);
}
}
return 0;
}
PyErr_SetString(PyExc_TypeError, "Argument must be either empty or a list or a dictionary");
return -1;
}
// Commands get/set
Py::Dict TooltablePy::getTools(void) const
{
PyObject *dict = PyDict_New();
for(std::map<int,Path::Tool*>::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) {
PyObject *tool = new Path::ToolPy(i->second);
PyDict_SetItem(dict,PYINT_FROMLONG(i->first),tool);
}
return Py::Dict(dict);
}
void TooltablePy::setTools(Py::Dict arg)
{
getTooltablePtr()->Tools.clear();
PyObject* dict_copy = PyDict_Copy(arg.ptr());
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(dict_copy, &pos, &key, &value)) {
if ( PyObject_TypeCheck(key,&(PYINT_TYPE)) && ((PyObject_TypeCheck(value, &(Path::ToolPy::Type))) || PyObject_TypeCheck(value, &PyDict_Type))) {
int ckey = (int)PYINT_ASLONG(key);
if (PyObject_TypeCheck(value, &(Path::ToolPy::Type))) {
Path::Tool &tool = *static_cast<Path::ToolPy*>(value)->getToolPtr();
getTooltablePtr()->setTool(tool, ckey);
} else {
PyErr_Clear();
Path::Tool *tool = new Path::Tool;
// The 'pyTool' object must be created on the heap otherwise Python
// will fail to properly track the reference counts and aborts
// in debug mode.
Path::ToolPy* pyTool = new Path::ToolPy(tool);
PyObject* success = pyTool->setFromTemplate(value);
if (!success) {
Py_DECREF(pyTool);
throw Py::Exception();
}
getTooltablePtr()->setTool(*tool, ckey);
Py_DECREF(pyTool);
Py_DECREF(success);
}
} else {
throw Py::TypeError("The dictionary can only contain int:tool pairs");
}
}
}
// specific methods
PyObject* TooltablePy::copy(PyObject * args)
{
if (PyArg_ParseTuple(args, "")) {
return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
}
throw Py::TypeError("This method accepts no argument");
}
PyObject* TooltablePy::addTools(PyObject * args)
{
PyObject* o;
if (PyArg_ParseTuple(args, "O!", &(Path::ToolPy::Type), &o)) {
Path::Tool &tool = *static_cast<Path::ToolPy*>(o)->getToolPtr();
getTooltablePtr()->addTool(tool);
//return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
Py_INCREF(Py_None);
return Py_None;
}
PyErr_Clear();
if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &o)) {
Py::List list(o);
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Path::ToolPy::Type))) {
Path::Tool &tool = *static_cast<Path::ToolPy*>((*it).ptr())->getToolPtr();
getTooltablePtr()->addTool(tool);
}
}
//return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
Py_INCREF(Py_None);
return Py_None;
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - tool or list of tools expected");
}
PyObject* TooltablePy::setTool(PyObject * args)
{
PyObject* o;
int pos = -1;
if (PyArg_ParseTuple(args, "iO!", &pos, &(Path::ToolPy::Type), &o)) {
Path::Tool &tool = *static_cast<Path::ToolPy*>(o)->getToolPtr();
getTooltablePtr()->setTool(tool,pos);
//return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
Py_INCREF(Py_None);
return Py_None;
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected tool and optional integer");
}
PyObject* TooltablePy::getTool(PyObject * args)
{
int pos = -1;
if (PyArg_ParseTuple(args, "i", &pos)) {
if (getTooltablePtr()->hasTool(pos))
{
Path::Tool tool = getTooltablePtr()->getTool(pos);
return new ToolPy(new Path::Tool(tool));
}
else
{
Py_INCREF(Py_None);
return Py_None;
}
}
Py_Error(Base::BaseExceptionFreeCADError, "Argument must be integer");
}
PyObject* TooltablePy::deleteTool(PyObject * args)
{
int pos = -1;
if (PyArg_ParseTuple(args, "|i", &pos)) {
getTooltablePtr()->deleteTool(pos);
//return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
Py_INCREF(Py_None);
return Py_None;
}
Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected an integer (optional)");
}
// custom attributes get/set
PyObject *TooltablePy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int TooltablePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
Py::Int TooltablePy::getVersion(void) const
{
return Py::Int(getTooltablePtr()->Version);
}
void TooltablePy::setVersion(Py::Int version) {
getTooltablePtr()->Version = version;
}
Py::String TooltablePy::getName(void) const
{
return Py::String(getTooltablePtr()->Name.c_str());
}
void TooltablePy::setName(Py::String arg)
{
std::string name = arg.as_std_string();
getTooltablePtr()->Name = name;
}
PyObject* TooltablePy::setFromTemplate(PyObject * args)
{
PyObject *dict = 0;
if (PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict)) {
Py::Dict d(dict);
setTools(d);
Py_Return ;
}
PyErr_SetString(PyExc_TypeError, "argument must be a dictionary returned from templateAttrs()");
return 0;
}
PyObject* TooltablePy::templateAttrs(PyObject * args)
{
(void)args;
PyObject *dict = PyDict_New();
for(std::map<int,Path::Tool*>::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) {
// The 'tool' object must be created on the heap otherwise Python
// will fail to properly track the reference counts and aborts
// in debug mode.
Path::ToolPy* tool = new Path::ToolPy(new Path::Tool(*i->second));
PyObject *attrs = tool->templateAttrs(0);
PyDict_SetItem(dict, PYINT_FROMLONG(i->first), attrs);
Py_DECREF(tool);
}
return dict;
}

View File

@@ -1,83 +1,83 @@
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP
#define BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP
#if defined(_MSC_VER)
# pragma once
#endif
#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>
#include <boost/container/detail/preprocessor.hpp>
#include "../../intrusive/detail/has_member_function_callable_with.hpp"
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME allocate
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 2, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME destroy
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 3, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME max_size
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 0, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME select_on_container_copy_construction
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 0, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME construct
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS+1, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME swap
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
namespace boost {
namespace container {
namespace container_detail {
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(pointer)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_pointer)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(reference)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_reference)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(void_pointer)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_void_pointer)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(size_type)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_copy_assignment)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_move_assignment)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_swap)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(difference_type)
} //namespace container_detail {
} //namespace container {
} //namespace boost {
#include <boost/container/detail/config_end.hpp>
#endif // ! defined(BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP)
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP
#define BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP
#if defined(_MSC_VER)
# pragma once
#endif
#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>
#include <boost/container/detail/preprocessor.hpp>
#include "../../intrusive/detail/has_member_function_callable_with.hpp"
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME allocate
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 2, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME destroy
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 3, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME max_size
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 0, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME select_on_container_copy_construction
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 0, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME construct
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS+1, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME swap
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "../../intrusive/detail/has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
namespace boost {
namespace container {
namespace container_detail {
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(pointer)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_pointer)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(reference)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_reference)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(void_pointer)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_void_pointer)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(size_type)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_copy_assignment)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_move_assignment)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_swap)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(difference_type)
} //namespace container_detail {
} //namespace container {
} //namespace boost {
#include <boost/container/detail/config_end.hpp>
#endif // ! defined(BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP)

View File

@@ -1,365 +1,365 @@
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
//////////////////////////////////////////////////////////////////////////////
// sample.h
#if !defined(BOOST_PP_IS_ITERATING)
#ifndef BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED
#define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/detail/workaround.hpp>
#include <boost/intrusive/detail/preprocessor.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/static_assert.hpp>
#include <boost/move/move.hpp>
//Mark that we don't support 0 arg calls due to compiler ICE in GCC 3.4/4.0/4.1 and
//wrong SFINAE for GCC 4.2/4.3
#if defined(__GNUC__) && !defined(__clang__) && ((__GNUC__*100 + __GNUC_MINOR__*10) >= 340) && ((__GNUC__*100 + __GNUC_MINOR__*10) <= 430)
#define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED
#elif defined(BOOST_INTEL) && (BOOST_INTEL < 1200 )
#define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED
#endif
namespace boost_intrusive_has_member_function_callable_with {
struct dont_care
{
dont_care(...);
};
struct private_type
{
static private_type p;
private_type const &operator,(int) const;
};
typedef char yes_type; // sizeof(yes_type) == 1
struct no_type{ char dummy[2]; }; // sizeof(no_type) == 2
template<typename T>
no_type is_private_type(T const &);
yes_type is_private_type(private_type const &);
} //boost_intrusive_has_member_function_callable_with
#include <boost/intrusive/detail/config_end.hpp>
#endif //BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED
#else //!BOOST_PP_IS_ITERATING
#ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
#error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME not defined!"
#endif
#ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
#error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN not defined!"
#endif
#ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END not defined!"
#endif
#if BOOST_PP_ITERATION_START() != 0
#error "BOOST_PP_ITERATION_START() must be zero (0)"
#endif
#if BOOST_PP_ITERATION() == 0
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
template <typename Type>
class BOOST_PP_CAT(has_member_function_named_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
{
struct BaseMixin
{
void BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME();
};
struct Base : public ::boost::intrusive::detail::remove_cv<Type>::type, public BaseMixin { Base(); };
template <typename T, T t> class Helper{};
template <typename U>
static boost_intrusive_has_member_function_callable_with::no_type deduce
(U*, Helper<void (BaseMixin::*)(), &U::BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME>* = 0);
static boost_intrusive_has_member_function_callable_with::yes_type deduce(...);
public:
static const bool value =
sizeof(boost_intrusive_has_member_function_callable_with::yes_type) == sizeof(deduce((Base*)(0)));
};
#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
template<typename Fun, bool HasFunc
BOOST_PP_ENUM_TRAILING(BOOST_PP_ITERATION_FINISH(), BOOST_INTRUSIVE_PP_TEMPLATE_PARAM_VOID_DEFAULT, _)>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl);
//!
template<typename Fun BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION_FINISH(), class P)>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl)
<Fun, false BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION_FINISH(), P)>
{
static const bool value = false;
};
//!
#if !defined(_MSC_VER) || (_MSC_VER < 1600)
#if defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED)
template<typename Fun>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true BOOST_PP_ENUM_TRAILING(BOOST_PP_SUB(BOOST_PP_ITERATION_FINISH(), BOOST_PP_ITERATION()), BOOST_INTRUSIVE_PP_IDENTITY, void)>
{
//Mark that we don't support 0 arg calls due to compiler ICE in GCC 3.4/4.0/4.1 and
//wrong SFINAE for GCC 4.2/4.3
static const bool value = true;
};
#else //defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED)
//Special case for 0 args
template< class F
, std::size_t N =
sizeof((boost::move_detail::declval<F>().
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME (), 0))>
struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
{
boost_intrusive_has_member_function_callable_with::yes_type dummy;
BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int);
};
//For buggy compilers like MSVC 7.1+ ((F*)0)->func() does not
//SFINAE-out the zeroarg_checker_ instantiation but sizeof yields to 0.
template<class F>
struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<F, 0>
{
boost_intrusive_has_member_function_callable_with::no_type dummy;
BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int);
};
template<typename Fun>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true BOOST_PP_ENUM_TRAILING(BOOST_PP_SUB(BOOST_PP_ITERATION_FINISH(), BOOST_PP_ITERATION()), BOOST_INTRUSIVE_PP_IDENTITY, void)>
{
template<class U>
static BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<U>
Test(BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<U>*);
template <class U>
static boost_intrusive_has_member_function_callable_with::no_type Test(...);
static const bool value = sizeof(Test< Fun >(0))
== sizeof(boost_intrusive_has_member_function_callable_with::yes_type);
};
#endif //defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED)
#else //#if !defined(_MSC_VER) || (_MSC_VER < 1600)
template<typename Fun>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true BOOST_PP_ENUM_TRAILING(BOOST_PP_SUB(BOOST_PP_ITERATION_FINISH(), BOOST_PP_ITERATION()), BOOST_INTRUSIVE_PP_IDENTITY, void)>
{
template<class U>
static decltype( boost::move_detail::declval<Fun>().BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME()
, boost_intrusive_has_member_function_callable_with::yes_type())
Test(Fun*);
template<class U>
static boost_intrusive_has_member_function_callable_with::no_type Test(...);
static const bool value = sizeof(Test<Fun>(0))
== sizeof(boost_intrusive_has_member_function_callable_with::yes_type);
};
#endif //#if !defined(_MSC_VER) || (_MSC_VER < 1600)
#else //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
template<typename Fun, bool HasFunc, class ...Args>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl);
template<typename Fun, class ...Args>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, false, Args...>
{
static const bool value = false;
};
//Special case for 0 args
template< class F
, std::size_t N =
sizeof((boost::move_detail::declval<F>().
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME (), 0))>
struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
{
boost_intrusive_has_member_function_callable_with::yes_type dummy;
BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int);
};
//For buggy compilers like MSVC 7.1+ ((F*)0)->func() does not
//SFINAE-out the zeroarg_checker_ instantiation but sizeof yields to 0.
template<class F>
struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<F, 0>
{
boost_intrusive_has_member_function_callable_with::no_type dummy;
BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int);
};
template<typename Fun>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true>
{
#ifdef BOOST_MSVC
template<class U>
static decltype( boost::move_detail::declval<Fun>().BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME()
, boost_intrusive_has_member_function_callable_with::yes_type())
Test(Fun*);
#else
template<class U>
static BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
<U> Test(BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<U>*);
#endif
template <class U>
static boost_intrusive_has_member_function_callable_with::no_type Test(...);
static const bool value = sizeof(Test< Fun >(0))
== sizeof(boost_intrusive_has_member_function_callable_with::yes_type);
};
template<typename Fun, class ...DontCares>
struct BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )
: Fun
{
BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )();
using Fun::BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME;
boost_intrusive_has_member_function_callable_with::private_type
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
( DontCares...) const;
};
template<typename Fun, class ...Args>
struct BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl)
<Fun, true , Args...>
{
template<class T>
struct make_dontcare
{
typedef boost_intrusive_has_member_function_callable_with::dont_care type;
};
typedef BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )
<Fun, typename make_dontcare<Args>::type...> FunWrap;
static bool const value = (sizeof(boost_intrusive_has_member_function_callable_with::no_type) ==
sizeof(boost_intrusive_has_member_function_callable_with::is_private_type
( (::boost::move_detail::declval< FunWrap >().
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
( ::boost::move_detail::declval<Args>()... ), 0) )
)
);
};
template<typename Fun, class ...Args>
struct BOOST_PP_CAT( has_member_function_callable_with_
, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
: public BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_
, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
< Fun
, BOOST_PP_CAT( has_member_function_named_
, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )<Fun>::value
, Args... >
{};
#endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#else //BOOST_PP_ITERATION() == 0
#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
template<typename Fun>
struct BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION())
, BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME))
: Fun
{
BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION())
, BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME))();
using Fun::BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME;
boost_intrusive_has_member_function_callable_with::private_type
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
( BOOST_PP_ENUM(BOOST_PP_ITERATION()
, BOOST_INTRUSIVE_PP_IDENTITY
, boost_intrusive_has_member_function_callable_with::dont_care)) const;
};
template<typename Fun BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION(), class P)>
struct BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_
, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true
BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION(), P)
BOOST_PP_ENUM_TRAILING( BOOST_PP_SUB(BOOST_PP_ITERATION_FINISH(), BOOST_PP_ITERATION())
, BOOST_INTRUSIVE_PP_IDENTITY
, void)>
{
typedef BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION())
, BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME))<Fun>
FunWrap;
static bool const value =
(sizeof(boost_intrusive_has_member_function_callable_with::no_type) ==
sizeof(boost_intrusive_has_member_function_callable_with::is_private_type
( (boost::move_detail::declval<FunWrap>().
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
( BOOST_PP_ENUM( BOOST_PP_ITERATION(), BOOST_INTRUSIVE_PP_DECLVAL, _) ), 0
)
)
)
);
};
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
#endif //BOOST_PP_ITERATION() == 0
#if BOOST_PP_ITERATION() == BOOST_PP_ITERATION_FINISH()
#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
template<typename Fun
BOOST_PP_ENUM_TRAILING(BOOST_PP_ITERATION_FINISH(), BOOST_INTRUSIVE_PP_TEMPLATE_PARAM_VOID_DEFAULT, _)>
struct BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
: public BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl)
<Fun, BOOST_PP_CAT(has_member_function_named_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<Fun>::value
BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION_FINISH(), P) >
{};
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
#undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
#undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
#undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#endif //#if BOOST_PP_ITERATION() == BOOST_PP_ITERATION_FINISH()
#endif //!BOOST_PP_IS_ITERATING
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
//////////////////////////////////////////////////////////////////////////////
// sample.h
#if !defined(BOOST_PP_IS_ITERATING)
#ifndef BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED
#define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/detail/workaround.hpp>
#include <boost/intrusive/detail/preprocessor.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/static_assert.hpp>
#include <boost/move/move.hpp>
//Mark that we don't support 0 arg calls due to compiler ICE in GCC 3.4/4.0/4.1 and
//wrong SFINAE for GCC 4.2/4.3
#if defined(__GNUC__) && !defined(__clang__) && ((__GNUC__*100 + __GNUC_MINOR__*10) >= 340) && ((__GNUC__*100 + __GNUC_MINOR__*10) <= 430)
#define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED
#elif defined(BOOST_INTEL) && (BOOST_INTEL < 1200 )
#define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED
#endif
namespace boost_intrusive_has_member_function_callable_with {
struct dont_care
{
dont_care(...);
};
struct private_type
{
static private_type p;
private_type const &operator,(int) const;
};
typedef char yes_type; // sizeof(yes_type) == 1
struct no_type{ char dummy[2]; }; // sizeof(no_type) == 2
template<typename T>
no_type is_private_type(T const &);
yes_type is_private_type(private_type const &);
} //boost_intrusive_has_member_function_callable_with
#include <boost/intrusive/detail/config_end.hpp>
#endif //BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED
#else //!BOOST_PP_IS_ITERATING
#ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
#error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME not defined!"
#endif
#ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
#error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN not defined!"
#endif
#ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END not defined!"
#endif
#if BOOST_PP_ITERATION_START() != 0
#error "BOOST_PP_ITERATION_START() must be zero (0)"
#endif
#if BOOST_PP_ITERATION() == 0
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
template <typename Type>
class BOOST_PP_CAT(has_member_function_named_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
{
struct BaseMixin
{
void BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME();
};
struct Base : public ::boost::intrusive::detail::remove_cv<Type>::type, public BaseMixin { Base(); };
template <typename T, T t> class Helper{};
template <typename U>
static boost_intrusive_has_member_function_callable_with::no_type deduce
(U*, Helper<void (BaseMixin::*)(), &U::BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME>* = 0);
static boost_intrusive_has_member_function_callable_with::yes_type deduce(...);
public:
static const bool value =
sizeof(boost_intrusive_has_member_function_callable_with::yes_type) == sizeof(deduce((Base*)(0)));
};
#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
template<typename Fun, bool HasFunc
BOOST_PP_ENUM_TRAILING(BOOST_PP_ITERATION_FINISH(), BOOST_INTRUSIVE_PP_TEMPLATE_PARAM_VOID_DEFAULT, _)>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl);
//!
template<typename Fun BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION_FINISH(), class P)>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl)
<Fun, false BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION_FINISH(), P)>
{
static const bool value = false;
};
//!
#if !defined(_MSC_VER) || (_MSC_VER < 1600)
#if defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED)
template<typename Fun>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true BOOST_PP_ENUM_TRAILING(BOOST_PP_SUB(BOOST_PP_ITERATION_FINISH(), BOOST_PP_ITERATION()), BOOST_INTRUSIVE_PP_IDENTITY, void)>
{
//Mark that we don't support 0 arg calls due to compiler ICE in GCC 3.4/4.0/4.1 and
//wrong SFINAE for GCC 4.2/4.3
static const bool value = true;
};
#else //defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED)
//Special case for 0 args
template< class F
, std::size_t N =
sizeof((boost::move_detail::declval<F>().
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME (), 0))>
struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
{
boost_intrusive_has_member_function_callable_with::yes_type dummy;
BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int);
};
//For buggy compilers like MSVC 7.1+ ((F*)0)->func() does not
//SFINAE-out the zeroarg_checker_ instantiation but sizeof yields to 0.
template<class F>
struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<F, 0>
{
boost_intrusive_has_member_function_callable_with::no_type dummy;
BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int);
};
template<typename Fun>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true BOOST_PP_ENUM_TRAILING(BOOST_PP_SUB(BOOST_PP_ITERATION_FINISH(), BOOST_PP_ITERATION()), BOOST_INTRUSIVE_PP_IDENTITY, void)>
{
template<class U>
static BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<U>
Test(BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<U>*);
template <class U>
static boost_intrusive_has_member_function_callable_with::no_type Test(...);
static const bool value = sizeof(Test< Fun >(0))
== sizeof(boost_intrusive_has_member_function_callable_with::yes_type);
};
#endif //defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED)
#else //#if !defined(_MSC_VER) || (_MSC_VER < 1600)
template<typename Fun>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true BOOST_PP_ENUM_TRAILING(BOOST_PP_SUB(BOOST_PP_ITERATION_FINISH(), BOOST_PP_ITERATION()), BOOST_INTRUSIVE_PP_IDENTITY, void)>
{
template<class U>
static decltype( boost::move_detail::declval<Fun>().BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME()
, boost_intrusive_has_member_function_callable_with::yes_type())
Test(Fun*);
template<class U>
static boost_intrusive_has_member_function_callable_with::no_type Test(...);
static const bool value = sizeof(Test<Fun>(0))
== sizeof(boost_intrusive_has_member_function_callable_with::yes_type);
};
#endif //#if !defined(_MSC_VER) || (_MSC_VER < 1600)
#else //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
template<typename Fun, bool HasFunc, class ...Args>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl);
template<typename Fun, class ...Args>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, false, Args...>
{
static const bool value = false;
};
//Special case for 0 args
template< class F
, std::size_t N =
sizeof((boost::move_detail::declval<F>().
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME (), 0))>
struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
{
boost_intrusive_has_member_function_callable_with::yes_type dummy;
BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int);
};
//For buggy compilers like MSVC 7.1+ ((F*)0)->func() does not
//SFINAE-out the zeroarg_checker_ instantiation but sizeof yields to 0.
template<class F>
struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<F, 0>
{
boost_intrusive_has_member_function_callable_with::no_type dummy;
BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int);
};
template<typename Fun>
struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true>
{
#ifdef BOOST_MSVC
template<class U>
static decltype( boost::move_detail::declval<Fun>().BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME()
, boost_intrusive_has_member_function_callable_with::yes_type())
Test(Fun*);
#else
template<class U>
static BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
<U> Test(BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<U>*);
#endif
template <class U>
static boost_intrusive_has_member_function_callable_with::no_type Test(...);
static const bool value = sizeof(Test< Fun >(0))
== sizeof(boost_intrusive_has_member_function_callable_with::yes_type);
};
template<typename Fun, class ...DontCares>
struct BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )
: Fun
{
BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )();
using Fun::BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME;
boost_intrusive_has_member_function_callable_with::private_type
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
( DontCares...) const;
};
template<typename Fun, class ...Args>
struct BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl)
<Fun, true , Args...>
{
template<class T>
struct make_dontcare
{
typedef boost_intrusive_has_member_function_callable_with::dont_care type;
};
typedef BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )
<Fun, typename make_dontcare<Args>::type...> FunWrap;
static bool const value = (sizeof(boost_intrusive_has_member_function_callable_with::no_type) ==
sizeof(boost_intrusive_has_member_function_callable_with::is_private_type
( (::boost::move_detail::declval< FunWrap >().
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
( ::boost::move_detail::declval<Args>()... ), 0) )
)
);
};
template<typename Fun, class ...Args>
struct BOOST_PP_CAT( has_member_function_callable_with_
, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
: public BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_
, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
< Fun
, BOOST_PP_CAT( has_member_function_named_
, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )<Fun>::value
, Args... >
{};
#endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#else //BOOST_PP_ITERATION() == 0
#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
template<typename Fun>
struct BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION())
, BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME))
: Fun
{
BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION())
, BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME))();
using Fun::BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME;
boost_intrusive_has_member_function_callable_with::private_type
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
( BOOST_PP_ENUM(BOOST_PP_ITERATION()
, BOOST_INTRUSIVE_PP_IDENTITY
, boost_intrusive_has_member_function_callable_with::dont_care)) const;
};
template<typename Fun BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION(), class P)>
struct BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_
, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl)
<Fun, true
BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION(), P)
BOOST_PP_ENUM_TRAILING( BOOST_PP_SUB(BOOST_PP_ITERATION_FINISH(), BOOST_PP_ITERATION())
, BOOST_INTRUSIVE_PP_IDENTITY
, void)>
{
typedef BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION())
, BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME))<Fun>
FunWrap;
static bool const value =
(sizeof(boost_intrusive_has_member_function_callable_with::no_type) ==
sizeof(boost_intrusive_has_member_function_callable_with::is_private_type
( (boost::move_detail::declval<FunWrap>().
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
( BOOST_PP_ENUM( BOOST_PP_ITERATION(), BOOST_INTRUSIVE_PP_DECLVAL, _) ), 0
)
)
)
);
};
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
#endif //BOOST_PP_ITERATION() == 0
#if BOOST_PP_ITERATION() == BOOST_PP_ITERATION_FINISH()
#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
template<typename Fun
BOOST_PP_ENUM_TRAILING(BOOST_PP_ITERATION_FINISH(), BOOST_INTRUSIVE_PP_TEMPLATE_PARAM_VOID_DEFAULT, _)>
struct BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)
: public BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl)
<Fun, BOOST_PP_CAT(has_member_function_named_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)<Fun>::value
BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION_FINISH(), P) >
{};
BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING)
#undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME
#undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN
#undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END
#endif //#if BOOST_PP_ITERATION() == BOOST_PP_ITERATION_FINISH()
#endif //!BOOST_PP_IS_ITERATING

View File

@@ -1,292 +1,292 @@
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Pablo Halpern 2009. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTRUSIVE_ALLOCATOR_MEMORY_UTIL_HPP
#define BOOST_INTRUSIVE_ALLOCATOR_MEMORY_UTIL_HPP
#if (defined _MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/detail/workaround.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/intrusive/detail/preprocessor.hpp>
namespace boost {
namespace intrusive {
namespace detail {
template <typename T>
inline T* addressof(T& obj)
{
return static_cast<T*>
(static_cast<void*>
(const_cast<char*>
(&reinterpret_cast<const char&>(obj))
)
);
}
template <typename T> struct unvoid { typedef T type; };
template <> struct unvoid<void> { struct type { }; };
template <> struct unvoid<const void> { struct type { }; };
template <typename T> struct unvoid_ref { typedef T &type; };
template <> struct unvoid_ref<void> { struct type_impl { }; typedef type_impl & type; };
template <> struct unvoid_ref<const void> { struct type_impl { }; typedef type_impl & type; };
template <typename T>
struct LowPriorityConversion
{
// Convertible from T with user-defined-conversion rank.
LowPriorityConversion(const T&) { }
};
// Infrastructure for providing a default type for T::TNAME if absent.
#define BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(TNAME) \
template <typename T, typename DefaultType> \
struct boost_intrusive_default_type_ ## TNAME \
{ \
template <typename X> \
static char test(int, typename X::TNAME*); \
\
template <typename X> \
static int test(boost::intrusive::detail:: \
LowPriorityConversion<int>, void*); \
\
struct DefaultWrap { typedef DefaultType TNAME; }; \
\
static const bool value = (1 == sizeof(test<T>(0, 0))); \
\
typedef typename \
::boost::intrusive::detail::if_c \
<value, T, DefaultWrap>::type::TNAME type; \
}; \
\
template <typename T, typename DefaultType> \
struct boost_intrusive_eval_default_type_ ## TNAME \
{ \
template <typename X> \
static char test(int, typename X::TNAME*); \
\
template <typename X> \
static int test(boost::intrusive::detail:: \
LowPriorityConversion<int>, void*); \
\
struct DefaultWrap \
{ typedef typename DefaultType::type TNAME; }; \
\
static const bool value = (1 == sizeof(test<T>(0, 0))); \
\
typedef typename \
::boost::intrusive::detail::eval_if_c \
< value \
, ::boost::intrusive::detail::identity<T> \
, ::boost::intrusive::detail::identity<DefaultWrap> \
>::type::TNAME type; \
}; \
//
#define BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(INSTANTIATION_NS_PREFIX, T, TNAME, TIMPL) \
typename INSTANTIATION_NS_PREFIX \
boost_intrusive_default_type_ ## TNAME< T, TIMPL >::type \
//
#define BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_EVAL_DEFAULT(INSTANTIATION_NS_PREFIX, T, TNAME, TIMPL) \
typename INSTANTIATION_NS_PREFIX \
boost_intrusive_eval_default_type_ ## TNAME< T, TIMPL >::type \
//
}}} //namespace boost::intrusive::detail
#include "has_member_function_callable_with.hpp"
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME pointer_to
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME static_cast_from
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME const_cast_from
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME dynamic_cast_from
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
namespace boost {
namespace intrusive {
namespace detail {
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(element_type)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(difference_type)
//////////////////////
//struct first_param
//////////////////////
template <typename T> struct first_param
{ typedef void type; };
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <template <typename, typename...> class TemplateClass, typename T, typename... Args>
struct first_param< TemplateClass<T, Args...> >
{
typedef T type;
};
#else //C++03 compilers
#define BOOST_PP_LOCAL_MACRO(n) \
template < template <typename \
BOOST_PP_ENUM_TRAILING(n, BOOST_INTRUSIVE_PP_IDENTITY, typename) > \
class TemplateClass \
, typename T BOOST_PP_ENUM_TRAILING_PARAMS(n, class P)> \
struct first_param \
< TemplateClass<T BOOST_PP_ENUM_TRAILING_PARAMS(n, P)> > \
{ \
typedef T type; \
}; \
//
#define BOOST_PP_LOCAL_LIMITS (0, BOOST_INTRUSIVE_MAX_CONSTRUCTOR_PARAMETERS)
#include BOOST_PP_LOCAL_ITERATE()
#endif //!defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
///////////////////////////
//struct type_rebind_mode
///////////////////////////
template <typename Ptr, typename T>
struct type_has_rebind
{
template <typename X>
#if !defined (__SUNPRO_CC)
static char test(int, typename X::template rebind<T>*);
#else
static char test(int, typename X::rebind<T>*);
#endif
template <typename X>
static int test(boost::intrusive::detail::LowPriorityConversion<int>, void*);
static const bool value = (1 == sizeof(test<Ptr>(0, 0)));
};
template <typename Ptr, typename T>
struct type_has_rebind_other
{
template <typename X>
#if !defined (__SUNPRO_CC)
static char test(int, typename X::template rebind<T>::other*);
#else
static char test(int, typename X::rebind<T>::other*);
#endif
template <typename X>
static int test(boost::intrusive::detail::LowPriorityConversion<int>, void*);
static const bool value = (1 == sizeof(test<Ptr>(0, 0)));
};
template <typename Ptr, typename T>
struct type_rebind_mode
{
static const unsigned int rebind = (unsigned int)type_has_rebind<Ptr, T>::value;
static const unsigned int rebind_other = (unsigned int)type_has_rebind_other<Ptr, T>::value;
static const unsigned int mode = rebind + rebind*rebind_other;
};
////////////////////////
//struct type_rebinder
////////////////////////
template <typename Ptr, typename U, unsigned int RebindMode = type_rebind_mode<Ptr, U>::mode>
struct type_rebinder;
// Implementation of pointer_traits<Ptr>::rebind if Ptr has
// its own rebind::other type (C++03)
template <typename Ptr, typename U>
struct type_rebinder< Ptr, U, 2u >
{
typedef typename Ptr::template rebind<U>::other type;
};
// Implementation of pointer_traits<Ptr>::rebind if Ptr has
// its own rebind template.
template <typename Ptr, typename U>
struct type_rebinder< Ptr, U, 1u >
{
typedef typename Ptr::template rebind<U> type;
};
// Specialization of pointer_traits<Ptr>::rebind if Ptr does not
// have its own rebind template but has a the form Ptr<class T,
// OtherArgs>, where OtherArgs comprises zero or more type parameters.
// Many pointers fit this form, hence many pointers will get a
// reasonable default for rebind.
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <template <class, class...> class Ptr, typename T, class... Tn, class U>
struct type_rebinder<Ptr<T, Tn...>, U, 0u >
{
typedef Ptr<U, Tn...> type;
};
//Needed for non-conforming compilers like GCC 4.3
template <template <class> class Ptr, typename T, class U>
struct type_rebinder<Ptr<T>, U, 0u >
{
typedef Ptr<U> type;
};
#else //C++03 compilers
#define BOOST_PP_LOCAL_MACRO(n) \
template < template <typename \
BOOST_PP_ENUM_TRAILING(n, BOOST_INTRUSIVE_PP_IDENTITY, typename) > \
class Ptr \
, typename T BOOST_PP_ENUM_TRAILING_PARAMS(n, class P) \
, class U> \
struct type_rebinder \
< Ptr<T BOOST_PP_ENUM_TRAILING_PARAMS(n, P)>, U, 0u > \
{ \
typedef Ptr<U BOOST_PP_ENUM_TRAILING_PARAMS(n, P)> type; \
}; \
//
#define BOOST_PP_LOCAL_LIMITS (0, BOOST_INTRUSIVE_MAX_CONSTRUCTOR_PARAMETERS)
#include BOOST_PP_LOCAL_ITERATE()
#endif //!defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
} //namespace detail {
} //namespace intrusive {
} //namespace boost {
#include <boost/intrusive/detail/config_end.hpp>
#endif // ! defined(BOOST_INTRUSIVE_ALLOCATOR_MEMORY_UTIL_HPP)
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Pablo Halpern 2009. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTRUSIVE_ALLOCATOR_MEMORY_UTIL_HPP
#define BOOST_INTRUSIVE_ALLOCATOR_MEMORY_UTIL_HPP
#if (defined _MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/detail/workaround.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/intrusive/detail/preprocessor.hpp>
namespace boost {
namespace intrusive {
namespace detail {
template <typename T>
inline T* addressof(T& obj)
{
return static_cast<T*>
(static_cast<void*>
(const_cast<char*>
(&reinterpret_cast<const char&>(obj))
)
);
}
template <typename T> struct unvoid { typedef T type; };
template <> struct unvoid<void> { struct type { }; };
template <> struct unvoid<const void> { struct type { }; };
template <typename T> struct unvoid_ref { typedef T &type; };
template <> struct unvoid_ref<void> { struct type_impl { }; typedef type_impl & type; };
template <> struct unvoid_ref<const void> { struct type_impl { }; typedef type_impl & type; };
template <typename T>
struct LowPriorityConversion
{
// Convertible from T with user-defined-conversion rank.
LowPriorityConversion(const T&) { }
};
// Infrastructure for providing a default type for T::TNAME if absent.
#define BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(TNAME) \
template <typename T, typename DefaultType> \
struct boost_intrusive_default_type_ ## TNAME \
{ \
template <typename X> \
static char test(int, typename X::TNAME*); \
\
template <typename X> \
static int test(boost::intrusive::detail:: \
LowPriorityConversion<int>, void*); \
\
struct DefaultWrap { typedef DefaultType TNAME; }; \
\
static const bool value = (1 == sizeof(test<T>(0, 0))); \
\
typedef typename \
::boost::intrusive::detail::if_c \
<value, T, DefaultWrap>::type::TNAME type; \
}; \
\
template <typename T, typename DefaultType> \
struct boost_intrusive_eval_default_type_ ## TNAME \
{ \
template <typename X> \
static char test(int, typename X::TNAME*); \
\
template <typename X> \
static int test(boost::intrusive::detail:: \
LowPriorityConversion<int>, void*); \
\
struct DefaultWrap \
{ typedef typename DefaultType::type TNAME; }; \
\
static const bool value = (1 == sizeof(test<T>(0, 0))); \
\
typedef typename \
::boost::intrusive::detail::eval_if_c \
< value \
, ::boost::intrusive::detail::identity<T> \
, ::boost::intrusive::detail::identity<DefaultWrap> \
>::type::TNAME type; \
}; \
//
#define BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(INSTANTIATION_NS_PREFIX, T, TNAME, TIMPL) \
typename INSTANTIATION_NS_PREFIX \
boost_intrusive_default_type_ ## TNAME< T, TIMPL >::type \
//
#define BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_EVAL_DEFAULT(INSTANTIATION_NS_PREFIX, T, TNAME, TIMPL) \
typename INSTANTIATION_NS_PREFIX \
boost_intrusive_eval_default_type_ ## TNAME< T, TIMPL >::type \
//
}}} //namespace boost::intrusive::detail
#include "has_member_function_callable_with.hpp"
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME pointer_to
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME static_cast_from
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME const_cast_from
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME dynamic_cast_from
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail {
#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}}
#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, "has_member_function_callable_with.hpp"))
#include BOOST_PP_ITERATE()
namespace boost {
namespace intrusive {
namespace detail {
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(element_type)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(difference_type)
//////////////////////
//struct first_param
//////////////////////
template <typename T> struct first_param
{ typedef void type; };
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <template <typename, typename...> class TemplateClass, typename T, typename... Args>
struct first_param< TemplateClass<T, Args...> >
{
typedef T type;
};
#else //C++03 compilers
#define BOOST_PP_LOCAL_MACRO(n) \
template < template <typename \
BOOST_PP_ENUM_TRAILING(n, BOOST_INTRUSIVE_PP_IDENTITY, typename) > \
class TemplateClass \
, typename T BOOST_PP_ENUM_TRAILING_PARAMS(n, class P)> \
struct first_param \
< TemplateClass<T BOOST_PP_ENUM_TRAILING_PARAMS(n, P)> > \
{ \
typedef T type; \
}; \
//
#define BOOST_PP_LOCAL_LIMITS (0, BOOST_INTRUSIVE_MAX_CONSTRUCTOR_PARAMETERS)
#include BOOST_PP_LOCAL_ITERATE()
#endif //!defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
///////////////////////////
//struct type_rebind_mode
///////////////////////////
template <typename Ptr, typename T>
struct type_has_rebind
{
template <typename X>
#if !defined (__SUNPRO_CC)
static char test(int, typename X::template rebind<T>*);
#else
static char test(int, typename X::rebind<T>*);
#endif
template <typename X>
static int test(boost::intrusive::detail::LowPriorityConversion<int>, void*);
static const bool value = (1 == sizeof(test<Ptr>(0, 0)));
};
template <typename Ptr, typename T>
struct type_has_rebind_other
{
template <typename X>
#if !defined (__SUNPRO_CC)
static char test(int, typename X::template rebind<T>::other*);
#else
static char test(int, typename X::rebind<T>::other*);
#endif
template <typename X>
static int test(boost::intrusive::detail::LowPriorityConversion<int>, void*);
static const bool value = (1 == sizeof(test<Ptr>(0, 0)));
};
template <typename Ptr, typename T>
struct type_rebind_mode
{
static const unsigned int rebind = (unsigned int)type_has_rebind<Ptr, T>::value;
static const unsigned int rebind_other = (unsigned int)type_has_rebind_other<Ptr, T>::value;
static const unsigned int mode = rebind + rebind*rebind_other;
};
////////////////////////
//struct type_rebinder
////////////////////////
template <typename Ptr, typename U, unsigned int RebindMode = type_rebind_mode<Ptr, U>::mode>
struct type_rebinder;
// Implementation of pointer_traits<Ptr>::rebind if Ptr has
// its own rebind::other type (C++03)
template <typename Ptr, typename U>
struct type_rebinder< Ptr, U, 2u >
{
typedef typename Ptr::template rebind<U>::other type;
};
// Implementation of pointer_traits<Ptr>::rebind if Ptr has
// its own rebind template.
template <typename Ptr, typename U>
struct type_rebinder< Ptr, U, 1u >
{
typedef typename Ptr::template rebind<U> type;
};
// Specialization of pointer_traits<Ptr>::rebind if Ptr does not
// have its own rebind template but has a the form Ptr<class T,
// OtherArgs>, where OtherArgs comprises zero or more type parameters.
// Many pointers fit this form, hence many pointers will get a
// reasonable default for rebind.
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <template <class, class...> class Ptr, typename T, class... Tn, class U>
struct type_rebinder<Ptr<T, Tn...>, U, 0u >
{
typedef Ptr<U, Tn...> type;
};
//Needed for non-conforming compilers like GCC 4.3
template <template <class> class Ptr, typename T, class U>
struct type_rebinder<Ptr<T>, U, 0u >
{
typedef Ptr<U> type;
};
#else //C++03 compilers
#define BOOST_PP_LOCAL_MACRO(n) \
template < template <typename \
BOOST_PP_ENUM_TRAILING(n, BOOST_INTRUSIVE_PP_IDENTITY, typename) > \
class Ptr \
, typename T BOOST_PP_ENUM_TRAILING_PARAMS(n, class P) \
, class U> \
struct type_rebinder \
< Ptr<T BOOST_PP_ENUM_TRAILING_PARAMS(n, P)>, U, 0u > \
{ \
typedef Ptr<U BOOST_PP_ENUM_TRAILING_PARAMS(n, P)> type; \
}; \
//
#define BOOST_PP_LOCAL_LIMITS (0, BOOST_INTRUSIVE_MAX_CONSTRUCTOR_PARAMETERS)
#include BOOST_PP_LOCAL_ITERATE()
#endif //!defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
} //namespace detail {
} //namespace intrusive {
} //namespace boost {
#include <boost/intrusive/detail/config_end.hpp>
#endif // ! defined(BOOST_INTRUSIVE_ALLOCATOR_MEMORY_UTIL_HPP)

View File

@@ -1,93 +1,93 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <Gui/Application.h>
#include <Gui/WidgetFactory.h>
#include <Gui/Language/Translator.h>
#include "ViewProviderPath.h"
#include "DlgSettingsPathColor.h"
#include "ViewProviderPathCompound.h"
#include "ViewProviderPathShape.h"
#include "ViewProviderArea.h"
// use a different name to CreateCommand()
void CreatePathCommands(void);
void loadPathResource()
{
// add resources and reloads the translators
Q_INIT_RESOURCE(Path);
Gui::Translator::instance()->refresh();
}
namespace PathGui {
extern PyObject* initModule();
}
/* Python entry */
PyMOD_INIT_FUNC(PathGui)
{
if (!Gui::Application::Instance) {
PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application.");
PyMOD_Return(0);
}
try {
Base::Interpreter().runString("import PartGui");
Base::Interpreter().runString("import Path");
}
catch(const Base::Exception& e) {
PyErr_SetString(PyExc_ImportError, e.what());
PyMOD_Return(0);
}
PyObject* mod = PathGui::initModule();
Base::Console().Log("Loading GUI of Path module... done\n");
// instantiating the commands
CreatePathCommands();
// addition objects
PathGui::ViewProviderPath ::init();
PathGui::ViewProviderPathCompound ::init();
PathGui::ViewProviderPathCompoundPython ::init();
PathGui::ViewProviderPathShape ::init();
PathGui::ViewProviderPathPython ::init();
PathGui::ViewProviderArea ::init();
PathGui::ViewProviderAreaPython ::init();
PathGui::ViewProviderAreaView ::init();
PathGui::ViewProviderAreaViewPython ::init();
// add resources and reloads the translators
loadPathResource();
// register preferences pages
new Gui::PrefPageProducer<PathGui::DlgSettingsPathColor> ("Path");
PyMOD_Return(mod);
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <Gui/Application.h>
#include <Gui/WidgetFactory.h>
#include <Gui/Language/Translator.h>
#include "ViewProviderPath.h"
#include "DlgSettingsPathColor.h"
#include "ViewProviderPathCompound.h"
#include "ViewProviderPathShape.h"
#include "ViewProviderArea.h"
// use a different name to CreateCommand()
void CreatePathCommands(void);
void loadPathResource()
{
// add resources and reloads the translators
Q_INIT_RESOURCE(Path);
Gui::Translator::instance()->refresh();
}
namespace PathGui {
extern PyObject* initModule();
}
/* Python entry */
PyMOD_INIT_FUNC(PathGui)
{
if (!Gui::Application::Instance) {
PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application.");
PyMOD_Return(0);
}
try {
Base::Interpreter().runString("import PartGui");
Base::Interpreter().runString("import Path");
}
catch(const Base::Exception& e) {
PyErr_SetString(PyExc_ImportError, e.what());
PyMOD_Return(0);
}
PyObject* mod = PathGui::initModule();
Base::Console().Log("Loading GUI of Path module... done\n");
// instantiating the commands
CreatePathCommands();
// addition objects
PathGui::ViewProviderPath ::init();
PathGui::ViewProviderPathCompound ::init();
PathGui::ViewProviderPathCompoundPython ::init();
PathGui::ViewProviderPathShape ::init();
PathGui::ViewProviderPathPython ::init();
PathGui::ViewProviderArea ::init();
PathGui::ViewProviderAreaPython ::init();
PathGui::ViewProviderAreaView ::init();
PathGui::ViewProviderAreaViewPython ::init();
// add resources and reloads the translators
loadPathResource();
// register preferences pages
new Gui::PrefPageProducer<PathGui::DlgSettingsPathColor> ("Path");
PyMOD_Return(mod);
}

View File

@@ -1,293 +1,293 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include <CXX/Extensions.hxx>
#include <CXX/Objects.hxx>
#include <QDir>
#include <QFileInfo>
#include <Base/Console.h>
#include <Base/VectorPy.h>
#include <Base/FileInfo.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObjectPy.h>
#include <Gui/Command.h>
#include <Gui/WaitCursor.h>
#include "ViewProviderPath.h"
#include "DlgProcessorChooser.h"
#include "ui_DlgProcessorChooser.h"
namespace PathGui {
class Module : public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("PathGui")
{
add_varargs_method("open",&Module::open,
"open(filename): Opens a GCode file as a new document"
);
add_varargs_method("insert",&Module::insert,
"insert(filename,docname): Imports a given GCode file into the given document"
);
add_varargs_method("export",&Module::exporter,
"export(objectslist,filename): Exports a given list of Path objects to a GCode file"
);
initialize("This module is the PathGui module."); // register with Python
}
virtual ~Module() {}
private:
Py::Object open(const Py::Tuple& args)
{
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Base::FileInfo fi(EncodedName);
if (!fi.exists())
throw Py::RuntimeError("File not found");
Gui::WaitCursor wc;
wc.restoreCursor();
try {
std::string path = App::GetApplication().getHomePath();
path += "Mod/Path/PathScripts/post/";
QDir dir1(QString::fromUtf8(path.c_str()), QString::fromLatin1("*_pre.py"));
std::string cMacroPath = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
->GetASCII("MacroPath",App::Application::getUserMacroDir().c_str());
QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QString::fromLatin1("*_pre.py"));
QFileInfoList list = dir1.entryInfoList();
list << dir2.entryInfoList();
std::vector<std::string> scripts;
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
scripts.push_back(fileInfo.baseName().toStdString());
}
std::string processor;
PathGui::DlgProcessorChooser Dlg(scripts);
if (Dlg.exec() != QDialog::Accepted) {
return Py::None();
}
processor = Dlg.getProcessor();
std::ostringstream pre;
std::ostringstream cmd;
if (processor.empty()) {
App::Document *pcDoc = App::GetApplication().newDocument("Unnamed");
Gui::Command::runCommand(Gui::Command::Gui,"import Path");
cmd << "Path.read(\"" << EncodedName << "\",\"" << pcDoc->getName() << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
} else {
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.baseName().toStdString() == processor) {
if (fileInfo.absoluteFilePath().contains(QString::fromLatin1("PathScripts"))) {
pre << "from PathScripts.post import " << processor;
} else {
pre << "import " << processor;
}
Gui::Command::runCommand(Gui::Command::Gui,pre.str().c_str());
cmd << processor << ".open(\"" << EncodedName << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
}
}
}
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
Py::Object insert(const Py::Tuple& args)
{
char* Name;
char* DocName=0;
if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Base::FileInfo fi(EncodedName);
if (!fi.exists())
throw Py::RuntimeError("File not found");
Gui::WaitCursor wc;
wc.restoreCursor();
try {
std::string path = App::GetApplication().getHomePath();
path += "Mod/Path/PathScripts/post/";
QDir dir1(QString::fromUtf8(path.c_str()), QString::fromLatin1("*_pre.py"));
std::string cMacroPath = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
->GetASCII("MacroPath",App::Application::getUserMacroDir().c_str());
QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QString::fromLatin1("*_pre.py"));
QFileInfoList list = dir1.entryInfoList();
list << dir2.entryInfoList();
std::vector<std::string> scripts;
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
scripts.push_back(fileInfo.baseName().toStdString());
}
std::string processor;
PathGui::DlgProcessorChooser Dlg(scripts);
if (Dlg.exec() != QDialog::Accepted) {
return Py::None();
}
processor = Dlg.getProcessor();
App::Document *pcDoc = 0;
if (DocName)
pcDoc = App::GetApplication().getDocument(DocName);
else
pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc) {
pcDoc = App::GetApplication().newDocument(DocName);
}
std::ostringstream pre;
std::ostringstream cmd;
if (processor.empty()) {
Gui::Command::runCommand(Gui::Command::Gui,"import Path");
cmd << "Path.read(\"" << EncodedName << "\",\"" << pcDoc->getName() << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
} else {
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.baseName().toStdString() == processor) {
if (fileInfo.absoluteFilePath().contains(QString::fromLatin1("PathScripts"))) {
pre << "from PathScripts.post import " << processor;
} else {
pre << "import " << processor;
}
Gui::Command::runCommand(Gui::Command::Gui,pre.str().c_str());
cmd << processor << ".insert(\"" << EncodedName << "\",\"" << pcDoc->getName() << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
}
}
}
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
Py::Object exporter(const Py::Tuple& args)
{
PyObject* object;
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "Oet",&object,"utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Gui::WaitCursor wc;
wc.restoreCursor();
try {
Py::Sequence objlist(object);
if (objlist.size() == 0)
throw Py::RuntimeError("No object to export");
std::string path = App::GetApplication().getHomePath();
path += "Mod/Path/PathScripts/post/";
QDir dir1(QString::fromUtf8(path.c_str()), QString::fromLatin1("*_post.py"));
std::string cMacroPath = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
->GetASCII("MacroPath",App::Application::getUserMacroDir().c_str());
QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QString::fromLatin1("*_post.py"));
QFileInfoList list = dir1.entryInfoList();
list << dir2.entryInfoList();
std::vector<std::string> scripts;
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
scripts.push_back(fileInfo.baseName().toStdString());
}
PathGui::DlgProcessorChooser Dlg(scripts, true);
if (Dlg.exec() != QDialog::Accepted) {
return Py::None();
}
std::string processor = Dlg.getProcessor();
std::string arguments = Dlg.getArguments();
std::ostringstream pre;
std::ostringstream cmd;
if (processor.empty()) {
if (objlist.size() > 1) {
throw Py::RuntimeError("Cannot export more than one object without using a post script");
}
PyObject* item = objlist[0].ptr();
if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
App::Document* doc = obj->getDocument();
Gui::Command::runCommand(Gui::Command::Gui,"import Path");
cmd << "Path.write(FreeCAD.getDocument(\"" << doc->getName() << "\").getObject(\"" << obj->getNameInDocument() << "\"),\"" << EncodedName << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
} else {
return Py::None();
}
} else {
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.baseName().toStdString() == processor) {
if (fileInfo.absoluteFilePath().contains(QString::fromLatin1("PathScripts"))) {
pre << "from PathScripts.post import " << processor;
} else {
pre << "import " << processor;
}
Gui::Command::runCommand(Gui::Command::Gui,pre.str().c_str());
cmd << processor << ".export(__objs__,\"" << EncodedName << "\",\"" << arguments << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
}
}
}
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
};
PyObject* initModule()
{
return (new Module)->module().ptr();
}
} // namespace PathGui
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#endif
#include <CXX/Extensions.hxx>
#include <CXX/Objects.hxx>
#include <QDir>
#include <QFileInfo>
#include <Base/Console.h>
#include <Base/VectorPy.h>
#include <Base/FileInfo.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObjectPy.h>
#include <Gui/Command.h>
#include <Gui/WaitCursor.h>
#include "ViewProviderPath.h"
#include "DlgProcessorChooser.h"
#include "ui_DlgProcessorChooser.h"
namespace PathGui {
class Module : public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("PathGui")
{
add_varargs_method("open",&Module::open,
"open(filename): Opens a GCode file as a new document"
);
add_varargs_method("insert",&Module::insert,
"insert(filename,docname): Imports a given GCode file into the given document"
);
add_varargs_method("export",&Module::exporter,
"export(objectslist,filename): Exports a given list of Path objects to a GCode file"
);
initialize("This module is the PathGui module."); // register with Python
}
virtual ~Module() {}
private:
Py::Object open(const Py::Tuple& args)
{
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Base::FileInfo fi(EncodedName);
if (!fi.exists())
throw Py::RuntimeError("File not found");
Gui::WaitCursor wc;
wc.restoreCursor();
try {
std::string path = App::GetApplication().getHomePath();
path += "Mod/Path/PathScripts/post/";
QDir dir1(QString::fromUtf8(path.c_str()), QString::fromLatin1("*_pre.py"));
std::string cMacroPath = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
->GetASCII("MacroPath",App::Application::getUserMacroDir().c_str());
QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QString::fromLatin1("*_pre.py"));
QFileInfoList list = dir1.entryInfoList();
list << dir2.entryInfoList();
std::vector<std::string> scripts;
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
scripts.push_back(fileInfo.baseName().toStdString());
}
std::string processor;
PathGui::DlgProcessorChooser Dlg(scripts);
if (Dlg.exec() != QDialog::Accepted) {
return Py::None();
}
processor = Dlg.getProcessor();
std::ostringstream pre;
std::ostringstream cmd;
if (processor.empty()) {
App::Document *pcDoc = App::GetApplication().newDocument("Unnamed");
Gui::Command::runCommand(Gui::Command::Gui,"import Path");
cmd << "Path.read(\"" << EncodedName << "\",\"" << pcDoc->getName() << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
} else {
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.baseName().toStdString() == processor) {
if (fileInfo.absoluteFilePath().contains(QString::fromLatin1("PathScripts"))) {
pre << "from PathScripts.post import " << processor;
} else {
pre << "import " << processor;
}
Gui::Command::runCommand(Gui::Command::Gui,pre.str().c_str());
cmd << processor << ".open(\"" << EncodedName << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
}
}
}
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
Py::Object insert(const Py::Tuple& args)
{
char* Name;
char* DocName=0;
if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Base::FileInfo fi(EncodedName);
if (!fi.exists())
throw Py::RuntimeError("File not found");
Gui::WaitCursor wc;
wc.restoreCursor();
try {
std::string path = App::GetApplication().getHomePath();
path += "Mod/Path/PathScripts/post/";
QDir dir1(QString::fromUtf8(path.c_str()), QString::fromLatin1("*_pre.py"));
std::string cMacroPath = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
->GetASCII("MacroPath",App::Application::getUserMacroDir().c_str());
QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QString::fromLatin1("*_pre.py"));
QFileInfoList list = dir1.entryInfoList();
list << dir2.entryInfoList();
std::vector<std::string> scripts;
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
scripts.push_back(fileInfo.baseName().toStdString());
}
std::string processor;
PathGui::DlgProcessorChooser Dlg(scripts);
if (Dlg.exec() != QDialog::Accepted) {
return Py::None();
}
processor = Dlg.getProcessor();
App::Document *pcDoc = 0;
if (DocName)
pcDoc = App::GetApplication().getDocument(DocName);
else
pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc) {
pcDoc = App::GetApplication().newDocument(DocName);
}
std::ostringstream pre;
std::ostringstream cmd;
if (processor.empty()) {
Gui::Command::runCommand(Gui::Command::Gui,"import Path");
cmd << "Path.read(\"" << EncodedName << "\",\"" << pcDoc->getName() << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
} else {
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.baseName().toStdString() == processor) {
if (fileInfo.absoluteFilePath().contains(QString::fromLatin1("PathScripts"))) {
pre << "from PathScripts.post import " << processor;
} else {
pre << "import " << processor;
}
Gui::Command::runCommand(Gui::Command::Gui,pre.str().c_str());
cmd << processor << ".insert(\"" << EncodedName << "\",\"" << pcDoc->getName() << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
}
}
}
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
Py::Object exporter(const Py::Tuple& args)
{
PyObject* object;
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "Oet",&object,"utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
Gui::WaitCursor wc;
wc.restoreCursor();
try {
Py::Sequence objlist(object);
if (objlist.size() == 0)
throw Py::RuntimeError("No object to export");
std::string path = App::GetApplication().getHomePath();
path += "Mod/Path/PathScripts/post/";
QDir dir1(QString::fromUtf8(path.c_str()), QString::fromLatin1("*_post.py"));
std::string cMacroPath = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
->GetASCII("MacroPath",App::Application::getUserMacroDir().c_str());
QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QString::fromLatin1("*_post.py"));
QFileInfoList list = dir1.entryInfoList();
list << dir2.entryInfoList();
std::vector<std::string> scripts;
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
scripts.push_back(fileInfo.baseName().toStdString());
}
PathGui::DlgProcessorChooser Dlg(scripts, true);
if (Dlg.exec() != QDialog::Accepted) {
return Py::None();
}
std::string processor = Dlg.getProcessor();
std::string arguments = Dlg.getArguments();
std::ostringstream pre;
std::ostringstream cmd;
if (processor.empty()) {
if (objlist.size() > 1) {
throw Py::RuntimeError("Cannot export more than one object without using a post script");
}
PyObject* item = objlist[0].ptr();
if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
App::Document* doc = obj->getDocument();
Gui::Command::runCommand(Gui::Command::Gui,"import Path");
cmd << "Path.write(FreeCAD.getDocument(\"" << doc->getName() << "\").getObject(\"" << obj->getNameInDocument() << "\"),\"" << EncodedName << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
} else {
return Py::None();
}
} else {
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.baseName().toStdString() == processor) {
if (fileInfo.absoluteFilePath().contains(QString::fromLatin1("PathScripts"))) {
pre << "from PathScripts.post import " << processor;
} else {
pre << "import " << processor;
}
Gui::Command::runCommand(Gui::Command::Gui,pre.str().c_str());
cmd << processor << ".export(__objs__,\"" << EncodedName << "\",\"" << arguments << "\")";
Gui::Command::runCommand(Gui::Command::Gui,cmd.str().c_str());
}
}
}
}
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
return Py::None();
}
};
PyObject* initModule()
{
return (new Module)->module().ptr();
}
} // namespace PathGui

View File

@@ -1,348 +1,348 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <TopExp_Explorer.hxx>
#endif
#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/MainWindow.h>
#include <Gui/Command.h>
#include <Gui/Selection.h>
#include <Gui/SelectionFilter.h>
#include <Gui/Document.h>
#include <Gui/Control.h>
#include <Mod/Path/App/FeaturePath.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include <Mod/Path/App/FeaturePathShape.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Path/App/FeatureArea.h>
// Path Area #####################################################################################################
DEF_STD_CMD_A(CmdPathArea)
CmdPathArea::CmdPathArea()
:Command("Path_Area")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("Area");
sToolTipText = QT_TR_NOOP("Creates a feature area from selected objects");
sWhatsThis = "Path_Area";
sStatusTip = sToolTipText;
sPixmap = "Path-Area";
}
void CmdPathArea::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::list<std::string> cmds;
std::ostringstream sources;
std::string areaName;
bool addView = true;
for(const Gui::SelectionObject &selObj :
getSelection().getSelectionEx(NULL, Part::Feature::getClassTypeId()))
{
const Part::Feature *pcObj = static_cast<const Part::Feature*>(selObj.getObject());
const std::vector<std::string> &subnames = selObj.getSubNames();
if(addView && areaName.size()) addView = false;
if(subnames.empty()) {
if(addView && pcObj->getTypeId().isDerivedFrom(Path::FeatureArea::getClassTypeId()))
areaName = pcObj->getNameInDocument();
sources << "FreeCAD.activeDocument()." << pcObj->getNameInDocument() << ",";
continue;
}
for(const std::string &name : subnames) {
if(name.compare(0,4,"Face") && name.compare(0,4,"Edge")) {
Base::Console().Error("Selected shape is not 2D\n");
return;
}
std::ostringstream subname;
subname << pcObj->getNameInDocument() << '_' << name;
std::string sub_fname = getUniqueObjectName(subname.str().c_str());
std::ostringstream cmd;
cmd << "FreeCAD.activeDocument().addObject('Part::Feature','" << sub_fname <<
"').Shape = PathCommands.findShape(FreeCAD.activeDocument()." <<
pcObj->getNameInDocument() << ".Shape,'" << name << "'";
if(!name.compare(0,4,"Edge"))
cmd << ",'Wires'";
cmd << ')';
cmds.push_back(cmd.str());
sources << "FreeCAD.activeDocument()." << sub_fname << ",";
}
}
if(addView && areaName.size()) {
std::string FeatName = getUniqueObjectName("FeatureAreaView");
openCommand("Create Path Area View");
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureAreaView','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Source = FreeCAD.activeDocument().%s",
FeatName.c_str(),areaName.c_str());
commitCommand();
updateActive();
return;
}
std::string FeatName = getUniqueObjectName("FeatureArea");
openCommand("Create Path Area");
doCommand(Doc,"import PathCommands");
for(const std::string &cmd : cmds)
doCommand(Doc,"%s", cmd.c_str());
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureArea','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Sources = [ %s ]",FeatName.c_str(),sources.str().c_str());
commitCommand();
updateActive();
}
bool CmdPathArea::isActive(void)
{
return hasActiveDocument();
}
DEF_STD_CMD_A(CmdPathAreaWorkplane)
CmdPathAreaWorkplane::CmdPathAreaWorkplane()
:Command("Path_Area_Workplane")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("Area workplane");
sToolTipText = QT_TR_NOOP("Select a workplane for a FeatureArea");
sWhatsThis = "Path_Area_Workplane";
sStatusTip = sToolTipText;
sPixmap = "Path-Area-Workplane";
}
void CmdPathAreaWorkplane::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::string areaName;
std::string planeSubname;
std::string planeName;
for(Gui::SelectionObject &selObj :
getSelection().getSelectionEx(NULL, Part::Feature::getClassTypeId()))
{
const std::vector<std::string> &subnames = selObj.getSubNames();
if(subnames.size()>1) {
Base::Console().Error("Please select one sub shape object for plane only\n");
return;
}
const Part::Feature *pcObj = static_cast<Part::Feature*>(selObj.getObject());
if(subnames.empty()) {
if(pcObj->getTypeId().isDerivedFrom(Path::FeatureArea::getClassTypeId())) {
if(areaName.size()){
Base::Console().Error("Please select one FeatureArea only\n");
return;
}
areaName = pcObj->getNameInDocument();
continue;
}
for (TopExp_Explorer it(pcObj->Shape.getShape().getShape(), TopAbs_SHELL); it.More(); it.Next()) {
Base::Console().Error("Selected shape is not 2D\n");
return;
}
}
if(planeName.size()){
Base::Console().Error("Please select one shape object for plane only\n");
return;
}else{
planeSubname = planeName = pcObj->getNameInDocument();
planeSubname += ".Shape";
}
for(const std::string &name : subnames) {
if(name.compare(0,4,"Face") && name.compare(0,4,"Edge")) {
Base::Console().Error("Selected shape is not 2D\n");
return;
}
std::ostringstream subname;
subname << planeSubname << ",'" << name << "','Wires'";
planeSubname = subname.str();
}
}
if(areaName.empty()) {
Base::Console().Error("Please select one FeatureArea\n");
return;
}
if(planeName.empty()) {
Base::Console().Error("Please select one shape object\n");
return;
}
openCommand("Select Workplane for Path Area");
doCommand(Doc,"import PathCommands");
doCommand(Doc,"FreeCAD.activeDocument().%s.WorkPlane = PathCommands.findShape("
"FreeCAD.activeDocument().%s)", areaName.c_str(),planeSubname.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.ViewObject.Visibility = True",areaName.c_str());
commitCommand();
updateActive();
}
bool CmdPathAreaWorkplane::isActive(void)
{
return !getSelection().getSelectionEx(NULL, Path::FeatureArea::getClassTypeId()).empty();
}
// Path compound #####################################################################################################
DEF_STD_CMD_A(CmdPathCompound)
CmdPathCompound::CmdPathCompound()
:Command("Path_Compound")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("Compound");
sToolTipText = QT_TR_NOOP("Creates a compound from selected paths");
sWhatsThis = "Path_Compound";
sStatusTip = sToolTipText;
sPixmap = "Path-Compound";
}
void CmdPathCompound::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
if (Sel.size() > 0) {
std::ostringstream cmd;
cmd << "[";
Path::Feature *pcPathObject;
for (std::vector<Gui::SelectionSingleton::SelObj>::const_iterator it=Sel.begin();it!=Sel.end();++it) {
if ((*it).pObject->getTypeId().isDerivedFrom(Path::Feature::getClassTypeId())) {
pcPathObject = static_cast<Path::Feature*>((*it).pObject);
cmd << "FreeCAD.activeDocument()." << pcPathObject->getNameInDocument() << ",";
} else {
Base::Console().Error("Only Path objects must be selected before running this command\n");
return;
}
}
cmd << "]";
std::string FeatName = getUniqueObjectName("PathCompound");
openCommand("Create Path Compound");
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureCompound','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Group = %s",FeatName.c_str(),cmd.str().c_str());
commitCommand();
updateActive();
} else {
Base::Console().Error("At least one Path object must be selected\n");
return;
}
}
bool CmdPathCompound::isActive(void)
{
return hasActiveDocument();
}
// Path Shape #####################################################################################################
DEF_STD_CMD_A(CmdPathShape)
CmdPathShape::CmdPathShape()
:Command("Path_Shape")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("From Shape");
sToolTipText = QT_TR_NOOP("Creates a path from a selected shape");
sWhatsThis = "Path_Shape";
sStatusTip = sToolTipText;
sPixmap = "Path-Shape";
}
void CmdPathShape::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::list<std::string> cmds;
std::ostringstream sources;
for(const Gui::SelectionObject &selObj :
getSelection().getSelectionEx(NULL, Part::Feature::getClassTypeId()))
{
const Part::Feature *pcObj = static_cast<const Part::Feature*>(selObj.getObject());
const std::vector<std::string> &subnames = selObj.getSubNames();
if(subnames.empty()) {
sources << "FreeCAD.activeDocument()." << pcObj->getNameInDocument() << ",";
continue;
}
for(const std::string &name : subnames) {
if(name.compare(0,4,"Face") && name.compare(0,4,"Edge")) {
Base::Console().Warning("Ignored shape %s %s\n",
pcObj->getNameInDocument(), name.c_str());
continue;
}
std::ostringstream subname;
subname << pcObj->getNameInDocument() << '_' << name;
std::string sub_fname = getUniqueObjectName(subname.str().c_str());
std::ostringstream cmd;
cmd << "FreeCAD.activeDocument().addObject('Part::Feature','" << sub_fname <<
"').Shape = PathCommands.findShape(FreeCAD.activeDocument()." <<
pcObj->getNameInDocument() << ".Shape,'" << name << "'";
if(!name.compare(0,4,"Edge"))
cmd << ",'Wires'";
cmd << ')';
cmds.push_back(cmd.str());
sources << "FreeCAD.activeDocument()." << sub_fname << ",";
}
}
std::string FeatName = getUniqueObjectName("PathShape");
openCommand("Create Path Shape");
doCommand(Doc,"import PathCommands");
for(const std::string &cmd : cmds)
doCommand(Doc, "%s", cmd.c_str());
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureShape','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Sources = [ %s ]",FeatName.c_str(),sources.str().c_str());
commitCommand();
updateActive();
}
bool CmdPathShape::isActive(void)
{
return hasActiveDocument();
}
void CreatePathCommands(void)
{
Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
rcCmdMgr.addCommand(new CmdPathCompound());
rcCmdMgr.addCommand(new CmdPathShape());
rcCmdMgr.addCommand(new CmdPathArea());
rcCmdMgr.addCommand(new CmdPathAreaWorkplane());
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <TopExp_Explorer.hxx>
#endif
#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/MainWindow.h>
#include <Gui/Command.h>
#include <Gui/Selection.h>
#include <Gui/SelectionFilter.h>
#include <Gui/Document.h>
#include <Gui/Control.h>
#include <Mod/Path/App/FeaturePath.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include <Mod/Path/App/FeaturePathShape.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Path/App/FeatureArea.h>
// Path Area #####################################################################################################
DEF_STD_CMD_A(CmdPathArea)
CmdPathArea::CmdPathArea()
:Command("Path_Area")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("Area");
sToolTipText = QT_TR_NOOP("Creates a feature area from selected objects");
sWhatsThis = "Path_Area";
sStatusTip = sToolTipText;
sPixmap = "Path-Area";
}
void CmdPathArea::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::list<std::string> cmds;
std::ostringstream sources;
std::string areaName;
bool addView = true;
for(const Gui::SelectionObject &selObj :
getSelection().getSelectionEx(NULL, Part::Feature::getClassTypeId()))
{
const Part::Feature *pcObj = static_cast<const Part::Feature*>(selObj.getObject());
const std::vector<std::string> &subnames = selObj.getSubNames();
if(addView && areaName.size()) addView = false;
if(subnames.empty()) {
if(addView && pcObj->getTypeId().isDerivedFrom(Path::FeatureArea::getClassTypeId()))
areaName = pcObj->getNameInDocument();
sources << "FreeCAD.activeDocument()." << pcObj->getNameInDocument() << ",";
continue;
}
for(const std::string &name : subnames) {
if(name.compare(0,4,"Face") && name.compare(0,4,"Edge")) {
Base::Console().Error("Selected shape is not 2D\n");
return;
}
std::ostringstream subname;
subname << pcObj->getNameInDocument() << '_' << name;
std::string sub_fname = getUniqueObjectName(subname.str().c_str());
std::ostringstream cmd;
cmd << "FreeCAD.activeDocument().addObject('Part::Feature','" << sub_fname <<
"').Shape = PathCommands.findShape(FreeCAD.activeDocument()." <<
pcObj->getNameInDocument() << ".Shape,'" << name << "'";
if(!name.compare(0,4,"Edge"))
cmd << ",'Wires'";
cmd << ')';
cmds.push_back(cmd.str());
sources << "FreeCAD.activeDocument()." << sub_fname << ",";
}
}
if(addView && areaName.size()) {
std::string FeatName = getUniqueObjectName("FeatureAreaView");
openCommand("Create Path Area View");
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureAreaView','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Source = FreeCAD.activeDocument().%s",
FeatName.c_str(),areaName.c_str());
commitCommand();
updateActive();
return;
}
std::string FeatName = getUniqueObjectName("FeatureArea");
openCommand("Create Path Area");
doCommand(Doc,"import PathCommands");
for(const std::string &cmd : cmds)
doCommand(Doc,"%s", cmd.c_str());
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureArea','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Sources = [ %s ]",FeatName.c_str(),sources.str().c_str());
commitCommand();
updateActive();
}
bool CmdPathArea::isActive(void)
{
return hasActiveDocument();
}
DEF_STD_CMD_A(CmdPathAreaWorkplane)
CmdPathAreaWorkplane::CmdPathAreaWorkplane()
:Command("Path_Area_Workplane")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("Area workplane");
sToolTipText = QT_TR_NOOP("Select a workplane for a FeatureArea");
sWhatsThis = "Path_Area_Workplane";
sStatusTip = sToolTipText;
sPixmap = "Path-Area-Workplane";
}
void CmdPathAreaWorkplane::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::string areaName;
std::string planeSubname;
std::string planeName;
for(Gui::SelectionObject &selObj :
getSelection().getSelectionEx(NULL, Part::Feature::getClassTypeId()))
{
const std::vector<std::string> &subnames = selObj.getSubNames();
if(subnames.size()>1) {
Base::Console().Error("Please select one sub shape object for plane only\n");
return;
}
const Part::Feature *pcObj = static_cast<Part::Feature*>(selObj.getObject());
if(subnames.empty()) {
if(pcObj->getTypeId().isDerivedFrom(Path::FeatureArea::getClassTypeId())) {
if(areaName.size()){
Base::Console().Error("Please select one FeatureArea only\n");
return;
}
areaName = pcObj->getNameInDocument();
continue;
}
for (TopExp_Explorer it(pcObj->Shape.getShape().getShape(), TopAbs_SHELL); it.More(); it.Next()) {
Base::Console().Error("Selected shape is not 2D\n");
return;
}
}
if(planeName.size()){
Base::Console().Error("Please select one shape object for plane only\n");
return;
}else{
planeSubname = planeName = pcObj->getNameInDocument();
planeSubname += ".Shape";
}
for(const std::string &name : subnames) {
if(name.compare(0,4,"Face") && name.compare(0,4,"Edge")) {
Base::Console().Error("Selected shape is not 2D\n");
return;
}
std::ostringstream subname;
subname << planeSubname << ",'" << name << "','Wires'";
planeSubname = subname.str();
}
}
if(areaName.empty()) {
Base::Console().Error("Please select one FeatureArea\n");
return;
}
if(planeName.empty()) {
Base::Console().Error("Please select one shape object\n");
return;
}
openCommand("Select Workplane for Path Area");
doCommand(Doc,"import PathCommands");
doCommand(Doc,"FreeCAD.activeDocument().%s.WorkPlane = PathCommands.findShape("
"FreeCAD.activeDocument().%s)", areaName.c_str(),planeSubname.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.ViewObject.Visibility = True",areaName.c_str());
commitCommand();
updateActive();
}
bool CmdPathAreaWorkplane::isActive(void)
{
return !getSelection().getSelectionEx(NULL, Path::FeatureArea::getClassTypeId()).empty();
}
// Path compound #####################################################################################################
DEF_STD_CMD_A(CmdPathCompound)
CmdPathCompound::CmdPathCompound()
:Command("Path_Compound")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("Compound");
sToolTipText = QT_TR_NOOP("Creates a compound from selected paths");
sWhatsThis = "Path_Compound";
sStatusTip = sToolTipText;
sPixmap = "Path-Compound";
}
void CmdPathCompound::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
if (Sel.size() > 0) {
std::ostringstream cmd;
cmd << "[";
Path::Feature *pcPathObject;
for (std::vector<Gui::SelectionSingleton::SelObj>::const_iterator it=Sel.begin();it!=Sel.end();++it) {
if ((*it).pObject->getTypeId().isDerivedFrom(Path::Feature::getClassTypeId())) {
pcPathObject = static_cast<Path::Feature*>((*it).pObject);
cmd << "FreeCAD.activeDocument()." << pcPathObject->getNameInDocument() << ",";
} else {
Base::Console().Error("Only Path objects must be selected before running this command\n");
return;
}
}
cmd << "]";
std::string FeatName = getUniqueObjectName("PathCompound");
openCommand("Create Path Compound");
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureCompound','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Group = %s",FeatName.c_str(),cmd.str().c_str());
commitCommand();
updateActive();
} else {
Base::Console().Error("At least one Path object must be selected\n");
return;
}
}
bool CmdPathCompound::isActive(void)
{
return hasActiveDocument();
}
// Path Shape #####################################################################################################
DEF_STD_CMD_A(CmdPathShape)
CmdPathShape::CmdPathShape()
:Command("Path_Shape")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("From Shape");
sToolTipText = QT_TR_NOOP("Creates a path from a selected shape");
sWhatsThis = "Path_Shape";
sStatusTip = sToolTipText;
sPixmap = "Path-Shape";
}
void CmdPathShape::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::list<std::string> cmds;
std::ostringstream sources;
for(const Gui::SelectionObject &selObj :
getSelection().getSelectionEx(NULL, Part::Feature::getClassTypeId()))
{
const Part::Feature *pcObj = static_cast<const Part::Feature*>(selObj.getObject());
const std::vector<std::string> &subnames = selObj.getSubNames();
if(subnames.empty()) {
sources << "FreeCAD.activeDocument()." << pcObj->getNameInDocument() << ",";
continue;
}
for(const std::string &name : subnames) {
if(name.compare(0,4,"Face") && name.compare(0,4,"Edge")) {
Base::Console().Warning("Ignored shape %s %s\n",
pcObj->getNameInDocument(), name.c_str());
continue;
}
std::ostringstream subname;
subname << pcObj->getNameInDocument() << '_' << name;
std::string sub_fname = getUniqueObjectName(subname.str().c_str());
std::ostringstream cmd;
cmd << "FreeCAD.activeDocument().addObject('Part::Feature','" << sub_fname <<
"').Shape = PathCommands.findShape(FreeCAD.activeDocument()." <<
pcObj->getNameInDocument() << ".Shape,'" << name << "'";
if(!name.compare(0,4,"Edge"))
cmd << ",'Wires'";
cmd << ')';
cmds.push_back(cmd.str());
sources << "FreeCAD.activeDocument()." << sub_fname << ",";
}
}
std::string FeatName = getUniqueObjectName("PathShape");
openCommand("Create Path Shape");
doCommand(Doc,"import PathCommands");
for(const std::string &cmd : cmds)
doCommand(Doc, "%s", cmd.c_str());
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureShape','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Sources = [ %s ]",FeatName.c_str(),sources.str().c_str());
commitCommand();
updateActive();
}
bool CmdPathShape::isActive(void)
{
return hasActiveDocument();
}
void CreatePathCommands(void)
{
Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
rcCmdMgr.addCommand(new CmdPathCompound());
rcCmdMgr.addCommand(new CmdPathShape());
rcCmdMgr.addCommand(new CmdPathArea());
rcCmdMgr.addCommand(new CmdPathAreaWorkplane());
}

View File

@@ -1,23 +1,23 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"

View File

@@ -1,87 +1,87 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATHGUI_PRECOMPILED_H
#define PATHGUI_PRECOMPILED_H
#include <FCConfig.h>
// Importing of App classes
#ifdef FC_OS_WIN32
# define PartExport __declspec(dllimport)
# define PathExport __declspec(dllimport)
# define PartGuiExport __declspec(dllexport)
# define PathGuiExport __declspec(dllexport)
#else // for Linux
# define PartExport
# define PathExport
# define PartGuiExport
# define PathGuiExport
#endif
#include <Standard_math.hxx>
#ifdef _MSC_VER
# pragma warning( disable : 4273 )
#endif
#ifdef _PreComp_
// Python
#include <Python.h>
// standard
#include <iostream>
#include <assert.h>
#include <cmath>
// STL
#include <vector>
#include <map>
#include <string>
#include <list>
#include <set>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
#ifdef FC_OS_WIN32
# include <windows.h>
#endif
// OCC
#include <TopExp_Explorer.hxx>
// Qt Toolkit
#ifndef __Qt4All__
# include <Gui/Qt4All.h>
#endif
// all of Inventor
#ifndef __InventorAll__
# include <Gui/InventorAll.h>
#endif
#endif //_PreComp_
#endif // PATHGUI_PRECOMPILED_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATHGUI_PRECOMPILED_H
#define PATHGUI_PRECOMPILED_H
#include <FCConfig.h>
// Importing of App classes
#ifdef FC_OS_WIN32
# define PartExport __declspec(dllimport)
# define PathExport __declspec(dllimport)
# define PartGuiExport __declspec(dllexport)
# define PathGuiExport __declspec(dllexport)
#else // for Linux
# define PartExport
# define PathExport
# define PartGuiExport
# define PathGuiExport
#endif
#include <Standard_math.hxx>
#ifdef _MSC_VER
# pragma warning( disable : 4273 )
#endif
#ifdef _PreComp_
// Python
#include <Python.h>
// standard
#include <iostream>
#include <assert.h>
#include <cmath>
// STL
#include <vector>
#include <map>
#include <string>
#include <list>
#include <set>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
#ifdef FC_OS_WIN32
# include <windows.h>
#endif
// OCC
#include <TopExp_Explorer.hxx>
// Qt Toolkit
#ifndef __Qt4All__
# include <Gui/Qt4All.h>
#endif
// all of Inventor
#ifndef __InventorAll__
# include <Gui/InventorAll.h>
#endif
#endif //_PreComp_
#endif // PATHGUI_PRECOMPILED_H

View File

@@ -1,162 +1,162 @@
<RCC>
<qresource>
<file>icons/Path-Adaptive.svg</file>
<file>icons/Path-ToolDuplicate.svg</file>
<file>icons/Path-3DPocket.svg</file>
<file>icons/Path-3DSurface.svg</file>
<file>icons/Path-Area-View.svg</file>
<file>icons/Path-Area-Workplane.svg</file>
<file>icons/Path-Area.svg</file>
<file>icons/Path-Array.svg</file>
<file>icons/Path-Axis.svg</file>
<file>icons/Path-BFastForward.svg</file>
<file>icons/Path-BPause.svg</file>
<file>icons/Path-BPlay.svg</file>
<file>icons/Path-BStep.svg</file>
<file>icons/Path-BStop.svg</file>
<file>icons/Path-BaseGeometry.svg</file>
<file>icons/Path-Comment.svg</file>
<file>icons/Path-Compound.svg</file>
<file>icons/Path-Contour.svg</file>
<file>icons/Path-Copy.svg</file>
<file>icons/Path-Custom.svg</file>
<file>icons/Path-Datums.svg</file>
<file>icons/Path-Deburr.svg</file>
<file>icons/Path-Depths.svg</file>
<file>icons/Path-Dressup.svg</file>
<file>icons/Path-Drilling.svg</file>
<file>icons/Path-Engrave.svg</file>
<file>icons/Path-ExportTemplate.svg</file>
<file>icons/Path-Face.svg</file>
<file>icons/Path-FacePocket.svg</file>
<file>icons/Path-FaceProfile.svg</file>
<file>icons/Path-Heights.svg</file>
<file>icons/Path-Helix.svg</file>
<file>icons/Path-Hop.svg</file>
<file>icons/Path-Inspect.svg</file>
<file>icons/Path-Job.svg</file>
<file>icons/Path-Kurve.svg</file>
<file>icons/Path-LengthOffset.svg</file>
<file>icons/Path-Machine.svg</file>
<file>icons/Path-MachineLathe.svg</file>
<file>icons/Path-MachineMill.svg</file>
<file>icons/Path-OpActive.svg</file>
<file>icons/Path-OpCopy.svg</file>
<file>icons/Path-OperationA.svg</file>
<file>icons/Path-OperationB.svg</file>
<file>icons/Path-Plane.svg</file>
<file>icons/Path-Pocket.svg</file>
<file>icons/Path-Post.svg</file>
<file>icons/Path-Probe.svg</file>
<file>icons/Path-Profile-Edges.svg</file>
<file>icons/Path-Profile-Face.svg</file>
<file>icons/Path-Profile.svg</file>
<file>icons/Path-Sanity.svg</file>
<file>icons/Path-SelectLoop.svg</file>
<file>icons/Path-SetupSheet.svg</file>
<file>icons/Path-Shape.svg</file>
<file>icons/Path-SimpleCopy.svg</file>
<file>icons/Path-Simulator.svg</file>
<file>icons/Path-Speed.svg</file>
<file>icons/Path-Stock.svg</file>
<file>icons/Path-Stop.svg</file>
<file>icons/Path-ToolBit.svg</file>
<file>icons/Path-ToolChange.svg</file>
<file>icons/Path-ToolController.svg</file>
<file>icons/Path-Toolpath.svg</file>
<file>icons/Path-ToolTable.svg</file>
<file>icons/Path-Waterline.svg</file>
<file>icons/arrow-ccw.svg</file>
<file>icons/arrow-cw.svg</file>
<file>icons/arrow-down.svg</file>
<file>icons/arrow-left-down.svg</file>
<file>icons/arrow-left-up.svg</file>
<file>icons/arrow-left.svg</file>
<file>icons/arrow-right-down.svg</file>
<file>icons/arrow-right-up.svg</file>
<file>icons/arrow-right.svg</file>
<file>icons/arrow-up.svg</file>
<file>icons/edge-join-miter-not.svg</file>
<file>icons/edge-join-miter.svg</file>
<file>icons/edge-join-round-not.svg</file>
<file>icons/edge-join-round.svg</file>
<file>icons/preferences-path.svg</file>
<file>panels/DlgJobChooser.ui</file>
<file>panels/DlgJobCreate.ui</file>
<file>panels/DlgJobModelSelect.ui</file>
<file>panels/DlgJobTemplateExport.ui</file>
<file>panels/DlgSelectPostProcessor.ui</file>
<file>panels/DlgTCChooser.ui</file>
<file>panels/DlgToolControllerEdit.ui</file>
<file>panels/DlgToolCopy.ui</file>
<file>panels/DlgToolEdit.ui</file>
<file>panels/DogboneEdit.ui</file>
<file>panels/DressupPathBoundary.ui</file>
<file>panels/HoldingTagsEdit.ui</file>
<file>panels/PageBaseGeometryEdit.ui</file>
<file>panels/PageBaseHoleGeometryEdit.ui</file>
<file>panels/PageBaseLocationEdit.ui</file>
<file>panels/PageDepthsEdit.ui</file>
<file>panels/PageHeightsEdit.ui</file>
<file>panels/PageOpDeburrEdit.ui</file>
<file>panels/PageOpDrillingEdit.ui</file>
<file>panels/PageOpEngraveEdit.ui</file>
<file>panels/PageOpHelixEdit.ui</file>
<file>panels/PageOpPocketExtEdit.ui</file>
<file>panels/PageOpPocketFullEdit.ui</file>
<file>panels/PageOpProbeEdit.ui</file>
<file>panels/PageOpProfileFullEdit.ui</file>
<file>panels/PageOpSurfaceEdit.ui</file>
<file>panels/PageOpWaterlineEdit.ui</file>
<file>panels/PathEdit.ui</file>
<file>panels/PointEdit.ui</file>
<file>panels/SetupGlobal.ui</file>
<file>panels/SetupOp.ui</file>
<file>panels/ToolBitEditor.ui</file>
<file>panels/ToolBitLibraryEdit.ui</file>
<file>panels/ToolBitSelector.ui</file>
<file>panels/ToolEditor.ui</file>
<file>panels/ToolLibraryEditor.ui</file>
<file>panels/TaskPathSimulator.ui</file>
<file>panels/ZCorrectEdit.ui</file>
<file>preferences/PathDressupHoldingTags.ui</file>
<file>preferences/PathJob.ui</file>
<file>translations/Path_af.qm</file>
<file>translations/Path_ar.qm</file>
<file>translations/Path_ca.qm</file>
<file>translations/Path_cs.qm</file>
<file>translations/Path_de.qm</file>
<file>translations/Path_el.qm</file>
<file>translations/Path_es-ES.qm</file>
<file>translations/Path_eu.qm</file>
<file>translations/Path_fi.qm</file>
<file>translations/Path_fil.qm</file>
<file>translations/Path_fr.qm</file>
<file>translations/Path_gl.qm</file>
<file>translations/Path_hr.qm</file>
<file>translations/Path_hu.qm</file>
<file>translations/Path_id.qm</file>
<file>translations/Path_it.qm</file>
<file>translations/Path_ja.qm</file>
<file>translations/Path_kab.qm</file>
<file>translations/Path_ko.qm</file>
<file>translations/Path_lt.qm</file>
<file>translations/Path_nl.qm</file>
<file>translations/Path_no.qm</file>
<file>translations/Path_pl.qm</file>
<file>translations/Path_pt-BR.qm</file>
<file>translations/Path_pt-PT.qm</file>
<file>translations/Path_ro.qm</file>
<file>translations/Path_ru.qm</file>
<file>translations/Path_sk.qm</file>
<file>translations/Path_sl.qm</file>
<file>translations/Path_sr.qm</file>
<file>translations/Path_sv-SE.qm</file>
<file>translations/Path_tr.qm</file>
<file>translations/Path_uk.qm</file>
<file>translations/Path_val-ES.qm</file>
<file>translations/Path_vi.qm</file>
<file>translations/Path_zh-CN.qm</file>
<file>translations/Path_zh-TW.qm</file>
</qresource>
</RCC>
<RCC>
<qresource>
<file>icons/Path-Adaptive.svg</file>
<file>icons/Path-ToolDuplicate.svg</file>
<file>icons/Path-3DPocket.svg</file>
<file>icons/Path-3DSurface.svg</file>
<file>icons/Path-Area-View.svg</file>
<file>icons/Path-Area-Workplane.svg</file>
<file>icons/Path-Area.svg</file>
<file>icons/Path-Array.svg</file>
<file>icons/Path-Axis.svg</file>
<file>icons/Path-BFastForward.svg</file>
<file>icons/Path-BPause.svg</file>
<file>icons/Path-BPlay.svg</file>
<file>icons/Path-BStep.svg</file>
<file>icons/Path-BStop.svg</file>
<file>icons/Path-BaseGeometry.svg</file>
<file>icons/Path-Comment.svg</file>
<file>icons/Path-Compound.svg</file>
<file>icons/Path-Contour.svg</file>
<file>icons/Path-Copy.svg</file>
<file>icons/Path-Custom.svg</file>
<file>icons/Path-Datums.svg</file>
<file>icons/Path-Deburr.svg</file>
<file>icons/Path-Depths.svg</file>
<file>icons/Path-Dressup.svg</file>
<file>icons/Path-Drilling.svg</file>
<file>icons/Path-Engrave.svg</file>
<file>icons/Path-ExportTemplate.svg</file>
<file>icons/Path-Face.svg</file>
<file>icons/Path-FacePocket.svg</file>
<file>icons/Path-FaceProfile.svg</file>
<file>icons/Path-Heights.svg</file>
<file>icons/Path-Helix.svg</file>
<file>icons/Path-Hop.svg</file>
<file>icons/Path-Inspect.svg</file>
<file>icons/Path-Job.svg</file>
<file>icons/Path-Kurve.svg</file>
<file>icons/Path-LengthOffset.svg</file>
<file>icons/Path-Machine.svg</file>
<file>icons/Path-MachineLathe.svg</file>
<file>icons/Path-MachineMill.svg</file>
<file>icons/Path-OpActive.svg</file>
<file>icons/Path-OpCopy.svg</file>
<file>icons/Path-OperationA.svg</file>
<file>icons/Path-OperationB.svg</file>
<file>icons/Path-Plane.svg</file>
<file>icons/Path-Pocket.svg</file>
<file>icons/Path-Post.svg</file>
<file>icons/Path-Probe.svg</file>
<file>icons/Path-Profile-Edges.svg</file>
<file>icons/Path-Profile-Face.svg</file>
<file>icons/Path-Profile.svg</file>
<file>icons/Path-Sanity.svg</file>
<file>icons/Path-SelectLoop.svg</file>
<file>icons/Path-SetupSheet.svg</file>
<file>icons/Path-Shape.svg</file>
<file>icons/Path-SimpleCopy.svg</file>
<file>icons/Path-Simulator.svg</file>
<file>icons/Path-Speed.svg</file>
<file>icons/Path-Stock.svg</file>
<file>icons/Path-Stop.svg</file>
<file>icons/Path-ToolBit.svg</file>
<file>icons/Path-ToolChange.svg</file>
<file>icons/Path-ToolController.svg</file>
<file>icons/Path-Toolpath.svg</file>
<file>icons/Path-ToolTable.svg</file>
<file>icons/Path-Waterline.svg</file>
<file>icons/arrow-ccw.svg</file>
<file>icons/arrow-cw.svg</file>
<file>icons/arrow-down.svg</file>
<file>icons/arrow-left-down.svg</file>
<file>icons/arrow-left-up.svg</file>
<file>icons/arrow-left.svg</file>
<file>icons/arrow-right-down.svg</file>
<file>icons/arrow-right-up.svg</file>
<file>icons/arrow-right.svg</file>
<file>icons/arrow-up.svg</file>
<file>icons/edge-join-miter-not.svg</file>
<file>icons/edge-join-miter.svg</file>
<file>icons/edge-join-round-not.svg</file>
<file>icons/edge-join-round.svg</file>
<file>icons/preferences-path.svg</file>
<file>panels/DlgJobChooser.ui</file>
<file>panels/DlgJobCreate.ui</file>
<file>panels/DlgJobModelSelect.ui</file>
<file>panels/DlgJobTemplateExport.ui</file>
<file>panels/DlgSelectPostProcessor.ui</file>
<file>panels/DlgTCChooser.ui</file>
<file>panels/DlgToolControllerEdit.ui</file>
<file>panels/DlgToolCopy.ui</file>
<file>panels/DlgToolEdit.ui</file>
<file>panels/DogboneEdit.ui</file>
<file>panels/DressupPathBoundary.ui</file>
<file>panels/HoldingTagsEdit.ui</file>
<file>panels/PageBaseGeometryEdit.ui</file>
<file>panels/PageBaseHoleGeometryEdit.ui</file>
<file>panels/PageBaseLocationEdit.ui</file>
<file>panels/PageDepthsEdit.ui</file>
<file>panels/PageHeightsEdit.ui</file>
<file>panels/PageOpDeburrEdit.ui</file>
<file>panels/PageOpDrillingEdit.ui</file>
<file>panels/PageOpEngraveEdit.ui</file>
<file>panels/PageOpHelixEdit.ui</file>
<file>panels/PageOpPocketExtEdit.ui</file>
<file>panels/PageOpPocketFullEdit.ui</file>
<file>panels/PageOpProbeEdit.ui</file>
<file>panels/PageOpProfileFullEdit.ui</file>
<file>panels/PageOpSurfaceEdit.ui</file>
<file>panels/PageOpWaterlineEdit.ui</file>
<file>panels/PathEdit.ui</file>
<file>panels/PointEdit.ui</file>
<file>panels/SetupGlobal.ui</file>
<file>panels/SetupOp.ui</file>
<file>panels/ToolBitEditor.ui</file>
<file>panels/ToolBitLibraryEdit.ui</file>
<file>panels/ToolBitSelector.ui</file>
<file>panels/ToolEditor.ui</file>
<file>panels/ToolLibraryEditor.ui</file>
<file>panels/TaskPathSimulator.ui</file>
<file>panels/ZCorrectEdit.ui</file>
<file>preferences/PathDressupHoldingTags.ui</file>
<file>preferences/PathJob.ui</file>
<file>translations/Path_af.qm</file>
<file>translations/Path_ar.qm</file>
<file>translations/Path_ca.qm</file>
<file>translations/Path_cs.qm</file>
<file>translations/Path_de.qm</file>
<file>translations/Path_el.qm</file>
<file>translations/Path_es-ES.qm</file>
<file>translations/Path_eu.qm</file>
<file>translations/Path_fi.qm</file>
<file>translations/Path_fil.qm</file>
<file>translations/Path_fr.qm</file>
<file>translations/Path_gl.qm</file>
<file>translations/Path_hr.qm</file>
<file>translations/Path_hu.qm</file>
<file>translations/Path_id.qm</file>
<file>translations/Path_it.qm</file>
<file>translations/Path_ja.qm</file>
<file>translations/Path_kab.qm</file>
<file>translations/Path_ko.qm</file>
<file>translations/Path_lt.qm</file>
<file>translations/Path_nl.qm</file>
<file>translations/Path_no.qm</file>
<file>translations/Path_pl.qm</file>
<file>translations/Path_pt-BR.qm</file>
<file>translations/Path_pt-PT.qm</file>
<file>translations/Path_ro.qm</file>
<file>translations/Path_ru.qm</file>
<file>translations/Path_sk.qm</file>
<file>translations/Path_sl.qm</file>
<file>translations/Path_sr.qm</file>
<file>translations/Path_sv-SE.qm</file>
<file>translations/Path_tr.qm</file>
<file>translations/Path_uk.qm</file>
<file>translations/Path_val-ES.qm</file>
<file>translations/Path_vi.qm</file>
<file>translations/Path_zh-CN.qm</file>
<file>translations/Path_zh-TW.qm</file>
</qresource>
</RCC>

View File

@@ -1,435 +1,435 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1"
id="svg2816"
height="64px"
width="64px">
<defs
id="defs2818">
<linearGradient
id="linearGradient4031">
<stop
style="stop-color:#d3d7cf;stop-opacity:1"
offset="0"
id="stop4033" />
<stop
style="stop-color:#888a85;stop-opacity:1"
offset="1"
id="stop4035" />
</linearGradient>
<linearGradient
id="linearGradient3989">
<stop
style="stop-color:#d3d7cf;stop-opacity:1"
offset="0"
id="stop3991" />
<stop
style="stop-color:#888a85;stop-opacity:1"
offset="1"
id="stop3993" />
</linearGradient>
<linearGradient
id="linearGradient3945">
<stop
id="stop3947"
offset="0"
style="stop-color:#8f5902;stop-opacity:1" />
<stop
id="stop3949"
offset="1"
style="stop-color:#e9b96e;stop-opacity:1" />
</linearGradient>
<linearGradient
id="linearGradient3937">
<stop
id="stop3939"
offset="0"
style="stop-color:#8f5902;stop-opacity:1" />
<stop
id="stop3941"
offset="1"
style="stop-color:#e9b96e;stop-opacity:1" />
</linearGradient>
<linearGradient
id="linearGradient4513">
<stop
id="stop4515"
offset="0"
style="stop-color:#d3d7cf;stop-opacity:1" />
<stop
id="stop4517"
offset="1"
style="stop-color:#888a85;stop-opacity:1" />
</linearGradient>
<linearGradient
id="linearGradient3681">
<stop
style="stop-color:#fff110;stop-opacity:1;"
offset="0"
id="stop3697" />
<stop
id="stop3685"
offset="1"
style="stop-color:#cf7008;stop-opacity:1;" />
</linearGradient>
<pattern
xlink:href="#Strips1_1-4"
id="pattern5231"
patternTransform="matrix(0.67643728,-0.81829155,2.4578314,1.8844554,-26.450606,18.294947)" />
<pattern
patternUnits="userSpaceOnUse"
width="2"
height="1"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,3.4760987,3.534923)"
id="Strips1_1-4">
<rect
style="fill:black;stroke:none"
x="0"
y="-0.5"
width="1"
height="2"
id="rect4483-4" />
</pattern>
<pattern
xlink:href="#Strips1_1-6"
id="pattern5231-4"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,39.618381,8.9692804)" />
<pattern
patternUnits="userSpaceOnUse"
width="2"
height="1"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,3.4760987,3.534923)"
id="Strips1_1-6">
<rect
style="fill:black;stroke:none"
x="0"
y="-0.5"
width="1"
height="2"
id="rect4483-0" />
</pattern>
<pattern
xlink:href="#pattern5231-3"
id="pattern5296"
patternTransform="matrix(0.66513382,-1.0631299,2.4167603,2.4482973,-49.762569,2.9546807)" />
<pattern
xlink:href="#Strips1_1-4-3"
id="pattern5231-3"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,-26.336284,10.887197)" />
<pattern
patternUnits="userSpaceOnUse"
width="2"
height="1"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,3.4760987,3.534923)"
id="Strips1_1-4-3">
<rect
style="fill:black;stroke:none"
x="0"
y="-0.5"
width="1"
height="2"
id="rect4483-4-6" />
</pattern>
<pattern
xlink:href="#Strips1_1-9"
id="pattern5330"
patternTransform="matrix(0.42844886,-0.62155849,1.5567667,1.431396,27.948414,13.306456)" />
<pattern
patternUnits="userSpaceOnUse"
width="2"
height="1"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,3.4760987,3.534923)"
id="Strips1_1-9">
<rect
style="fill:black;stroke:none"
x="0"
y="-0.5"
width="1"
height="2"
id="rect4483-3" />
</pattern>
<linearGradient
gradientTransform="translate(127.27273,-51.272729)"
gradientUnits="userSpaceOnUse"
y2="40.168594"
x2="4.0605712"
y1="41.087898"
x1="37.89756"
id="linearGradient3687"
xlink:href="#linearGradient3681" />
<linearGradient
gradientTransform="translate(127.27273,-51.272729)"
gradientUnits="userSpaceOnUse"
y2="43.558987"
x2="59.811455"
y1="40.484772"
x1="37.894287"
id="linearGradient3695"
xlink:href="#linearGradient3681" />
<linearGradient
id="linearGradient3681-3">
<stop
style="stop-color:#fff110;stop-opacity:1;"
offset="0"
id="stop3697-3" />
<stop
id="stop3685-4"
offset="1"
style="stop-color:#cf7008;stop-opacity:1;" />
</linearGradient>
<linearGradient
xlink:href="#linearGradient3681-3"
id="linearGradient3608"
gradientUnits="userSpaceOnUse"
gradientTransform="translate(-37.00068,-20.487365)"
x1="37.894287"
y1="40.484772"
x2="59.811455"
y2="43.558987" />
<linearGradient
id="linearGradient4513-2">
<stop
id="stop4515-2"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-4"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<radialGradient
xlink:href="#linearGradient4513-2"
id="radialGradient4538"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,1.1841158,-8.5173246,-3.4097568)"
cx="32.151962"
cy="7.9319997"
fx="32.151962"
fy="7.9319997"
r="23.634638" />
<linearGradient
id="linearGradient4513-1">
<stop
id="stop4515-8"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-6"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<radialGradient
xlink:href="#linearGradient4513-1"
id="radialGradient4538-6"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,1.1841158,-8.5173246,-3.4097568)"
cx="32.151962"
cy="7.9319997"
fx="32.151962"
fy="7.9319997"
r="23.634638" />
<radialGradient
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1.0155652,0,0,1.1851825,-0.65241357,-1.4008677)"
r="23.634638"
fy="7.9319997"
fx="32.151962"
cy="7.9319997"
cx="32.151962"
id="radialGradient4521-5"
xlink:href="#linearGradient4513-6" />
<linearGradient
id="linearGradient4513-6">
<stop
id="stop4515-29"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-1"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
y2="11"
x2="33"
y1="5"
x1="32"
id="linearGradient3935"
xlink:href="#linearGradient4513" />
<linearGradient
gradientUnits="userSpaceOnUse"
y2="49"
x2="11"
y1="59"
x1="14"
id="linearGradient3943"
xlink:href="#linearGradient3937" />
<linearGradient
gradientUnits="userSpaceOnUse"
y2="49"
x2="51"
y1="59"
x1="54"
id="linearGradient3951"
xlink:href="#linearGradient3945" />
<radialGradient
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(0.67911969,0,0,1.122061,10.189733,-0.72498825)"
r="23.634638"
fy="17.949734"
fx="32.151962"
cy="17.949734"
cx="32.151962"
id="radialGradient4521-0-7"
xlink:href="#linearGradient4513-2-0" />
<linearGradient
id="linearGradient4513-2-0">
<stop
id="stop4515-2-9"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-4-3"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
y2="23"
x2="33"
y1="15"
x1="31"
id="linearGradient3987"
xlink:href="#linearGradient3989" />
<radialGradient
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(0.39497909,0,0,1.1841158,19.452609,-1.4604067)"
r="23.634638"
fy="35.869175"
fx="32.151962"
cy="35.869175"
cx="32.151962"
id="radialGradient4521-4-0"
xlink:href="#linearGradient4513-1-6" />
<linearGradient
id="linearGradient4513-1-6">
<stop
id="stop4515-8-2"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-6-6"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
y2="54.227272"
x2="36"
y1="27.90909"
x1="27.909092"
id="linearGradient4029"
xlink:href="#linearGradient4031" />
</defs>
<metadata
id="metadata2821">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
<dc:title>PathWorkbench</dc:title>
<dc:date>2016-02-26</dc:date>
<dc:relation>http://www.freecadweb.org/wiki/index.php?title=Artwork</dc:relation>
<dc:publisher>
<cc:Agent>
<dc:title>FreeCAD</dc:title>
</cc:Agent>
</dc:publisher>
<dc:identifier>FreeCAD/src/Mod/Path/Gui/Resources/icons/PathWorkbench.svg</dc:identifier>
<dc:rights>
<cc:Agent>
<dc:title>FreeCAD LGPL2+</dc:title>
</cc:Agent>
</dc:rights>
<cc:license>https://www.gnu.org/copyleft/lesser.html</cc:license>
<dc:contributor>
<cc:Agent>
<dc:title>[agryson] Alexander Gryson</dc:title>
</cc:Agent>
</dc:contributor>
</cc:Work>
</rdf:RDF>
</metadata>
<g
id="layer1">
<path
id="rect4590-5"
d="m 61,47 0,14 -29,0 13,-8 c 0,0 0.05185,-3.282514 0,-6 z"
style="color:#000000;fill:url(#linearGradient3951);fill-opacity:1;fill-rule:nonzero;stroke:#271903;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<path
id="rect4590"
d="m 3,47 0,14 29,0 -13,-8 c 0,0 -0.05185,-3.282514 0,-6 z"
style="color:#000000;fill:url(#linearGradient3943);fill-opacity:1;fill-rule:nonzero;stroke:#271903;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<rect
y="12.572689"
x="17"
height="12.427311"
width="29.999998"
id="rect4411"
style="color:#000000;fill:url(#linearGradient3987);fill-opacity:1;fill-rule:nonzero;stroke:#2e3436;stroke-width:1.99999975999999990;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<rect
y="3"
x="9"
height="10"
width="46"
id="rect3591"
style="color:#000000;fill:url(#linearGradient3935);fill-opacity:1;fill-rule:nonzero;stroke:#2e3436;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<path
id="rect4590-6"
d="m 5,49 0,10 20,0 -8,-5 0,-5 z"
style="color:#000000;fill:none;stroke:#e9b96e;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:11.60000038;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<path
id="rect4590-6-7"
d="m 59,49 0,10 -20,0 8,-5 0,-5 z"
style="color:#000000;fill:none;stroke:#e9b96e;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:11.60000038;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<rect
y="5"
x="11"
height="6"
width="42"
id="rect3591-2"
style="color:#000000;fill:none;stroke:#d3d7cf;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<rect
y="15"
x="19"
height="8"
width="26"
id="rect4411-6"
style="color:#000000;fill:none;stroke:#d3d7cf;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<g
id="g3859">
<path
style="color:#000000;fill:url(#linearGradient4029);fill-opacity:1;fill-rule:nonzero;stroke:#2e3436;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
d="m 32,25 -9,4 0,8 18,-8 0,-4 z m 9,6 -18,8 0,9 18,-7 z m 0,12 -18,7 9,6 9,-6 z"
id="rect4417" />
<path
style="color:#000000;fill:none;stroke:#d3d7cf;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
d="M 32.369624,26.992756 25.011364,30.170455 25,34 39,28 39,27 z M 38.967859,34.128565 25.064282,40.321412 25,45 38.935718,39.578542 z M 38.981168,45.978888 27.318182,50.5 l 4.762171,3.178588 6.903577,-4.674966 z"
id="rect4417-1" />
<path
style="fill:#d3d7cf;stroke:#2e3436;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-opacity:1"
d="m 23,27 0,-2 8,0 z"
id="path3085" />
</g>
</g>
</svg>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1"
id="svg2816"
height="64px"
width="64px">
<defs
id="defs2818">
<linearGradient
id="linearGradient4031">
<stop
style="stop-color:#d3d7cf;stop-opacity:1"
offset="0"
id="stop4033" />
<stop
style="stop-color:#888a85;stop-opacity:1"
offset="1"
id="stop4035" />
</linearGradient>
<linearGradient
id="linearGradient3989">
<stop
style="stop-color:#d3d7cf;stop-opacity:1"
offset="0"
id="stop3991" />
<stop
style="stop-color:#888a85;stop-opacity:1"
offset="1"
id="stop3993" />
</linearGradient>
<linearGradient
id="linearGradient3945">
<stop
id="stop3947"
offset="0"
style="stop-color:#8f5902;stop-opacity:1" />
<stop
id="stop3949"
offset="1"
style="stop-color:#e9b96e;stop-opacity:1" />
</linearGradient>
<linearGradient
id="linearGradient3937">
<stop
id="stop3939"
offset="0"
style="stop-color:#8f5902;stop-opacity:1" />
<stop
id="stop3941"
offset="1"
style="stop-color:#e9b96e;stop-opacity:1" />
</linearGradient>
<linearGradient
id="linearGradient4513">
<stop
id="stop4515"
offset="0"
style="stop-color:#d3d7cf;stop-opacity:1" />
<stop
id="stop4517"
offset="1"
style="stop-color:#888a85;stop-opacity:1" />
</linearGradient>
<linearGradient
id="linearGradient3681">
<stop
style="stop-color:#fff110;stop-opacity:1;"
offset="0"
id="stop3697" />
<stop
id="stop3685"
offset="1"
style="stop-color:#cf7008;stop-opacity:1;" />
</linearGradient>
<pattern
xlink:href="#Strips1_1-4"
id="pattern5231"
patternTransform="matrix(0.67643728,-0.81829155,2.4578314,1.8844554,-26.450606,18.294947)" />
<pattern
patternUnits="userSpaceOnUse"
width="2"
height="1"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,3.4760987,3.534923)"
id="Strips1_1-4">
<rect
style="fill:black;stroke:none"
x="0"
y="-0.5"
width="1"
height="2"
id="rect4483-4" />
</pattern>
<pattern
xlink:href="#Strips1_1-6"
id="pattern5231-4"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,39.618381,8.9692804)" />
<pattern
patternUnits="userSpaceOnUse"
width="2"
height="1"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,3.4760987,3.534923)"
id="Strips1_1-6">
<rect
style="fill:black;stroke:none"
x="0"
y="-0.5"
width="1"
height="2"
id="rect4483-0" />
</pattern>
<pattern
xlink:href="#pattern5231-3"
id="pattern5296"
patternTransform="matrix(0.66513382,-1.0631299,2.4167603,2.4482973,-49.762569,2.9546807)" />
<pattern
xlink:href="#Strips1_1-4-3"
id="pattern5231-3"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,-26.336284,10.887197)" />
<pattern
patternUnits="userSpaceOnUse"
width="2"
height="1"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,3.4760987,3.534923)"
id="Strips1_1-4-3">
<rect
style="fill:black;stroke:none"
x="0"
y="-0.5"
width="1"
height="2"
id="rect4483-4-6" />
</pattern>
<pattern
xlink:href="#Strips1_1-9"
id="pattern5330"
patternTransform="matrix(0.42844886,-0.62155849,1.5567667,1.431396,27.948414,13.306456)" />
<pattern
patternUnits="userSpaceOnUse"
width="2"
height="1"
patternTransform="matrix(0.66772843,-1.0037085,2.4261878,2.3114548,3.4760987,3.534923)"
id="Strips1_1-9">
<rect
style="fill:black;stroke:none"
x="0"
y="-0.5"
width="1"
height="2"
id="rect4483-3" />
</pattern>
<linearGradient
gradientTransform="translate(127.27273,-51.272729)"
gradientUnits="userSpaceOnUse"
y2="40.168594"
x2="4.0605712"
y1="41.087898"
x1="37.89756"
id="linearGradient3687"
xlink:href="#linearGradient3681" />
<linearGradient
gradientTransform="translate(127.27273,-51.272729)"
gradientUnits="userSpaceOnUse"
y2="43.558987"
x2="59.811455"
y1="40.484772"
x1="37.894287"
id="linearGradient3695"
xlink:href="#linearGradient3681" />
<linearGradient
id="linearGradient3681-3">
<stop
style="stop-color:#fff110;stop-opacity:1;"
offset="0"
id="stop3697-3" />
<stop
id="stop3685-4"
offset="1"
style="stop-color:#cf7008;stop-opacity:1;" />
</linearGradient>
<linearGradient
xlink:href="#linearGradient3681-3"
id="linearGradient3608"
gradientUnits="userSpaceOnUse"
gradientTransform="translate(-37.00068,-20.487365)"
x1="37.894287"
y1="40.484772"
x2="59.811455"
y2="43.558987" />
<linearGradient
id="linearGradient4513-2">
<stop
id="stop4515-2"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-4"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<radialGradient
xlink:href="#linearGradient4513-2"
id="radialGradient4538"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,1.1841158,-8.5173246,-3.4097568)"
cx="32.151962"
cy="7.9319997"
fx="32.151962"
fy="7.9319997"
r="23.634638" />
<linearGradient
id="linearGradient4513-1">
<stop
id="stop4515-8"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-6"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<radialGradient
xlink:href="#linearGradient4513-1"
id="radialGradient4538-6"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,1.1841158,-8.5173246,-3.4097568)"
cx="32.151962"
cy="7.9319997"
fx="32.151962"
fy="7.9319997"
r="23.634638" />
<radialGradient
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1.0155652,0,0,1.1851825,-0.65241357,-1.4008677)"
r="23.634638"
fy="7.9319997"
fx="32.151962"
cy="7.9319997"
cx="32.151962"
id="radialGradient4521-5"
xlink:href="#linearGradient4513-6" />
<linearGradient
id="linearGradient4513-6">
<stop
id="stop4515-29"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-1"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
y2="11"
x2="33"
y1="5"
x1="32"
id="linearGradient3935"
xlink:href="#linearGradient4513" />
<linearGradient
gradientUnits="userSpaceOnUse"
y2="49"
x2="11"
y1="59"
x1="14"
id="linearGradient3943"
xlink:href="#linearGradient3937" />
<linearGradient
gradientUnits="userSpaceOnUse"
y2="49"
x2="51"
y1="59"
x1="54"
id="linearGradient3951"
xlink:href="#linearGradient3945" />
<radialGradient
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(0.67911969,0,0,1.122061,10.189733,-0.72498825)"
r="23.634638"
fy="17.949734"
fx="32.151962"
cy="17.949734"
cx="32.151962"
id="radialGradient4521-0-7"
xlink:href="#linearGradient4513-2-0" />
<linearGradient
id="linearGradient4513-2-0">
<stop
id="stop4515-2-9"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-4-3"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
y2="23"
x2="33"
y1="15"
x1="31"
id="linearGradient3987"
xlink:href="#linearGradient3989" />
<radialGradient
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(0.39497909,0,0,1.1841158,19.452609,-1.4604067)"
r="23.634638"
fy="35.869175"
fx="32.151962"
cy="35.869175"
cx="32.151962"
id="radialGradient4521-4-0"
xlink:href="#linearGradient4513-1-6" />
<linearGradient
id="linearGradient4513-1-6">
<stop
id="stop4515-8-2"
offset="0"
style="stop-color:#ffffff;stop-opacity:1;" />
<stop
id="stop4517-6-6"
offset="1"
style="stop-color:#999999;stop-opacity:1;" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
y2="54.227272"
x2="36"
y1="27.90909"
x1="27.909092"
id="linearGradient4029"
xlink:href="#linearGradient4031" />
</defs>
<metadata
id="metadata2821">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
<dc:title>PathWorkbench</dc:title>
<dc:date>2016-02-26</dc:date>
<dc:relation>http://www.freecadweb.org/wiki/index.php?title=Artwork</dc:relation>
<dc:publisher>
<cc:Agent>
<dc:title>FreeCAD</dc:title>
</cc:Agent>
</dc:publisher>
<dc:identifier>FreeCAD/src/Mod/Path/Gui/Resources/icons/PathWorkbench.svg</dc:identifier>
<dc:rights>
<cc:Agent>
<dc:title>FreeCAD LGPL2+</dc:title>
</cc:Agent>
</dc:rights>
<cc:license>https://www.gnu.org/copyleft/lesser.html</cc:license>
<dc:contributor>
<cc:Agent>
<dc:title>[agryson] Alexander Gryson</dc:title>
</cc:Agent>
</dc:contributor>
</cc:Work>
</rdf:RDF>
</metadata>
<g
id="layer1">
<path
id="rect4590-5"
d="m 61,47 0,14 -29,0 13,-8 c 0,0 0.05185,-3.282514 0,-6 z"
style="color:#000000;fill:url(#linearGradient3951);fill-opacity:1;fill-rule:nonzero;stroke:#271903;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<path
id="rect4590"
d="m 3,47 0,14 29,0 -13,-8 c 0,0 -0.05185,-3.282514 0,-6 z"
style="color:#000000;fill:url(#linearGradient3943);fill-opacity:1;fill-rule:nonzero;stroke:#271903;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<rect
y="12.572689"
x="17"
height="12.427311"
width="29.999998"
id="rect4411"
style="color:#000000;fill:url(#linearGradient3987);fill-opacity:1;fill-rule:nonzero;stroke:#2e3436;stroke-width:1.99999975999999990;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<rect
y="3"
x="9"
height="10"
width="46"
id="rect3591"
style="color:#000000;fill:url(#linearGradient3935);fill-opacity:1;fill-rule:nonzero;stroke:#2e3436;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<path
id="rect4590-6"
d="m 5,49 0,10 20,0 -8,-5 0,-5 z"
style="color:#000000;fill:none;stroke:#e9b96e;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:11.60000038;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<path
id="rect4590-6-7"
d="m 59,49 0,10 -20,0 8,-5 0,-5 z"
style="color:#000000;fill:none;stroke:#e9b96e;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:11.60000038;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<rect
y="5"
x="11"
height="6"
width="42"
id="rect3591-2"
style="color:#000000;fill:none;stroke:#d3d7cf;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<rect
y="15"
x="19"
height="8"
width="26"
id="rect4411-6"
style="color:#000000;fill:none;stroke:#d3d7cf;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
<g
id="g3859">
<path
style="color:#000000;fill:url(#linearGradient4029);fill-opacity:1;fill-rule:nonzero;stroke:#2e3436;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
d="m 32,25 -9,4 0,8 18,-8 0,-4 z m 9,6 -18,8 0,9 18,-7 z m 0,12 -18,7 9,6 9,-6 z"
id="rect4417" />
<path
style="color:#000000;fill:none;stroke:#d3d7cf;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
d="M 32.369624,26.992756 25.011364,30.170455 25,34 39,28 39,27 z M 38.967859,34.128565 25.064282,40.321412 25,45 38.935718,39.578542 z M 38.981168,45.978888 27.318182,50.5 l 4.762171,3.178588 6.903577,-4.674966 z"
id="rect4417-1" />
<path
style="fill:#d3d7cf;stroke:#2e3436;stroke-width:2;stroke-linecap:butt;stroke-linejoin:round;stroke-opacity:1"
d="m 23,27 0,-2 8,0 z"
id="path3085" />
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -1,160 +1,160 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include "TaskDlgPathCompound.h"
#include "ui_TaskDlgPathCompound.h"
#include <Base/Console.h>
#include <Base/Exception.h>
#include <App/Document.h>
#include <App/DocumentObject.h>
#include <Gui/TaskView/TaskSelectLinkProperty.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Command.h>
#include <Mod/Path/App/Tooltable.h>
using namespace PathGui;
using namespace Gui;
/* TRANSLATOR PathGui::TaskWidgetPathCompound */
//**************************************************************************
// TaskWidget
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TaskWidgetPathCompound::TaskWidgetPathCompound(ViewProviderPathCompound *CompoundView,QWidget *parent)
: TaskBox(Gui::BitmapFactory().pixmap("Path-Compound"),tr("Compound paths"),true, parent)
{
// we need a separate container widget to add all controls to
proxy = new QWidget(this);
ui = new Ui_TaskDlgPathCompound();
ui->setupUi(proxy);
QMetaObject::connectSlotsByName(this);
this->groupLayout()->addWidget(proxy);
Path::FeatureCompound* pcCompound = static_cast<Path::FeatureCompound*>(CompoundView->getObject());
const std::vector<App::DocumentObject*> &Paths = pcCompound->Group.getValues();
for (std::vector<App::DocumentObject*>::const_iterator it= Paths.begin();it!=Paths.end();++it) {
QString name = QString::fromLatin1((*it)->getNameInDocument());
name += QString::fromLatin1(" (");
name += QString::fromUtf8((*it)->Label.getValue());
name += QString::fromLatin1(")");
ui->PathsList->addItem(name);
}
}
TaskWidgetPathCompound::~TaskWidgetPathCompound()
{
delete ui;
}
std::vector<std::string> TaskWidgetPathCompound::getList(void) const {
std::vector<std::string> names;
for(int i = 0; i < ui->PathsList->count(); i++)
{
QListWidgetItem* item = ui->PathsList->item(i);
QString name = item->text();
QStringList result;
result = name.split(QRegExp(QString::fromLatin1("\\s+")));
std::cout << result[0].toStdString() << std::endl;
names.push_back(result[0].toStdString());
}
return names;
}
void TaskWidgetPathCompound::changeEvent(QEvent *e)
{
TaskBox::changeEvent(e);
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(proxy);
}
}
//**************************************************************************
// TaskDialog
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TaskDlgPathCompound::TaskDlgPathCompound(PathGui::ViewProviderPathCompound *obj)
: TaskDialog(),CompoundView(obj)
{
assert(CompoundView);
(void)CompoundView; // fix clang warning
parameter = new TaskWidgetPathCompound(CompoundView);
Content.push_back(parameter);
}
TaskDlgPathCompound::~TaskDlgPathCompound()
{
}
//==== calls from the TaskView ===============================================================
void TaskDlgPathCompound::open()
{
}
void TaskDlgPathCompound::clicked(int button)
{
Q_UNUSED(button);
}
bool TaskDlgPathCompound::accept()
{
std::vector<App::DocumentObject*> paths;
Path::FeatureCompound* pcCompound = static_cast<Path::FeatureCompound*>(CompoundView->getObject());
App::Document* pcDoc = static_cast<App::Document*>(pcCompound->getDocument());
std::vector<std::string> names = parameter->getList();
for(std::size_t i = 0; i < names.size(); i++)
{
App::DocumentObject* pcPath = static_cast<App::DocumentObject*>(pcDoc->getObject(names[i].c_str()));
paths.push_back(pcPath);
}
pcCompound->Group.setValues(paths);
Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
return true;
}
bool TaskDlgPathCompound::reject()
{
Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
return true;
}
void TaskDlgPathCompound::helpRequested()
{
}
#include "moc_TaskDlgPathCompound.cpp"
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include "TaskDlgPathCompound.h"
#include "ui_TaskDlgPathCompound.h"
#include <Base/Console.h>
#include <Base/Exception.h>
#include <App/Document.h>
#include <App/DocumentObject.h>
#include <Gui/TaskView/TaskSelectLinkProperty.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Command.h>
#include <Mod/Path/App/Tooltable.h>
using namespace PathGui;
using namespace Gui;
/* TRANSLATOR PathGui::TaskWidgetPathCompound */
//**************************************************************************
// TaskWidget
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TaskWidgetPathCompound::TaskWidgetPathCompound(ViewProviderPathCompound *CompoundView,QWidget *parent)
: TaskBox(Gui::BitmapFactory().pixmap("Path-Compound"),tr("Compound paths"),true, parent)
{
// we need a separate container widget to add all controls to
proxy = new QWidget(this);
ui = new Ui_TaskDlgPathCompound();
ui->setupUi(proxy);
QMetaObject::connectSlotsByName(this);
this->groupLayout()->addWidget(proxy);
Path::FeatureCompound* pcCompound = static_cast<Path::FeatureCompound*>(CompoundView->getObject());
const std::vector<App::DocumentObject*> &Paths = pcCompound->Group.getValues();
for (std::vector<App::DocumentObject*>::const_iterator it= Paths.begin();it!=Paths.end();++it) {
QString name = QString::fromLatin1((*it)->getNameInDocument());
name += QString::fromLatin1(" (");
name += QString::fromUtf8((*it)->Label.getValue());
name += QString::fromLatin1(")");
ui->PathsList->addItem(name);
}
}
TaskWidgetPathCompound::~TaskWidgetPathCompound()
{
delete ui;
}
std::vector<std::string> TaskWidgetPathCompound::getList(void) const {
std::vector<std::string> names;
for(int i = 0; i < ui->PathsList->count(); i++)
{
QListWidgetItem* item = ui->PathsList->item(i);
QString name = item->text();
QStringList result;
result = name.split(QRegExp(QString::fromLatin1("\\s+")));
std::cout << result[0].toStdString() << std::endl;
names.push_back(result[0].toStdString());
}
return names;
}
void TaskWidgetPathCompound::changeEvent(QEvent *e)
{
TaskBox::changeEvent(e);
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(proxy);
}
}
//**************************************************************************
// TaskDialog
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TaskDlgPathCompound::TaskDlgPathCompound(PathGui::ViewProviderPathCompound *obj)
: TaskDialog(),CompoundView(obj)
{
assert(CompoundView);
(void)CompoundView; // fix clang warning
parameter = new TaskWidgetPathCompound(CompoundView);
Content.push_back(parameter);
}
TaskDlgPathCompound::~TaskDlgPathCompound()
{
}
//==== calls from the TaskView ===============================================================
void TaskDlgPathCompound::open()
{
}
void TaskDlgPathCompound::clicked(int button)
{
Q_UNUSED(button);
}
bool TaskDlgPathCompound::accept()
{
std::vector<App::DocumentObject*> paths;
Path::FeatureCompound* pcCompound = static_cast<Path::FeatureCompound*>(CompoundView->getObject());
App::Document* pcDoc = static_cast<App::Document*>(pcCompound->getDocument());
std::vector<std::string> names = parameter->getList();
for(std::size_t i = 0; i < names.size(); i++)
{
App::DocumentObject* pcPath = static_cast<App::DocumentObject*>(pcDoc->getObject(names[i].c_str()));
paths.push_back(pcPath);
}
pcCompound->Group.setValues(paths);
Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
return true;
}
bool TaskDlgPathCompound::reject()
{
Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
return true;
}
void TaskDlgPathCompound::helpRequested()
{
}
#include "moc_TaskDlgPathCompound.cpp"

View File

@@ -1,91 +1,91 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATHGUI_TaskDlgPathCompound_H
#define PATHGUI_TaskDlgPathCompound_H
#include <Gui/TaskView/TaskView.h>
#include <Gui/TaskView/TaskDialog.h>
#include <Mod/Path/App/FeaturePath.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include "ViewProviderPathCompound.h"
class Ui_TaskDlgPathCompound;
namespace PathGui {
/// Widget
class TaskWidgetPathCompound : public Gui::TaskView::TaskBox
{
Q_OBJECT
public:
TaskWidgetPathCompound(ViewProviderPathCompound *CompoundView, QWidget *parent=0);
~TaskWidgetPathCompound();
std::vector<std::string> getList(void) const;
protected:
void changeEvent(QEvent *e);
private:
QWidget* proxy;
Ui_TaskDlgPathCompound* ui;
};
/// Task Dialog
class PathGuiExport TaskDlgPathCompound : public Gui::TaskView::TaskDialog
{
Q_OBJECT
public:
TaskDlgPathCompound(PathGui::ViewProviderPathCompound *);
~TaskDlgPathCompound();
public:
/// is called the TaskView when the dialog is opened
virtual void open();
/// is called by the framework if an button is clicked which has no accept or rject role
virtual void clicked(int);
/// is called by the framework if the dialog is accepted (Ok)
virtual bool accept();
/// is called by the framework if the dialog is rejected (Cancel)
virtual bool reject();
/// is called by the framework if the user press the help button
virtual void helpRequested();
/// returns for Close and Help button
virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const
{ return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; }
protected:
PathGui::ViewProviderPathCompound *CompoundView;
TaskWidgetPathCompound *parameter;
};
} //namespace RobotGui
#endif // PATHGUI_TASKDLGPATHCOMPOUND_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATHGUI_TaskDlgPathCompound_H
#define PATHGUI_TaskDlgPathCompound_H
#include <Gui/TaskView/TaskView.h>
#include <Gui/TaskView/TaskDialog.h>
#include <Mod/Path/App/FeaturePath.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include "ViewProviderPathCompound.h"
class Ui_TaskDlgPathCompound;
namespace PathGui {
/// Widget
class TaskWidgetPathCompound : public Gui::TaskView::TaskBox
{
Q_OBJECT
public:
TaskWidgetPathCompound(ViewProviderPathCompound *CompoundView, QWidget *parent=0);
~TaskWidgetPathCompound();
std::vector<std::string> getList(void) const;
protected:
void changeEvent(QEvent *e);
private:
QWidget* proxy;
Ui_TaskDlgPathCompound* ui;
};
/// Task Dialog
class PathGuiExport TaskDlgPathCompound : public Gui::TaskView::TaskDialog
{
Q_OBJECT
public:
TaskDlgPathCompound(PathGui::ViewProviderPathCompound *);
~TaskDlgPathCompound();
public:
/// is called the TaskView when the dialog is opened
virtual void open();
/// is called by the framework if an button is clicked which has no accept or rject role
virtual void clicked(int);
/// is called by the framework if the dialog is accepted (Ok)
virtual bool accept();
/// is called by the framework if the dialog is rejected (Cancel)
virtual bool reject();
/// is called by the framework if the user press the help button
virtual void helpRequested();
/// returns for Close and Help button
virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const
{ return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; }
protected:
PathGui::ViewProviderPathCompound *CompoundView;
TaskWidgetPathCompound *parameter;
};
} //namespace RobotGui
#endif // PATHGUI_TASKDLGPATHCOMPOUND_H

View File

@@ -1,197 +1,197 @@
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Gui/Application.h>
#include <Mod/Path/App/FeatureArea.h>
#include "ViewProviderArea.h"
using namespace PathGui;
PROPERTY_SOURCE(PathGui::ViewProviderArea, PartGui::ViewProviderPlaneParametric)
ViewProviderArea::ViewProviderArea()
{
sPixmap = "Path-Area.svg";
}
ViewProviderArea::~ViewProviderArea()
{
}
std::vector<App::DocumentObject*> ViewProviderArea::claimChildren(void) const
{
return std::vector<App::DocumentObject*>(
static_cast<Path::FeatureArea*>(getObject())->Sources.getValues());
}
bool ViewProviderArea::canDragObjects() const
{
return true;
}
bool ViewProviderArea::canDragObject(App::DocumentObject* obj) const
{
return obj && obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId());
}
void ViewProviderArea::dragObject(App::DocumentObject* obj)
{
Path::FeatureArea* area = static_cast<Path::FeatureArea*>(getObject());
std::vector<App::DocumentObject*> sources = area->Sources.getValues();
for (std::vector<App::DocumentObject*>::iterator it = sources.begin(); it != sources.end(); ++it) {
if (*it == obj) {
sources.erase(it);
area->Sources.setValues(sources);
break;
}
}
}
bool ViewProviderArea::canDropObjects() const
{
return true;
}
bool ViewProviderArea::canDropObject(App::DocumentObject* obj) const
{
return canDragObject(obj);
}
void ViewProviderArea::dropObject(App::DocumentObject* obj)
{
Path::FeatureArea* area = static_cast<Path::FeatureArea*>(getObject());
std::vector<App::DocumentObject*> sources = area->Sources.getValues();
sources.push_back(obj);
area->Sources.setValues(sources);
}
void ViewProviderArea::updateData(const App::Property* prop)
{
PartGui::ViewProviderPart::updateData(prop);
if (prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId())) {
std::vector<App::DocumentObject*> pShapes = static_cast<const App::PropertyLinkList*>(prop)->getValues();
for (std::vector<App::DocumentObject*>::iterator it = pShapes.begin(); it != pShapes.end(); ++it) {
if (*it)
Gui::Application::Instance->hideViewProvider(*it);
}
}
}
bool ViewProviderArea::onDelete(const std::vector<std::string> &)
{
// get the input shapes
Path::FeatureArea* area = static_cast<Path::FeatureArea*>(getObject());
std::vector<App::DocumentObject*> pShapes =area->Sources.getValues();
for (std::vector<App::DocumentObject*>::iterator it = pShapes.begin(); it != pShapes.end(); ++it) {
if (*it)
Gui::Application::Instance->showViewProvider(*it);
}
return true;
}
// Python object -----------------------------------------------------------------------
PROPERTY_SOURCE(PathGui::ViewProviderAreaView, PartGui::ViewProviderPlaneParametric)
ViewProviderAreaView::ViewProviderAreaView()
{
sPixmap = "Path-Area-View.svg";
}
ViewProviderAreaView::~ViewProviderAreaView()
{
}
std::vector<App::DocumentObject*> ViewProviderAreaView::claimChildren(void) const
{
std::vector<App::DocumentObject*> ret;
Path::FeatureAreaView* feature = static_cast<Path::FeatureAreaView*>(getObject());
if(feature->Source.getValue())
ret.push_back(feature->Source.getValue());
return ret;
}
bool ViewProviderAreaView::canDragObjects() const
{
return true;
}
bool ViewProviderAreaView::canDragObject(App::DocumentObject* obj) const
{
return obj && obj->getTypeId().isDerivedFrom(Path::FeatureArea::getClassTypeId());
}
void ViewProviderAreaView::dragObject(App::DocumentObject* )
{
Path::FeatureAreaView* feature = static_cast<Path::FeatureAreaView*>(getObject());
feature->Source.setValue(NULL);
}
bool ViewProviderAreaView::canDropObjects() const
{
return true;
}
bool ViewProviderAreaView::canDropObject(App::DocumentObject* obj) const
{
return canDragObject(obj);
}
void ViewProviderAreaView::dropObject(App::DocumentObject* obj)
{
Path::FeatureAreaView* feature = static_cast<Path::FeatureAreaView*>(getObject());
feature->Source.setValue(obj);
}
void ViewProviderAreaView::updateData(const App::Property* prop)
{
PartGui::ViewProviderPlaneParametric::updateData(prop);
if (prop->getTypeId().isDerivedFrom(App::PropertyLink::getClassTypeId()))
Gui::Application::Instance->hideViewProvider(
static_cast<const App::PropertyLink*>(prop)->getValue());
}
bool ViewProviderAreaView::onDelete(const std::vector<std::string> &)
{
Path::FeatureAreaView* feature = static_cast<Path::FeatureAreaView*>(getObject());
Gui::Application::Instance->showViewProvider(feature->Source.getValue());
return true;
}
// Python object -----------------------------------------------------------------------
namespace Gui {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(PathGui::ViewProviderAreaPython, PathGui::ViewProviderArea)
PROPERTY_SOURCE_TEMPLATE(PathGui::ViewProviderAreaViewPython, PathGui::ViewProviderAreaView)
/// @endcond
// explicit template instantiation
template class PathGuiExport ViewProviderPythonFeatureT<PathGui::ViewProviderArea>;
template class PathGuiExport ViewProviderPythonFeatureT<PathGui::ViewProviderAreaView>;
}
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Gui/Application.h>
#include <Mod/Path/App/FeatureArea.h>
#include "ViewProviderArea.h"
using namespace PathGui;
PROPERTY_SOURCE(PathGui::ViewProviderArea, PartGui::ViewProviderPlaneParametric)
ViewProviderArea::ViewProviderArea()
{
sPixmap = "Path-Area.svg";
}
ViewProviderArea::~ViewProviderArea()
{
}
std::vector<App::DocumentObject*> ViewProviderArea::claimChildren(void) const
{
return std::vector<App::DocumentObject*>(
static_cast<Path::FeatureArea*>(getObject())->Sources.getValues());
}
bool ViewProviderArea::canDragObjects() const
{
return true;
}
bool ViewProviderArea::canDragObject(App::DocumentObject* obj) const
{
return obj && obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId());
}
void ViewProviderArea::dragObject(App::DocumentObject* obj)
{
Path::FeatureArea* area = static_cast<Path::FeatureArea*>(getObject());
std::vector<App::DocumentObject*> sources = area->Sources.getValues();
for (std::vector<App::DocumentObject*>::iterator it = sources.begin(); it != sources.end(); ++it) {
if (*it == obj) {
sources.erase(it);
area->Sources.setValues(sources);
break;
}
}
}
bool ViewProviderArea::canDropObjects() const
{
return true;
}
bool ViewProviderArea::canDropObject(App::DocumentObject* obj) const
{
return canDragObject(obj);
}
void ViewProviderArea::dropObject(App::DocumentObject* obj)
{
Path::FeatureArea* area = static_cast<Path::FeatureArea*>(getObject());
std::vector<App::DocumentObject*> sources = area->Sources.getValues();
sources.push_back(obj);
area->Sources.setValues(sources);
}
void ViewProviderArea::updateData(const App::Property* prop)
{
PartGui::ViewProviderPart::updateData(prop);
if (prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId())) {
std::vector<App::DocumentObject*> pShapes = static_cast<const App::PropertyLinkList*>(prop)->getValues();
for (std::vector<App::DocumentObject*>::iterator it = pShapes.begin(); it != pShapes.end(); ++it) {
if (*it)
Gui::Application::Instance->hideViewProvider(*it);
}
}
}
bool ViewProviderArea::onDelete(const std::vector<std::string> &)
{
// get the input shapes
Path::FeatureArea* area = static_cast<Path::FeatureArea*>(getObject());
std::vector<App::DocumentObject*> pShapes =area->Sources.getValues();
for (std::vector<App::DocumentObject*>::iterator it = pShapes.begin(); it != pShapes.end(); ++it) {
if (*it)
Gui::Application::Instance->showViewProvider(*it);
}
return true;
}
// Python object -----------------------------------------------------------------------
PROPERTY_SOURCE(PathGui::ViewProviderAreaView, PartGui::ViewProviderPlaneParametric)
ViewProviderAreaView::ViewProviderAreaView()
{
sPixmap = "Path-Area-View.svg";
}
ViewProviderAreaView::~ViewProviderAreaView()
{
}
std::vector<App::DocumentObject*> ViewProviderAreaView::claimChildren(void) const
{
std::vector<App::DocumentObject*> ret;
Path::FeatureAreaView* feature = static_cast<Path::FeatureAreaView*>(getObject());
if(feature->Source.getValue())
ret.push_back(feature->Source.getValue());
return ret;
}
bool ViewProviderAreaView::canDragObjects() const
{
return true;
}
bool ViewProviderAreaView::canDragObject(App::DocumentObject* obj) const
{
return obj && obj->getTypeId().isDerivedFrom(Path::FeatureArea::getClassTypeId());
}
void ViewProviderAreaView::dragObject(App::DocumentObject* )
{
Path::FeatureAreaView* feature = static_cast<Path::FeatureAreaView*>(getObject());
feature->Source.setValue(NULL);
}
bool ViewProviderAreaView::canDropObjects() const
{
return true;
}
bool ViewProviderAreaView::canDropObject(App::DocumentObject* obj) const
{
return canDragObject(obj);
}
void ViewProviderAreaView::dropObject(App::DocumentObject* obj)
{
Path::FeatureAreaView* feature = static_cast<Path::FeatureAreaView*>(getObject());
feature->Source.setValue(obj);
}
void ViewProviderAreaView::updateData(const App::Property* prop)
{
PartGui::ViewProviderPlaneParametric::updateData(prop);
if (prop->getTypeId().isDerivedFrom(App::PropertyLink::getClassTypeId()))
Gui::Application::Instance->hideViewProvider(
static_cast<const App::PropertyLink*>(prop)->getValue());
}
bool ViewProviderAreaView::onDelete(const std::vector<std::string> &)
{
Path::FeatureAreaView* feature = static_cast<Path::FeatureAreaView*>(getObject());
Gui::Application::Instance->showViewProvider(feature->Source.getValue());
return true;
}
// Python object -----------------------------------------------------------------------
namespace Gui {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(PathGui::ViewProviderAreaPython, PathGui::ViewProviderArea)
PROPERTY_SOURCE_TEMPLATE(PathGui::ViewProviderAreaViewPython, PathGui::ViewProviderAreaView)
/// @endcond
// explicit template instantiation
template class PathGuiExport ViewProviderPythonFeatureT<PathGui::ViewProviderArea>;
template class PathGuiExport ViewProviderPythonFeatureT<PathGui::ViewProviderAreaView>;
}

View File

@@ -1,83 +1,83 @@
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#ifndef PATH_ViewProviderArea_H
#define PATH_ViewProviderArea_H
#include <Gui/ViewProviderPythonFeature.h>
#include <Mod/Part/Gui/ViewProviderPlaneParametric.h>
namespace PathGui
{
class PathGuiExport ViewProviderArea : public PartGui::ViewProviderPlaneParametric
{
PROPERTY_HEADER(PathGui::ViewProviderArea);
public:
ViewProviderArea();
virtual ~ViewProviderArea();
/// grouping handling
virtual std::vector<App::DocumentObject*> claimChildren(void) const;
virtual void updateData(const App::Property*);
virtual bool onDelete(const std::vector<std::string> &);
/// drag and drop
virtual bool canDragObjects() const;
virtual bool canDragObject(App::DocumentObject*) const;
virtual void dragObject(App::DocumentObject*);
virtual bool canDropObjects() const;
virtual bool canDropObject(App::DocumentObject*) const;
virtual void dropObject(App::DocumentObject*);
};
typedef Gui::ViewProviderPythonFeatureT<ViewProviderArea> ViewProviderAreaPython;
class PathGuiExport ViewProviderAreaView : public PartGui::ViewProviderPlaneParametric
{
PROPERTY_HEADER(PathGui::ViewProviderAreaView);
public:
ViewProviderAreaView();
virtual ~ViewProviderAreaView();
virtual std::vector<App::DocumentObject*> claimChildren(void) const;
virtual void updateData(const App::Property*);
virtual bool onDelete(const std::vector<std::string> &);
/// drag and drop
virtual bool canDragObjects() const;
virtual bool canDragObject(App::DocumentObject*) const;
virtual void dragObject(App::DocumentObject*);
virtual bool canDropObjects() const;
virtual bool canDropObject(App::DocumentObject*) const;
virtual void dropObject(App::DocumentObject*);
};
typedef Gui::ViewProviderPythonFeatureT<ViewProviderAreaView> ViewProviderAreaViewPython;
} //namespace PathGui
#endif // PATH_ViewProviderArea_H
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#ifndef PATH_ViewProviderArea_H
#define PATH_ViewProviderArea_H
#include <Gui/ViewProviderPythonFeature.h>
#include <Mod/Part/Gui/ViewProviderPlaneParametric.h>
namespace PathGui
{
class PathGuiExport ViewProviderArea : public PartGui::ViewProviderPlaneParametric
{
PROPERTY_HEADER(PathGui::ViewProviderArea);
public:
ViewProviderArea();
virtual ~ViewProviderArea();
/// grouping handling
virtual std::vector<App::DocumentObject*> claimChildren(void) const;
virtual void updateData(const App::Property*);
virtual bool onDelete(const std::vector<std::string> &);
/// drag and drop
virtual bool canDragObjects() const;
virtual bool canDragObject(App::DocumentObject*) const;
virtual void dragObject(App::DocumentObject*);
virtual bool canDropObjects() const;
virtual bool canDropObject(App::DocumentObject*) const;
virtual void dropObject(App::DocumentObject*);
};
typedef Gui::ViewProviderPythonFeatureT<ViewProviderArea> ViewProviderAreaPython;
class PathGuiExport ViewProviderAreaView : public PartGui::ViewProviderPlaneParametric
{
PROPERTY_HEADER(PathGui::ViewProviderAreaView);
public:
ViewProviderAreaView();
virtual ~ViewProviderAreaView();
virtual std::vector<App::DocumentObject*> claimChildren(void) const;
virtual void updateData(const App::Property*);
virtual bool onDelete(const std::vector<std::string> &);
/// drag and drop
virtual bool canDragObjects() const;
virtual bool canDragObject(App::DocumentObject*) const;
virtual void dragObject(App::DocumentObject*);
virtual bool canDropObjects() const;
virtual bool canDropObject(App::DocumentObject*) const;
virtual void dropObject(App::DocumentObject*);
};
typedef Gui::ViewProviderPythonFeatureT<ViewProviderAreaView> ViewProviderAreaViewPython;
} //namespace PathGui
#endif // PATH_ViewProviderArea_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,125 +1,125 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_ViewProviderPath_H
#define PATH_ViewProviderPath_H
#include <App/PropertyGeo.h>
#include <Gui/Selection.h>
#include <Gui/ViewProviderGeometryObject.h>
#include <Gui/SoFCSelection.h>
#include <Gui/ViewProviderPythonFeature.h>
#include <Mod/Part/Gui/SoBrepEdgeSet.h>
class SoCoordinate3;
class SoDrawStyle;
class SoMaterial;
class SoBaseColor;
class SoMaterialBinding;
class SoTransform;
class SoSwitch;
namespace PathGui
{
class PathSelectionObserver;
class PathGuiExport ViewProviderPath : public Gui::ViewProviderGeometryObject
{
PROPERTY_HEADER(PathGui::ViewProviderPath);
typedef ViewProviderGeometryObject inherited;
public:
/// constructor.
ViewProviderPath();
/// destructor.
~ViewProviderPath();
// Display properties
App::PropertyInteger LineWidth;
App::PropertyColor NormalColor;
App::PropertyColor MarkerColor;
App::PropertyBool ShowNodes;
App::PropertyVector StartPosition;
App::PropertyIntegerConstraint StartIndex;
App::PropertyIntegerConstraint::Constraints StartIndexConstraints;
App::PropertyIntegerConstraint ShowCount;
App::PropertyIntegerConstraint::Constraints ShowCountConstraints;
void attach(App::DocumentObject *pcObject);
void setDisplayMode(const char* ModeName);
std::vector<std::string> getDisplayModes() const;
void updateData(const App::Property*);
void recomputeBoundingBox();
virtual QIcon getIcon() const;
virtual bool useNewSelectionModel(void) const;
virtual std::string getElement(const SoDetail *) const;
SoDetail* getDetail(const char* subelement) const;
void updateShowConstraints();
void updateVisual(bool rebuild = false);
void hideSelection();
virtual void showBoundingBox(bool show);
friend class PathSelectionObserver;
protected:
virtual void onChanged(const App::Property* prop);
virtual unsigned long getBoundColor() const;
SoCoordinate3 * pcLineCoords;
SoCoordinate3 * pcMarkerCoords;
SoDrawStyle * pcDrawStyle;
SoDrawStyle * pcMarkerStyle;
PartGui::SoBrepEdgeSet * pcLines;
SoMaterial * pcLineColor;
SoBaseColor * pcMarkerColor;
SoMaterialBinding * pcMatBind;
std::vector<int> colorindex;
SoSwitch * pcMarkerSwitch;
SoSwitch * pcArrowSwitch;
SoTransform * pcArrowTransform;
std::vector<int> command2Edge;
std::deque<int> edge2Command;
std::deque<int> edgeIndices;
mutable int pt0Index;
bool blockPropertyChange;
int edgeStart;
int coordStart;
int coordEnd;
};
typedef Gui::ViewProviderPythonFeatureT<ViewProviderPath> ViewProviderPathPython;
} //namespace PathGui
#endif // PATH_VIEWPROVIDERPATH_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_ViewProviderPath_H
#define PATH_ViewProviderPath_H
#include <App/PropertyGeo.h>
#include <Gui/Selection.h>
#include <Gui/ViewProviderGeometryObject.h>
#include <Gui/SoFCSelection.h>
#include <Gui/ViewProviderPythonFeature.h>
#include <Mod/Part/Gui/SoBrepEdgeSet.h>
class SoCoordinate3;
class SoDrawStyle;
class SoMaterial;
class SoBaseColor;
class SoMaterialBinding;
class SoTransform;
class SoSwitch;
namespace PathGui
{
class PathSelectionObserver;
class PathGuiExport ViewProviderPath : public Gui::ViewProviderGeometryObject
{
PROPERTY_HEADER(PathGui::ViewProviderPath);
typedef ViewProviderGeometryObject inherited;
public:
/// constructor.
ViewProviderPath();
/// destructor.
~ViewProviderPath();
// Display properties
App::PropertyInteger LineWidth;
App::PropertyColor NormalColor;
App::PropertyColor MarkerColor;
App::PropertyBool ShowNodes;
App::PropertyVector StartPosition;
App::PropertyIntegerConstraint StartIndex;
App::PropertyIntegerConstraint::Constraints StartIndexConstraints;
App::PropertyIntegerConstraint ShowCount;
App::PropertyIntegerConstraint::Constraints ShowCountConstraints;
void attach(App::DocumentObject *pcObject);
void setDisplayMode(const char* ModeName);
std::vector<std::string> getDisplayModes() const;
void updateData(const App::Property*);
void recomputeBoundingBox();
virtual QIcon getIcon() const;
virtual bool useNewSelectionModel(void) const;
virtual std::string getElement(const SoDetail *) const;
SoDetail* getDetail(const char* subelement) const;
void updateShowConstraints();
void updateVisual(bool rebuild = false);
void hideSelection();
virtual void showBoundingBox(bool show);
friend class PathSelectionObserver;
protected:
virtual void onChanged(const App::Property* prop);
virtual unsigned long getBoundColor() const;
SoCoordinate3 * pcLineCoords;
SoCoordinate3 * pcMarkerCoords;
SoDrawStyle * pcDrawStyle;
SoDrawStyle * pcMarkerStyle;
PartGui::SoBrepEdgeSet * pcLines;
SoMaterial * pcLineColor;
SoBaseColor * pcMarkerColor;
SoMaterialBinding * pcMatBind;
std::vector<int> colorindex;
SoSwitch * pcMarkerSwitch;
SoSwitch * pcArrowSwitch;
SoTransform * pcArrowTransform;
std::vector<int> command2Edge;
std::deque<int> edge2Command;
std::deque<int> edgeIndices;
mutable int pt0Index;
bool blockPropertyChange;
int edgeStart;
int coordStart;
int coordEnd;
};
typedef Gui::ViewProviderPythonFeatureT<ViewProviderPath> ViewProviderPathPython;
} //namespace PathGui
#endif // PATH_VIEWPROVIDERPATH_H

View File

@@ -1,97 +1,97 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Gui/Control.h>
#include <Gui/BitmapFactory.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include "TaskDlgPathCompound.h"
using namespace Gui;
using namespace PathGui;
PROPERTY_SOURCE(PathGui::ViewProviderPathCompound, PathGui::ViewProviderPath)
bool ViewProviderPathCompound::setEdit(int ModNum)
{
Q_UNUSED(ModNum);
Gui::TaskView::TaskDialog* dlg = new TaskDlgPathCompound(this);
Gui::Control().showDialog(dlg);
return true;
}
void ViewProviderPathCompound::unsetEdit(int ModNum)
{
Q_UNUSED(ModNum);
// when pressing ESC make sure to close the dialog
Gui::Control().closeDialog();
}
std::vector<App::DocumentObject*> ViewProviderPathCompound::claimChildren(void)const
{
return std::vector<App::DocumentObject*>(static_cast<Path::FeatureCompound *>(getObject())->Group.getValues());
}
bool ViewProviderPathCompound::canDragObjects() const
{
return true;
}
void ViewProviderPathCompound::dragObject(App::DocumentObject* obj)
{
static_cast<Path::FeatureCompound *>(getObject())->removeObject(obj);
}
bool ViewProviderPathCompound::canDropObjects() const
{
return true;
}
void ViewProviderPathCompound::dropObject(App::DocumentObject* obj)
{
static_cast<Path::FeatureCompound *>(getObject())->addObject(obj);
}
QIcon ViewProviderPathCompound::getIcon() const
{
return Gui::BitmapFactory().pixmap("Path-Compound");
}
// Python object -----------------------------------------------------------------------
namespace Gui {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(PathGui::ViewProviderPathCompoundPython, PathGui::ViewProviderPathCompound)
/// @endcond
// explicit template instantiation
template class PathGuiExport ViewProviderPythonFeatureT<PathGui::ViewProviderPathCompound>;
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Gui/Control.h>
#include <Gui/BitmapFactory.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include "TaskDlgPathCompound.h"
using namespace Gui;
using namespace PathGui;
PROPERTY_SOURCE(PathGui::ViewProviderPathCompound, PathGui::ViewProviderPath)
bool ViewProviderPathCompound::setEdit(int ModNum)
{
Q_UNUSED(ModNum);
Gui::TaskView::TaskDialog* dlg = new TaskDlgPathCompound(this);
Gui::Control().showDialog(dlg);
return true;
}
void ViewProviderPathCompound::unsetEdit(int ModNum)
{
Q_UNUSED(ModNum);
// when pressing ESC make sure to close the dialog
Gui::Control().closeDialog();
}
std::vector<App::DocumentObject*> ViewProviderPathCompound::claimChildren(void)const
{
return std::vector<App::DocumentObject*>(static_cast<Path::FeatureCompound *>(getObject())->Group.getValues());
}
bool ViewProviderPathCompound::canDragObjects() const
{
return true;
}
void ViewProviderPathCompound::dragObject(App::DocumentObject* obj)
{
static_cast<Path::FeatureCompound *>(getObject())->removeObject(obj);
}
bool ViewProviderPathCompound::canDropObjects() const
{
return true;
}
void ViewProviderPathCompound::dropObject(App::DocumentObject* obj)
{
static_cast<Path::FeatureCompound *>(getObject())->addObject(obj);
}
QIcon ViewProviderPathCompound::getIcon() const
{
return Gui::BitmapFactory().pixmap("Path-Compound");
}
// Python object -----------------------------------------------------------------------
namespace Gui {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(PathGui::ViewProviderPathCompoundPython, PathGui::ViewProviderPathCompound)
/// @endcond
// explicit template instantiation
template class PathGuiExport ViewProviderPythonFeatureT<PathGui::ViewProviderPathCompound>;
}

View File

@@ -1,56 +1,56 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_ViewProviderPathCompound_H
#define PATH_ViewProviderPathCompound_H
#include "ViewProviderPath.h"
namespace PathGui
{
class PathGuiExport ViewProviderPathCompound: public ViewProviderPath
{
PROPERTY_HEADER(PathGui::ViewProviderPathCompound);
public:
std::vector<App::DocumentObject*> claimChildren(void)const;
virtual bool canDragObjects() const;
virtual void dragObject(App::DocumentObject*);
virtual bool canDropObjects() const;
virtual void dropObject(App::DocumentObject*);
QIcon getIcon(void) const;
protected:
virtual bool setEdit(int ModNum);
virtual void unsetEdit(int ModNum);
};
typedef Gui::ViewProviderPythonFeatureT<ViewProviderPathCompound> ViewProviderPathCompoundPython;
} //namespace PathGui
#endif // PATH_ViewProviderPathCompound_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_ViewProviderPathCompound_H
#define PATH_ViewProviderPathCompound_H
#include "ViewProviderPath.h"
namespace PathGui
{
class PathGuiExport ViewProviderPathCompound: public ViewProviderPath
{
PROPERTY_HEADER(PathGui::ViewProviderPathCompound);
public:
std::vector<App::DocumentObject*> claimChildren(void)const;
virtual bool canDragObjects() const;
virtual void dragObject(App::DocumentObject*);
virtual bool canDropObjects() const;
virtual void dropObject(App::DocumentObject*);
QIcon getIcon(void) const;
protected:
virtual bool setEdit(int ModNum);
virtual void unsetEdit(int ModNum);
};
typedef Gui::ViewProviderPythonFeatureT<ViewProviderPathCompound> ViewProviderPathCompoundPython;
} //namespace PathGui
#endif // PATH_ViewProviderPathCompound_H

View File

@@ -1,114 +1,114 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Gui/BitmapFactory.h>
#include <Gui/Application.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Path/App/FeaturePathShape.h>
#include "ViewProviderPathShape.h"
using namespace Gui;
using namespace PathGui;
PROPERTY_SOURCE(PathGui::ViewProviderPathShape, PathGui::ViewProviderPath)
QIcon ViewProviderPathShape::getIcon() const
{
return Gui::BitmapFactory().pixmap("Path-Shape");
}
std::vector<App::DocumentObject*> ViewProviderPathShape::claimChildren(void) const
{
return std::vector<App::DocumentObject*>(
static_cast<Path::FeatureShape*>(getObject())->Sources.getValues());
}
bool ViewProviderPathShape::canDragObjects() const
{
return true;
}
bool ViewProviderPathShape::canDragObject(App::DocumentObject* obj) const
{
return obj && obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId());
}
void ViewProviderPathShape::dragObject(App::DocumentObject* obj)
{
Path::FeatureShape *feature = static_cast<Path::FeatureShape*>(getObject());
std::vector<App::DocumentObject*> sources = feature->Sources.getValues();
for (std::vector<App::DocumentObject*>::iterator it = sources.begin(); it != sources.end(); ++it) {
if (*it == obj) {
sources.erase(it);
feature->Sources.setValues(sources);
break;
}
}
}
bool ViewProviderPathShape::canDropObjects() const
{
return true;
}
bool ViewProviderPathShape::canDropObject(App::DocumentObject* obj) const
{
return canDragObject(obj);
}
void ViewProviderPathShape::dropObject(App::DocumentObject* obj)
{
Path::FeatureShape *feature = static_cast<Path::FeatureShape*>(getObject());
std::vector<App::DocumentObject*> sources = feature->Sources.getValues();
sources.push_back(obj);
feature->Sources.setValues(sources);
}
void ViewProviderPathShape::updateData(const App::Property* prop)
{
PathGui::ViewProviderPath::updateData(prop);
if (prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId())) {
std::vector<App::DocumentObject*> pShapes = static_cast<const App::PropertyLinkList*>(prop)->getValues();
for (std::vector<App::DocumentObject*>::iterator it = pShapes.begin(); it != pShapes.end(); ++it) {
if (*it)
Gui::Application::Instance->hideViewProvider(*it);
}
}
}
bool ViewProviderPathShape::onDelete(const std::vector<std::string> &)
{
// get the input shapes
Path::FeatureShape *feature = static_cast<Path::FeatureShape*>(getObject());
std::vector<App::DocumentObject*> pShapes =feature->Sources.getValues();
for (std::vector<App::DocumentObject*>::iterator it = pShapes.begin(); it != pShapes.end(); ++it) {
if (*it)
Gui::Application::Instance->showViewProvider(*it);
}
return true;
}
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Gui/BitmapFactory.h>
#include <Gui/Application.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Path/App/FeaturePathShape.h>
#include "ViewProviderPathShape.h"
using namespace Gui;
using namespace PathGui;
PROPERTY_SOURCE(PathGui::ViewProviderPathShape, PathGui::ViewProviderPath)
QIcon ViewProviderPathShape::getIcon() const
{
return Gui::BitmapFactory().pixmap("Path-Shape");
}
std::vector<App::DocumentObject*> ViewProviderPathShape::claimChildren(void) const
{
return std::vector<App::DocumentObject*>(
static_cast<Path::FeatureShape*>(getObject())->Sources.getValues());
}
bool ViewProviderPathShape::canDragObjects() const
{
return true;
}
bool ViewProviderPathShape::canDragObject(App::DocumentObject* obj) const
{
return obj && obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId());
}
void ViewProviderPathShape::dragObject(App::DocumentObject* obj)
{
Path::FeatureShape *feature = static_cast<Path::FeatureShape*>(getObject());
std::vector<App::DocumentObject*> sources = feature->Sources.getValues();
for (std::vector<App::DocumentObject*>::iterator it = sources.begin(); it != sources.end(); ++it) {
if (*it == obj) {
sources.erase(it);
feature->Sources.setValues(sources);
break;
}
}
}
bool ViewProviderPathShape::canDropObjects() const
{
return true;
}
bool ViewProviderPathShape::canDropObject(App::DocumentObject* obj) const
{
return canDragObject(obj);
}
void ViewProviderPathShape::dropObject(App::DocumentObject* obj)
{
Path::FeatureShape *feature = static_cast<Path::FeatureShape*>(getObject());
std::vector<App::DocumentObject*> sources = feature->Sources.getValues();
sources.push_back(obj);
feature->Sources.setValues(sources);
}
void ViewProviderPathShape::updateData(const App::Property* prop)
{
PathGui::ViewProviderPath::updateData(prop);
if (prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId())) {
std::vector<App::DocumentObject*> pShapes = static_cast<const App::PropertyLinkList*>(prop)->getValues();
for (std::vector<App::DocumentObject*>::iterator it = pShapes.begin(); it != pShapes.end(); ++it) {
if (*it)
Gui::Application::Instance->hideViewProvider(*it);
}
}
}
bool ViewProviderPathShape::onDelete(const std::vector<std::string> &)
{
// get the input shapes
Path::FeatureShape *feature = static_cast<Path::FeatureShape*>(getObject());
std::vector<App::DocumentObject*> pShapes =feature->Sources.getValues();
for (std::vector<App::DocumentObject*>::iterator it = pShapes.begin(); it != pShapes.end(); ++it) {
if (*it)
Gui::Application::Instance->showViewProvider(*it);
}
return true;
}

View File

@@ -1,57 +1,57 @@
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_ViewProviderPathShape_H
#define PATH_ViewProviderPathShape_H
#include "ViewProviderPath.h"
namespace PathGui
{
class PathGuiExport ViewProviderPathShape: public ViewProviderPath
{
PROPERTY_HEADER(PathGui::ViewProviderPathShape);
public:
/// grouping handling
virtual std::vector<App::DocumentObject*> claimChildren(void) const;
virtual void updateData(const App::Property*);
virtual bool onDelete(const std::vector<std::string> &);
/// drag and drop
virtual bool canDragObjects() const;
virtual bool canDragObject(App::DocumentObject*) const;
virtual void dragObject(App::DocumentObject*);
virtual bool canDropObjects() const;
virtual bool canDropObject(App::DocumentObject*) const;
virtual void dropObject(App::DocumentObject*);
QIcon getIcon(void) const;
};
} //namespace PathGui
#endif // PATH_ViewProviderPathShape_H
/***************************************************************************
* Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef PATH_ViewProviderPathShape_H
#define PATH_ViewProviderPathShape_H
#include "ViewProviderPath.h"
namespace PathGui
{
class PathGuiExport ViewProviderPathShape: public ViewProviderPath
{
PROPERTY_HEADER(PathGui::ViewProviderPathShape);
public:
/// grouping handling
virtual std::vector<App::DocumentObject*> claimChildren(void) const;
virtual void updateData(const App::Property*);
virtual bool onDelete(const std::vector<std::string> &);
/// drag and drop
virtual bool canDragObjects() const;
virtual bool canDragObject(App::DocumentObject*) const;
virtual void dragObject(App::DocumentObject*);
virtual bool canDropObjects() const;
virtual bool canDropObject(App::DocumentObject*) const;
virtual void dropObject(App::DocumentObject*);
QIcon getIcon(void) const;
};
} //namespace PathGui
#endif // PATH_ViewProviderPathShape_H

View File

@@ -1,32 +1,32 @@
#***************************************************************************
#* (c) Yorik van Havre (yorik@uncreated.net) 2014 *
#* *
#* This file is part of the FreeCAD CAx development system. *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* FreeCAD 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 Lesser General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with FreeCAD; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************/
# Get the Parameter Group of this module
ParGrp = App.ParamGet("System parameter:Modules").GetGroup("Path")
# Set the needed information
ParGrp.SetString("HelpIndex", "Path/Help/index.html")
ParGrp.SetString("WorkBenchName", "Path")
ParGrp.SetString("WorkBenchModule", "PathWorkbench.py")
FreeCAD.__unit_test__ += [ "TestPathApp" ]
#***************************************************************************
#* (c) Yorik van Havre (yorik@uncreated.net) 2014 *
#* *
#* This file is part of the FreeCAD CAx development system. *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* FreeCAD 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 Lesser General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with FreeCAD; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************/
# Get the Parameter Group of this module
ParGrp = App.ParamGet("System parameter:Modules").GetGroup("Path")
# Set the needed information
ParGrp.SetString("HelpIndex", "Path/Help/index.html")
ParGrp.SetString("WorkBenchName", "Path")
ParGrp.SetString("WorkBenchModule", "PathWorkbench.py")
FreeCAD.__unit_test__ += [ "TestPathApp" ]

View File

@@ -1,197 +1,197 @@
# ***************************************************************************
# * (c) Yorik van Havre (yorik@uncreated.net) 2014 *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD 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 Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************/
class PathCommandGroup:
def __init__(self, cmdlist, menu, tooltip=None):
self.cmdlist = cmdlist
self.menu = menu
if tooltip is None:
self.tooltip = menu
else:
self.tooltip = tooltip
def GetCommands(self):
return tuple(self.cmdlist)
def GetResources(self):
return {'MenuText': self.menu, 'ToolTip': self.tooltip}
def IsActive(self):
if FreeCAD.ActiveDocument is not None:
for o in FreeCAD.ActiveDocument.Objects:
if o.Name[:3] == "Job":
return True
return False
class PathWorkbench (Workbench):
"Path workbench"
def __init__(self):
self.__class__.Icon = FreeCAD.getResourceDir() + "Mod/Path/Resources/icons/PathWorkbench.svg"
self.__class__.MenuText = "Path"
self.__class__.ToolTip = "Path workbench"
def Initialize(self):
global PathCommandGroup
# Add preferences pages - before loading PathGui to properly order pages of Path group
from PathScripts import PathPreferencesPathJob, PathPreferencesPathDressup
FreeCADGui.addPreferencePage(PathPreferencesPathJob.JobPreferencesPage, "Path")
FreeCADGui.addPreferencePage(PathPreferencesPathDressup.DressupPreferencesPage, "Path")
# Check enablement of experimental features
from PathScripts import PathPreferences
# load the builtin modules
import Path
import PathScripts
import PathGui
from PySide import QtCore, QtGui
FreeCADGui.addLanguagePath(":/translations")
FreeCADGui.addIconPath(":/icons")
from PathScripts import PathGuiInit
from PathScripts import PathJobCmd
from PathScripts import PathToolBitCmd
from PathScripts import PathToolBitLibraryCmd
if PathPreferences.experimentalFeaturesEnabled():
toolbitcmdlist = PathToolBitCmd.CommandList + ["Separator"] + PathToolBitLibraryCmd.CommandList + ["Path_ToolController", "Separator"]
self.toolbitctxmenu = ["Path_ToolBitLibraryLoad", "Path_ToolController"]
else:
toolbitcmdlist = []
self.toolbitctxmenu = []
import PathCommands
PathGuiInit.Startup()
# build commands list
projcmdlist = ["Path_Job", "Path_Post"]
toolcmdlist = ["Path_Inspect", "Path_Simulator", "Path_ToolLibraryEdit", "Path_SelectLoop", "Path_OpActiveToggle"]
prepcmdlist = ["Path_Fixture", "Path_Comment", "Path_Stop", "Path_Custom", "Path_Probe"]
# twodopcmdlist = ["Path_Profile", "Path_Contour", "Path_Profile_Faces", "Path_Profile_Edges", "Path_Pocket_Shape", "Path_Drilling", "Path_MillFace", "Path_Helix", "Path_Adaptive"]
twodopcmdlist = ["Path_Profile", "Path_Pocket_Shape", "Path_Drilling", "Path_MillFace", "Path_Helix", "Path_Adaptive"]
threedopcmdlist = ["Path_Pocket_3D"]
engravecmdlist = ["Path_Engrave", "Path_Deburr"]
modcmdlist = ["Path_OperationCopy", "Path_Array", "Path_SimpleCopy"]
dressupcmdlist = ["Path_DressupAxisMap", "Path_DressupPathBoundary", "Path_DressupDogbone", "Path_DressupDragKnife", "Path_DressupLeadInOut", "Path_DressupRampEntry", "Path_DressupTag", "Path_DressupZCorrect"]
extracmdlist = []
# modcmdmore = ["Path_Hop",]
# remotecmdlist = ["Path_Remote"]
engravecmdgroup = ['Path_EngraveTools']
FreeCADGui.addCommand('Path_EngraveTools', PathCommandGroup(engravecmdlist, QtCore.QT_TRANSLATE_NOOP("Path", 'Engraving Operations')))
threedcmdgroup = threedopcmdlist
if PathPreferences.experimentalFeaturesEnabled():
projcmdlist.append("Path_Sanity")
prepcmdlist.append("Path_Shape")
extracmdlist.extend(["Path_Area", "Path_Area_Workplane"])
try:
import ocl # pylint: disable=unused-variable
from PathScripts import PathSurfaceGui
from PathScripts import PathWaterlineGui
threedopcmdlist.extend(["Path_Surface", "Path_Waterline"])
threedcmdgroup = ['Path_3dTools']
FreeCADGui.addCommand('Path_3dTools', PathCommandGroup(threedopcmdlist, QtCore.QT_TRANSLATE_NOOP("Path", '3D Operations')))
except ImportError:
FreeCAD.Console.PrintError("OpenCamLib is not working!\n")
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "Project Setup"), projcmdlist)
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "Tool Commands"), toolcmdlist)
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "New Operations"), twodopcmdlist+engravecmdgroup+threedcmdgroup)
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "Path Modification"), modcmdlist)
if extracmdlist:
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "Helpful Tools"), extracmdlist)
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path")], projcmdlist + ["Path_ExportTemplate", "Separator"] +
toolbitcmdlist + toolcmdlist + ["Separator"] + twodopcmdlist + engravecmdlist + ["Separator"] +
threedopcmdlist + ["Separator"])
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path"), QtCore.QT_TRANSLATE_NOOP(
"Path", "Path Dressup")], dressupcmdlist)
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path"), QtCore.QT_TRANSLATE_NOOP(
"Path", "Supplemental Commands")], prepcmdlist)
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path"), QtCore.QT_TRANSLATE_NOOP(
"Path", "Path Modification")], modcmdlist)
if extracmdlist:
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path")], extracmdlist)
self.dressupcmds = dressupcmdlist
curveAccuracy = PathPreferences.defaultLibAreaCurveAccuracy()
if curveAccuracy:
Path.Area.setDefaultParams(Accuracy=curveAccuracy)
Log('Loading Path workbench... done\n')
def GetClassName(self):
return "Gui::PythonWorkbench"
def Activated(self):
# update the translation engine
FreeCADGui.updateLocale()
Msg("Path workbench activated\n")
def Deactivated(self):
Msg("Path workbench deactivated\n")
def ContextMenu(self, recipient):
import PathScripts
menuAppended = False
if len(FreeCADGui.Selection.getSelection()) == 1:
obj = FreeCADGui.Selection.getSelection()[0]
if obj.isDerivedFrom("Path::Feature"):
self.appendContextMenu("", "Separator")
self.appendContextMenu("", ["Path_Inspect"])
selectedName = obj.Name
if "Remote" in selectedName:
self.appendContextMenu("", ["Refresh_Path"])
if "Job" in selectedName:
self.appendContextMenu("", ["Path_ExportTemplate"] + self.toolbitctxmenu)
menuAppended = True
if isinstance(obj.Proxy, PathScripts.PathOp.ObjectOp):
self.appendContextMenu("", ["Path_OperationCopy", "Path_OpActiveToggle"])
menuAppended = True
if obj.isDerivedFrom("Path::Feature"):
if "Profile" in selectedName or "Contour" in selectedName or "Dressup" in selectedName:
self.appendContextMenu("", "Separator")
# self.appendContextMenu("", ["Set_StartPoint"])
# self.appendContextMenu("", ["Set_EndPoint"])
for cmd in self.dressupcmds:
self.appendContextMenu("", [cmd])
menuAppended = True
if isinstance(obj.Proxy, PathScripts.PathToolBit.ToolBit):
self.appendContextMenu("", ["Path_ToolBitSave", "Path_ToolBitSaveAs"])
menuAppended = True
if menuAppended:
self.appendContextMenu("", "Separator")
Gui.addWorkbench(PathWorkbench())
FreeCAD.addImportType(
"GCode (*.nc *.gc *.ncc *.ngc *.cnc *.tap *.gcode)", "PathGui")
# FreeCAD.addExportType(
# "GCode (*.nc *.gc *.ncc *.ngc *.cnc *.tap *.gcode)", "PathGui")
# ***************************************************************************
# * (c) Yorik van Havre (yorik@uncreated.net) 2014 *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD 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 Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************/
class PathCommandGroup:
def __init__(self, cmdlist, menu, tooltip=None):
self.cmdlist = cmdlist
self.menu = menu
if tooltip is None:
self.tooltip = menu
else:
self.tooltip = tooltip
def GetCommands(self):
return tuple(self.cmdlist)
def GetResources(self):
return {'MenuText': self.menu, 'ToolTip': self.tooltip}
def IsActive(self):
if FreeCAD.ActiveDocument is not None:
for o in FreeCAD.ActiveDocument.Objects:
if o.Name[:3] == "Job":
return True
return False
class PathWorkbench (Workbench):
"Path workbench"
def __init__(self):
self.__class__.Icon = FreeCAD.getResourceDir() + "Mod/Path/Resources/icons/PathWorkbench.svg"
self.__class__.MenuText = "Path"
self.__class__.ToolTip = "Path workbench"
def Initialize(self):
global PathCommandGroup
# Add preferences pages - before loading PathGui to properly order pages of Path group
from PathScripts import PathPreferencesPathJob, PathPreferencesPathDressup
FreeCADGui.addPreferencePage(PathPreferencesPathJob.JobPreferencesPage, "Path")
FreeCADGui.addPreferencePage(PathPreferencesPathDressup.DressupPreferencesPage, "Path")
# Check enablement of experimental features
from PathScripts import PathPreferences
# load the builtin modules
import Path
import PathScripts
import PathGui
from PySide import QtCore, QtGui
FreeCADGui.addLanguagePath(":/translations")
FreeCADGui.addIconPath(":/icons")
from PathScripts import PathGuiInit
from PathScripts import PathJobCmd
from PathScripts import PathToolBitCmd
from PathScripts import PathToolBitLibraryCmd
if PathPreferences.experimentalFeaturesEnabled():
toolbitcmdlist = PathToolBitCmd.CommandList + ["Separator"] + PathToolBitLibraryCmd.CommandList + ["Path_ToolController", "Separator"]
self.toolbitctxmenu = ["Path_ToolBitLibraryLoad", "Path_ToolController"]
else:
toolbitcmdlist = []
self.toolbitctxmenu = []
import PathCommands
PathGuiInit.Startup()
# build commands list
projcmdlist = ["Path_Job", "Path_Post"]
toolcmdlist = ["Path_Inspect", "Path_Simulator", "Path_ToolLibraryEdit", "Path_SelectLoop", "Path_OpActiveToggle"]
prepcmdlist = ["Path_Fixture", "Path_Comment", "Path_Stop", "Path_Custom", "Path_Probe"]
# twodopcmdlist = ["Path_Profile", "Path_Contour", "Path_Profile_Faces", "Path_Profile_Edges", "Path_Pocket_Shape", "Path_Drilling", "Path_MillFace", "Path_Helix", "Path_Adaptive"]
twodopcmdlist = ["Path_Profile", "Path_Pocket_Shape", "Path_Drilling", "Path_MillFace", "Path_Helix", "Path_Adaptive"]
threedopcmdlist = ["Path_Pocket_3D"]
engravecmdlist = ["Path_Engrave", "Path_Deburr"]
modcmdlist = ["Path_OperationCopy", "Path_Array", "Path_SimpleCopy"]
dressupcmdlist = ["Path_DressupAxisMap", "Path_DressupPathBoundary", "Path_DressupDogbone", "Path_DressupDragKnife", "Path_DressupLeadInOut", "Path_DressupRampEntry", "Path_DressupTag", "Path_DressupZCorrect"]
extracmdlist = []
# modcmdmore = ["Path_Hop",]
# remotecmdlist = ["Path_Remote"]
engravecmdgroup = ['Path_EngraveTools']
FreeCADGui.addCommand('Path_EngraveTools', PathCommandGroup(engravecmdlist, QtCore.QT_TRANSLATE_NOOP("Path", 'Engraving Operations')))
threedcmdgroup = threedopcmdlist
if PathPreferences.experimentalFeaturesEnabled():
projcmdlist.append("Path_Sanity")
prepcmdlist.append("Path_Shape")
extracmdlist.extend(["Path_Area", "Path_Area_Workplane"])
try:
import ocl # pylint: disable=unused-variable
from PathScripts import PathSurfaceGui
from PathScripts import PathWaterlineGui
threedopcmdlist.extend(["Path_Surface", "Path_Waterline"])
threedcmdgroup = ['Path_3dTools']
FreeCADGui.addCommand('Path_3dTools', PathCommandGroup(threedopcmdlist, QtCore.QT_TRANSLATE_NOOP("Path", '3D Operations')))
except ImportError:
FreeCAD.Console.PrintError("OpenCamLib is not working!\n")
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "Project Setup"), projcmdlist)
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "Tool Commands"), toolcmdlist)
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "New Operations"), twodopcmdlist+engravecmdgroup+threedcmdgroup)
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "Path Modification"), modcmdlist)
if extracmdlist:
self.appendToolbar(QtCore.QT_TRANSLATE_NOOP("Path", "Helpful Tools"), extracmdlist)
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path")], projcmdlist + ["Path_ExportTemplate", "Separator"] +
toolbitcmdlist + toolcmdlist + ["Separator"] + twodopcmdlist + engravecmdlist + ["Separator"] +
threedopcmdlist + ["Separator"])
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path"), QtCore.QT_TRANSLATE_NOOP(
"Path", "Path Dressup")], dressupcmdlist)
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path"), QtCore.QT_TRANSLATE_NOOP(
"Path", "Supplemental Commands")], prepcmdlist)
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path"), QtCore.QT_TRANSLATE_NOOP(
"Path", "Path Modification")], modcmdlist)
if extracmdlist:
self.appendMenu([QtCore.QT_TRANSLATE_NOOP("Path", "&Path")], extracmdlist)
self.dressupcmds = dressupcmdlist
curveAccuracy = PathPreferences.defaultLibAreaCurveAccuracy()
if curveAccuracy:
Path.Area.setDefaultParams(Accuracy=curveAccuracy)
Log('Loading Path workbench... done\n')
def GetClassName(self):
return "Gui::PythonWorkbench"
def Activated(self):
# update the translation engine
FreeCADGui.updateLocale()
Msg("Path workbench activated\n")
def Deactivated(self):
Msg("Path workbench deactivated\n")
def ContextMenu(self, recipient):
import PathScripts
menuAppended = False
if len(FreeCADGui.Selection.getSelection()) == 1:
obj = FreeCADGui.Selection.getSelection()[0]
if obj.isDerivedFrom("Path::Feature"):
self.appendContextMenu("", "Separator")
self.appendContextMenu("", ["Path_Inspect"])
selectedName = obj.Name
if "Remote" in selectedName:
self.appendContextMenu("", ["Refresh_Path"])
if "Job" in selectedName:
self.appendContextMenu("", ["Path_ExportTemplate"] + self.toolbitctxmenu)
menuAppended = True
if isinstance(obj.Proxy, PathScripts.PathOp.ObjectOp):
self.appendContextMenu("", ["Path_OperationCopy", "Path_OpActiveToggle"])
menuAppended = True
if obj.isDerivedFrom("Path::Feature"):
if "Profile" in selectedName or "Contour" in selectedName or "Dressup" in selectedName:
self.appendContextMenu("", "Separator")
# self.appendContextMenu("", ["Set_StartPoint"])
# self.appendContextMenu("", ["Set_EndPoint"])
for cmd in self.dressupcmds:
self.appendContextMenu("", [cmd])
menuAppended = True
if isinstance(obj.Proxy, PathScripts.PathToolBit.ToolBit):
self.appendContextMenu("", ["Path_ToolBitSave", "Path_ToolBitSaveAs"])
menuAppended = True
if menuAppended:
self.appendContextMenu("", "Separator")
Gui.addWorkbench(PathWorkbench())
FreeCAD.addImportType(
"GCode (*.nc *.gc *.ncc *.ngc *.cnc *.tap *.gcode)", "PathGui")
# FreeCAD.addExportType(
# "GCode (*.nc *.gc *.ncc *.ngc *.cnc *.tap *.gcode)", "PathGui")

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,116 +1,116 @@
# *********************************************************************************************
# * Copyright (c) 2019/2020 Rene 'Renne' Bartsch, B.Sc. Informatics <rene@bartschnet.de> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD 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 Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ********************************************************************************************/
import FreeCAD
import PathScripts
from PathScripts import PostUtils
import datetime
TOOLTIP='''
This is a postprocessor file for the Path workbench. It is used to take
a pseudo-gcode fragment outputted by a Path object and output real GCode
suitable for the Max Computer GmbH nccad9 Computer Numeric Control.
Supported features:
- 3-axis milling
- manual tool change with tool number as comment
- spindle speed as comment
!!! gCode files must use the suffix .knc !!!'''
MACHINE_NAME = '''Max Computer GmbH nccad9 MCS/KOSY'''
# gCode for changing tools
# M01 <String> ; Displays <String> and waits for user interaction
TOOL_CHANGE = '''G77 ; Move to release position
M10 O6.0 ; Stop spindle
M01 Insert tool TOOL
G76 ; Move to reference point to ensure correct coordinates after tool change
M10 O6.1 ; Start spindel'''
# gCode finishing the program
POSTAMBLE = '''G77 ; Move to release position
M10 O6.0 ; Stop spindle'''
# gCode header with information about CAD-software, post-processor and date/time
HEADER = ''';Exported by FreeCAD
;Post Processor: {}
;CAM file: {}
;Output Time: {}
'''.format(__name__, FreeCAD.ActiveDocument.FileName, str(datetime.datetime.now()))
def export(objectslist, filename, argstring):
gcode = HEADER
for obj in objectslist:
for command in obj.Path.Commands:
# Manipulate tool change commands
if 'M6' == command.Name:
gcode += TOOL_CHANGE.replace('TOOL', str(int(command.Parameters['T'])))
# Convert spindle speed (rpm) command to comment
elif 'M3' == command.Name:
gcode += 'M01 Set spindle speed to ' + str(int(command.Parameters['S'])) + ' rounds per minute'
# Add other commands
else:
gcode += command.Name
# Loop through command parameters
for parameter, value in command.Parameters.items():
# Multiply F parameter value by 10 (FreeCAD = mm/s, nccad = 1/10 mm/s)
if 'F' == parameter:
value *= 10
# Add command parameters and values and round float as nccad9 does not support exponents
gcode += ' ' + parameter + str(round(value, 5))
gcode += '\n'
gcode += POSTAMBLE + '\n'
# Open editor window
if FreeCAD.GuiUp:
dia = PostUtils.GCodeEditorDialog()
dia.editor.setText(gcode)
result = dia.exec_()
if result:
gcode = dia.editor.toPlainText()
# Save to file
if filename != '-':
gfile = open(filename, "w")
gfile.write(gcode)
gfile.close()
return filename
# *********************************************************************************************
# * Copyright (c) 2019/2020 Rene 'Renne' Bartsch, B.Sc. Informatics <rene@bartschnet.de> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD 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 Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ********************************************************************************************/
import FreeCAD
import PathScripts
from PathScripts import PostUtils
import datetime
TOOLTIP='''
This is a postprocessor file for the Path workbench. It is used to take
a pseudo-gcode fragment outputted by a Path object and output real GCode
suitable for the Max Computer GmbH nccad9 Computer Numeric Control.
Supported features:
- 3-axis milling
- manual tool change with tool number as comment
- spindle speed as comment
!!! gCode files must use the suffix .knc !!!'''
MACHINE_NAME = '''Max Computer GmbH nccad9 MCS/KOSY'''
# gCode for changing tools
# M01 <String> ; Displays <String> and waits for user interaction
TOOL_CHANGE = '''G77 ; Move to release position
M10 O6.0 ; Stop spindle
M01 Insert tool TOOL
G76 ; Move to reference point to ensure correct coordinates after tool change
M10 O6.1 ; Start spindel'''
# gCode finishing the program
POSTAMBLE = '''G77 ; Move to release position
M10 O6.0 ; Stop spindle'''
# gCode header with information about CAD-software, post-processor and date/time
HEADER = ''';Exported by FreeCAD
;Post Processor: {}
;CAM file: {}
;Output Time: {}
'''.format(__name__, FreeCAD.ActiveDocument.FileName, str(datetime.datetime.now()))
def export(objectslist, filename, argstring):
gcode = HEADER
for obj in objectslist:
for command in obj.Path.Commands:
# Manipulate tool change commands
if 'M6' == command.Name:
gcode += TOOL_CHANGE.replace('TOOL', str(int(command.Parameters['T'])))
# Convert spindle speed (rpm) command to comment
elif 'M3' == command.Name:
gcode += 'M01 Set spindle speed to ' + str(int(command.Parameters['S'])) + ' rounds per minute'
# Add other commands
else:
gcode += command.Name
# Loop through command parameters
for parameter, value in command.Parameters.items():
# Multiply F parameter value by 10 (FreeCAD = mm/s, nccad = 1/10 mm/s)
if 'F' == parameter:
value *= 10
# Add command parameters and values and round float as nccad9 does not support exponents
gcode += ' ' + parameter + str(round(value, 5))
gcode += '\n'
gcode += POSTAMBLE + '\n'
# Open editor window
if FreeCAD.GuiUp:
dia = PostUtils.GCodeEditorDialog()
dia.editor.setText(gcode)
result = dia.exec_()
if result:
gcode = dia.editor.toPlainText()
# Save to file
if filename != '-':
gfile = open(filename, "w")
gfile.write(gcode)
gfile.close()
return filename

View File

@@ -1,122 +1,122 @@
// Arc.cpp
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "Arc.h"
#include "Curve.h"
void CArc::SetDirWithPoint(const Point& p)
{
double angs = atan2(m_s.y - m_c.y, m_s.x - m_c.x);
double ange = atan2(m_e.y - m_c.y, m_e.x - m_c.x);
double angp = atan2(p.y - m_c.y, p.x - m_c.x);
if(ange < angs)ange += 6.2831853071795864;
if(angp < angs - 0.0000000000001)angp += 6.2831853071795864;
if(angp > ange + 0.0000000000001)m_dir = false;
else m_dir = true;
}
double CArc::IncludedAngle()const
{
double angs = atan2(m_s.y - m_c.y, m_s.x - m_c.x);
double ange = atan2(m_e.y - m_c.y, m_e.x - m_c.x);
if(m_dir)
{
// make sure ange > angs
if(ange < angs)ange += 6.2831853071795864;
}
else
{
// make sure angs > ange
if(angs < ange)angs += 6.2831853071795864;
}
return fabs(ange - angs);
}
bool CArc::AlmostALine()const
{
Point mid_point = MidParam(0.5);
if(Line(m_s, m_e - m_s).Dist(mid_point) <= Point::tolerance)
return true;
const double max_arc_radius = 1.0 / Point::tolerance;
double radius = m_c.dist(m_s);
if (radius > max_arc_radius)
{
return true; // We don't want to produce an arc whose radius is too large.
}
return false;
}
Point CArc::MidParam(double param)const {
/// returns a point which is 0-1 along arc
if(fabs(param) < 0.00000000000001)return m_s;
if(fabs(param - 1.0) < 0.00000000000001)return m_e;
Point p;
Point v = m_s - m_c;
v.Rotate(param * IncludedAngle());
p = v + m_c;
return p;
}
//segments - number of segments per full revolution!
//d_angle - determines the direction and the amount of the arc to draw
void CArc::GetSegments(void(*callbackfunc)(const double *p), double pixels_per_mm)const
{
if(m_s == m_e)
return;
Point Va = m_s - m_c;
Point Vb = m_e - m_c;
double start_angle = atan2(Va.y, Va.x);
double end_angle = atan2(Vb.y, Vb.x);
if(m_dir)
{
if(start_angle > end_angle)end_angle += 6.28318530717958;
}
else
{
if(start_angle < end_angle)end_angle -= 6.28318530717958;
}
double radius = m_c.dist(m_s);
double d_angle = end_angle - start_angle;
int segments = (int)(fabs(pixels_per_mm * radius * d_angle / 6.28318530717958 + 1));
double theta = d_angle / (double)segments;
while(theta>1.0){segments*=2;theta = d_angle / (double)segments;}
double tangential_factor = tan(theta);
double radial_factor = 1 - cos(theta);
double x = radius * cos(start_angle);
double y = radius * sin(start_angle);
double pp[3] = {0.0, 0.0, 0.0};
for(int i = 0; i < segments + 1; i++)
{
Point p = m_c + Point(x, y);
pp[0] = p.x;
pp[1] = p.y;
(*callbackfunc)(pp);
double tx = -y;
double ty = x;
x += tx * tangential_factor;
y += ty * tangential_factor;
double rx = - x;
double ry = - y;
x += rx * radial_factor;
y += ry * radial_factor;
}
// Arc.cpp
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "Arc.h"
#include "Curve.h"
void CArc::SetDirWithPoint(const Point& p)
{
double angs = atan2(m_s.y - m_c.y, m_s.x - m_c.x);
double ange = atan2(m_e.y - m_c.y, m_e.x - m_c.x);
double angp = atan2(p.y - m_c.y, p.x - m_c.x);
if(ange < angs)ange += 6.2831853071795864;
if(angp < angs - 0.0000000000001)angp += 6.2831853071795864;
if(angp > ange + 0.0000000000001)m_dir = false;
else m_dir = true;
}
double CArc::IncludedAngle()const
{
double angs = atan2(m_s.y - m_c.y, m_s.x - m_c.x);
double ange = atan2(m_e.y - m_c.y, m_e.x - m_c.x);
if(m_dir)
{
// make sure ange > angs
if(ange < angs)ange += 6.2831853071795864;
}
else
{
// make sure angs > ange
if(angs < ange)angs += 6.2831853071795864;
}
return fabs(ange - angs);
}
bool CArc::AlmostALine()const
{
Point mid_point = MidParam(0.5);
if(Line(m_s, m_e - m_s).Dist(mid_point) <= Point::tolerance)
return true;
const double max_arc_radius = 1.0 / Point::tolerance;
double radius = m_c.dist(m_s);
if (radius > max_arc_radius)
{
return true; // We don't want to produce an arc whose radius is too large.
}
return false;
}
Point CArc::MidParam(double param)const {
/// returns a point which is 0-1 along arc
if(fabs(param) < 0.00000000000001)return m_s;
if(fabs(param - 1.0) < 0.00000000000001)return m_e;
Point p;
Point v = m_s - m_c;
v.Rotate(param * IncludedAngle());
p = v + m_c;
return p;
}
//segments - number of segments per full revolution!
//d_angle - determines the direction and the amount of the arc to draw
void CArc::GetSegments(void(*callbackfunc)(const double *p), double pixels_per_mm)const
{
if(m_s == m_e)
return;
Point Va = m_s - m_c;
Point Vb = m_e - m_c;
double start_angle = atan2(Va.y, Va.x);
double end_angle = atan2(Vb.y, Vb.x);
if(m_dir)
{
if(start_angle > end_angle)end_angle += 6.28318530717958;
}
else
{
if(start_angle < end_angle)end_angle -= 6.28318530717958;
}
double radius = m_c.dist(m_s);
double d_angle = end_angle - start_angle;
int segments = (int)(fabs(pixels_per_mm * radius * d_angle / 6.28318530717958 + 1));
double theta = d_angle / (double)segments;
while(theta>1.0){segments*=2;theta = d_angle / (double)segments;}
double tangential_factor = tan(theta);
double radial_factor = 1 - cos(theta);
double x = radius * cos(start_angle);
double y = radius * sin(start_angle);
double pp[3] = {0.0, 0.0, 0.0};
for(int i = 0; i < segments + 1; i++)
{
Point p = m_c + Point(x, y);
pp[0] = p.x;
pp[1] = p.y;
(*callbackfunc)(pp);
double tx = -y;
double ty = x;
x += tx * tangential_factor;
y += ty * tangential_factor;
double rx = - x;
double ry = - y;
x += rx * radial_factor;
y += ry * radial_factor;
}
}

View File

@@ -1,25 +1,25 @@
// Arc.h
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
#include "Point.h"
class CArc{
public:
Point m_s;
Point m_e;
Point m_c;
bool m_dir; // true - anti-clockwise, false - clockwise
int m_user_data;
CArc():m_dir(true), m_user_data(0){}
CArc(const Point& s, const Point& e, const Point& c, bool dir, int user_data):m_s(s), m_e(e), m_c(c), m_dir(dir), m_user_data(user_data){}
void SetDirWithPoint(const Point& p); // set m_dir, such that this point lies between m_s and m_e
double IncludedAngle()const; // always > 0
bool AlmostALine()const;
Point MidParam(double param)const;
void GetSegments(void(*callbackfunc)(const double *p), double pixels_per_mm)const;
// Arc.h
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
#include "Point.h"
class CArc{
public:
Point m_s;
Point m_e;
Point m_c;
bool m_dir; // true - anti-clockwise, false - clockwise
int m_user_data;
CArc():m_dir(true), m_user_data(0){}
CArc(const Point& s, const Point& e, const Point& c, bool dir, int user_data):m_s(s), m_e(e), m_c(c), m_dir(dir), m_user_data(user_data){}
void SetDirWithPoint(const Point& p); // set m_dir, such that this point lies between m_s and m_e
double IncludedAngle()const; // always > 0
bool AlmostALine()const;
Point MidParam(double param)const;
void GetSegments(void(*callbackfunc)(const double *p), double pixels_per_mm)const;
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,128 +1,128 @@
// Area.h
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
// repository now moved to github
#ifndef AREA_HEADER
#define AREA_HEADER
#include "Curve.h"
#include "clipper.hpp"
enum PocketMode
{
SpiralPocketMode,
ZigZagPocketMode,
SingleOffsetPocketMode,
ZigZagThenSingleOffsetPocketMode,
};
struct CAreaPocketParams
{
double tool_radius;
double extra_offset;
double stepover;
bool from_center;
PocketMode mode;
double zig_angle;
bool only_cut_first_offset;
CAreaPocketParams(double Tool_radius, double Extra_offset, double Stepover, bool From_center, PocketMode Mode, double Zig_angle)
{
tool_radius = Tool_radius;
extra_offset = Extra_offset;
stepover = Stepover;
from_center = From_center;
mode = Mode;
zig_angle = Zig_angle;
only_cut_first_offset = false;
}
};
class CArea
{
public:
std::list<CCurve> m_curves;
static double m_accuracy;
static double m_units; // 1.0 for mm, 25.4 for inches. All points are multiplied by this before going to the engine
static bool m_clipper_simple;
static double m_clipper_clean_distance;
static bool m_fit_arcs;
static int m_min_arc_points;
static int m_max_arc_points;
static double m_processing_done; // 0.0 to 100.0, set inside MakeOnePocketCurve
static double m_single_area_processing_length;
static double m_after_MakeOffsets_length;
static double m_MakeOffsets_increment;
static double m_split_processing_length;
static bool m_set_processing_length_in_split;
static bool m_please_abort; // the user sets this from another thread, to tell MakeOnePocketCurve to finish with no result.
static double m_clipper_scale;
void append(const CCurve& curve);
void move(CCurve&& curve);
void Subtract(const CArea& a2);
void Intersect(const CArea& a2);
void Union(const CArea& a2);
static CArea UniteCurves(std::list<CCurve> &curves);
void Xor(const CArea& a2);
void Offset(double inwards_value);
void OffsetWithClipper(double offset,
ClipperLib::JoinType joinType=ClipperLib::jtRound,
ClipperLib::EndType endType=ClipperLib::etOpenRound,
double miterLimit = 5.0,
double roundPrecision = 0.0);
void Thicken(double value);
void FitArcs();
unsigned int num_curves(){return static_cast<int>(m_curves.size());}
Point NearestPoint(const Point& p)const;
void GetBox(CBox2D &box);
void Reorder();
void MakePocketToolpath(std::list<CCurve> &toolpath, const CAreaPocketParams &params)const;
void SplitAndMakePocketToolpath(std::list<CCurve> &toolpath, const CAreaPocketParams &params)const;
void MakeOnePocketCurve(std::list<CCurve> &curve_list, const CAreaPocketParams &params)const;
static bool HolesLinked();
void Split(std::list<CArea> &m_areas)const;
double GetArea(bool always_add = false)const;
void SpanIntersections(const Span& span, std::list<Point> &pts)const;
void CurveIntersections(const CCurve& curve, std::list<Point> &pts)const;
void InsideCurves(const CCurve& curve, std::list<CCurve> &curves_inside)const;
void ChangeStartToNearest(const Point *pstart=NULL, double min_dist=1.0);
//Avoid outside direct accessing static member variable because of Windows DLL issue
#define CAREA_PARAM_DECLARE(_type,_name) \
static _type get_##_name();\
static void set_##_name(_type _name);
CAREA_PARAM_DECLARE(double,tolerance)
CAREA_PARAM_DECLARE(bool,fit_arcs)
CAREA_PARAM_DECLARE(bool,clipper_simple)
CAREA_PARAM_DECLARE(double,clipper_clean_distance)
CAREA_PARAM_DECLARE(double,accuracy)
CAREA_PARAM_DECLARE(double,units)
CAREA_PARAM_DECLARE(short,min_arc_points)
CAREA_PARAM_DECLARE(short,max_arc_points)
CAREA_PARAM_DECLARE(double,clipper_scale)
// Following functions is add to operate on possible open curves
void PopulateClipper(ClipperLib::Clipper &c, ClipperLib::PolyType type) const;
void Clip(ClipperLib::ClipType op,
const CArea *a,
ClipperLib::PolyFillType subjFillType = ClipperLib::pftEvenOdd,
ClipperLib::PolyFillType clipFillType = ClipperLib::pftEvenOdd);
};
enum eOverlapType
{
eOutside,
eInside,
eSiblings,
eCrossing,
};
eOverlapType GetOverlapType(const CCurve& c1, const CCurve& c2);
eOverlapType GetOverlapType(const CArea& a1, const CArea& a2);
bool IsInside(const Point& p, const CCurve& c);
bool IsInside(const Point& p, const CArea& a);
#endif // #define AREA_HEADER
// Area.h
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
// repository now moved to github
#ifndef AREA_HEADER
#define AREA_HEADER
#include "Curve.h"
#include "clipper.hpp"
enum PocketMode
{
SpiralPocketMode,
ZigZagPocketMode,
SingleOffsetPocketMode,
ZigZagThenSingleOffsetPocketMode,
};
struct CAreaPocketParams
{
double tool_radius;
double extra_offset;
double stepover;
bool from_center;
PocketMode mode;
double zig_angle;
bool only_cut_first_offset;
CAreaPocketParams(double Tool_radius, double Extra_offset, double Stepover, bool From_center, PocketMode Mode, double Zig_angle)
{
tool_radius = Tool_radius;
extra_offset = Extra_offset;
stepover = Stepover;
from_center = From_center;
mode = Mode;
zig_angle = Zig_angle;
only_cut_first_offset = false;
}
};
class CArea
{
public:
std::list<CCurve> m_curves;
static double m_accuracy;
static double m_units; // 1.0 for mm, 25.4 for inches. All points are multiplied by this before going to the engine
static bool m_clipper_simple;
static double m_clipper_clean_distance;
static bool m_fit_arcs;
static int m_min_arc_points;
static int m_max_arc_points;
static double m_processing_done; // 0.0 to 100.0, set inside MakeOnePocketCurve
static double m_single_area_processing_length;
static double m_after_MakeOffsets_length;
static double m_MakeOffsets_increment;
static double m_split_processing_length;
static bool m_set_processing_length_in_split;
static bool m_please_abort; // the user sets this from another thread, to tell MakeOnePocketCurve to finish with no result.
static double m_clipper_scale;
void append(const CCurve& curve);
void move(CCurve&& curve);
void Subtract(const CArea& a2);
void Intersect(const CArea& a2);
void Union(const CArea& a2);
static CArea UniteCurves(std::list<CCurve> &curves);
void Xor(const CArea& a2);
void Offset(double inwards_value);
void OffsetWithClipper(double offset,
ClipperLib::JoinType joinType=ClipperLib::jtRound,
ClipperLib::EndType endType=ClipperLib::etOpenRound,
double miterLimit = 5.0,
double roundPrecision = 0.0);
void Thicken(double value);
void FitArcs();
unsigned int num_curves(){return static_cast<int>(m_curves.size());}
Point NearestPoint(const Point& p)const;
void GetBox(CBox2D &box);
void Reorder();
void MakePocketToolpath(std::list<CCurve> &toolpath, const CAreaPocketParams &params)const;
void SplitAndMakePocketToolpath(std::list<CCurve> &toolpath, const CAreaPocketParams &params)const;
void MakeOnePocketCurve(std::list<CCurve> &curve_list, const CAreaPocketParams &params)const;
static bool HolesLinked();
void Split(std::list<CArea> &m_areas)const;
double GetArea(bool always_add = false)const;
void SpanIntersections(const Span& span, std::list<Point> &pts)const;
void CurveIntersections(const CCurve& curve, std::list<Point> &pts)const;
void InsideCurves(const CCurve& curve, std::list<CCurve> &curves_inside)const;
void ChangeStartToNearest(const Point *pstart=NULL, double min_dist=1.0);
//Avoid outside direct accessing static member variable because of Windows DLL issue
#define CAREA_PARAM_DECLARE(_type,_name) \
static _type get_##_name();\
static void set_##_name(_type _name);
CAREA_PARAM_DECLARE(double,tolerance)
CAREA_PARAM_DECLARE(bool,fit_arcs)
CAREA_PARAM_DECLARE(bool,clipper_simple)
CAREA_PARAM_DECLARE(double,clipper_clean_distance)
CAREA_PARAM_DECLARE(double,accuracy)
CAREA_PARAM_DECLARE(double,units)
CAREA_PARAM_DECLARE(short,min_arc_points)
CAREA_PARAM_DECLARE(short,max_arc_points)
CAREA_PARAM_DECLARE(double,clipper_scale)
// Following functions is add to operate on possible open curves
void PopulateClipper(ClipperLib::Clipper &c, ClipperLib::PolyType type) const;
void Clip(ClipperLib::ClipType op,
const CArea *a,
ClipperLib::PolyFillType subjFillType = ClipperLib::pftEvenOdd,
ClipperLib::PolyFillType clipFillType = ClipperLib::pftEvenOdd);
};
enum eOverlapType
{
eOutside,
eInside,
eSiblings,
eCrossing,
};
eOverlapType GetOverlapType(const CCurve& c1, const CCurve& c2);
eOverlapType GetOverlapType(const CArea& a1, const CArea& a2);
bool IsInside(const Point& p, const CCurve& c);
bool IsInside(const Point& p, const CArea& a);
#endif // #define AREA_HEADER

File diff suppressed because it is too large Load Diff

View File

@@ -1,31 +1,31 @@
// AreaDxf.cpp
// Copyright (c) 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "AreaDxf.h"
#include "Area.h"
AreaDxfRead::AreaDxfRead(CArea* area, const char* filepath):CDxfRead(filepath), m_area(area){}
void AreaDxfRead::StartCurveIfNecessary(const double* s)
{
Point ps(s);
if((m_area->m_curves.size() == 0) || (m_area->m_curves.back().m_vertices.size() == 0) || (m_area->m_curves.back().m_vertices.back().m_p != ps))
{
// start a new curve
m_area->m_curves.emplace_back();
m_area->m_curves.back().m_vertices.push_back(ps);
}
}
void AreaDxfRead::OnReadLine(const double* s, const double* e)
{
StartCurveIfNecessary(s);
m_area->m_curves.back().m_vertices.push_back(Point(e));
}
void AreaDxfRead::OnReadArc(const double* s, const double* e, const double* c, bool dir)
{
StartCurveIfNecessary(s);
m_area->m_curves.back().m_vertices.emplace_back(dir?1:0, Point(e), Point(c));
}
// AreaDxf.cpp
// Copyright (c) 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "AreaDxf.h"
#include "Area.h"
AreaDxfRead::AreaDxfRead(CArea* area, const char* filepath):CDxfRead(filepath), m_area(area){}
void AreaDxfRead::StartCurveIfNecessary(const double* s)
{
Point ps(s);
if((m_area->m_curves.size() == 0) || (m_area->m_curves.back().m_vertices.size() == 0) || (m_area->m_curves.back().m_vertices.back().m_p != ps))
{
// start a new curve
m_area->m_curves.emplace_back();
m_area->m_curves.back().m_vertices.push_back(ps);
}
}
void AreaDxfRead::OnReadLine(const double* s, const double* e)
{
StartCurveIfNecessary(s);
m_area->m_curves.back().m_vertices.push_back(Point(e));
}
void AreaDxfRead::OnReadArc(const double* s, const double* e, const double* c, bool dir)
{
StartCurveIfNecessary(s);
m_area->m_curves.back().m_vertices.emplace_back(dir?1:0, Point(e), Point(c));
}

View File

@@ -1,23 +1,23 @@
// AreaDxf.h
// Copyright (c) 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
#include "dxf.h"
class CSketch;
class CArea;
class CCurve;
class AreaDxfRead : public CDxfRead{
void StartCurveIfNecessary(const double* s);
public:
CArea* m_area;
AreaDxfRead(CArea* area, const char* filepath);
// AreaDxfRead's virtual functions
void OnReadLine(const double* s, const double* e);
void OnReadArc(const double* s, const double* e, const double* c, bool dir);
};
// AreaDxf.h
// Copyright (c) 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
#include "dxf.h"
class CSketch;
class CArea;
class CCurve;
class AreaDxfRead : public CDxfRead{
void StartCurveIfNecessary(const double* s);
public:
CArea* m_area;
AreaDxfRead(CArea* area, const char* filepath);
// AreaDxfRead's virtual functions
void OnReadLine(const double* s, const double* e);
void OnReadArc(const double* s, const double* e, const double* c, bool dir);
};

View File

@@ -1,167 +1,167 @@
// AreaOrderer.cpp
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#include "AreaOrderer.h"
#include <memory>
#include "Area.h"
using namespace std;
CAreaOrderer* CInnerCurves::area_orderer = NULL;
CInnerCurves::CInnerCurves(shared_ptr<CInnerCurves> pOuter, shared_ptr<CCurve> curve)
:m_pOuter(pOuter)
,m_curve(curve)
{
}
CInnerCurves::~CInnerCurves()
{
}
void CInnerCurves::Insert(shared_ptr<CCurve> pcurve)
{
std::list<shared_ptr<CInnerCurves> > outside_of_these;
std::list<shared_ptr<CInnerCurves> > crossing_these;
// check all inner curves
for(shared_ptr<CInnerCurves> c : m_inner_curves) {
switch(GetOverlapType(*pcurve, *(c->m_curve)))
{
case eOutside:
outside_of_these.push_back(c);
break;
case eInside:
// insert in this inner curve
c->Insert(pcurve);
return;
case eSiblings:
break;
case eCrossing:
crossing_these.push_back(c);
break;
}
}
// add as a new inner
shared_ptr<CInnerCurves> new_item(new CInnerCurves(shared_from_this(), pcurve));
this->m_inner_curves.insert(new_item);
for(shared_ptr<CInnerCurves> c : outside_of_these) {
// move items
c->m_pOuter = new_item;
new_item->m_inner_curves.insert(c);
this->m_inner_curves.erase(c);
}
for(shared_ptr<CInnerCurves> c : crossing_these) {
// unite these
new_item->Unite(c);
this->m_inner_curves.erase(c);
}
}
void CInnerCurves::GetArea(CArea &area, bool outside, bool use_curve)
{
if(use_curve && m_curve)
{
area.m_curves.push_back(*m_curve);
outside = !outside;
}
std::list<shared_ptr<CInnerCurves> > do_after;
for(shared_ptr<CInnerCurves> c: m_inner_curves) {
area.m_curves.push_back(*c->m_curve);
if(!outside)area.m_curves.back().Reverse();
if(outside)c->GetArea(area, !outside, false);
else do_after.push_back(c);
}
for(shared_ptr<CInnerCurves> c : do_after)
c->GetArea(area, !outside, false);
}
void CInnerCurves::Unite(shared_ptr<CInnerCurves> c)
{
// unite all the curves in c, with this one
shared_ptr<CArea> new_area(new CArea());
new_area->m_curves.push_back(*m_curve);
m_unite_area = new_area;
CArea a2;
c->GetArea(a2);
m_unite_area->Union(a2);
m_unite_area->Reorder();
for(std::list<CCurve>::iterator It = m_unite_area->m_curves.begin(); It != m_unite_area->m_curves.end(); It++)
{
CCurve &curve = *It;
if(It == m_unite_area->m_curves.begin())
m_curve = make_shared<CCurve>(curve);
else
{
if(curve.IsClockwise())curve.Reverse();
Insert(std::make_shared<CCurve>(curve));
}
}
}
CAreaOrderer::CAreaOrderer()
:m_top_level(make_shared<CInnerCurves>())
{
}
void CAreaOrderer::Insert(shared_ptr<CCurve> pcurve)
{
CInnerCurves::area_orderer = this;
// make them all anti-clockwise as they come in
if(pcurve->IsClockwise())pcurve->Reverse();
m_top_level->Insert(pcurve);
}
CArea CAreaOrderer::ResultArea()const
{
CArea a;
if(m_top_level)
{
m_top_level->GetArea(a);
}
return a;
}
// AreaOrderer.cpp
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#include "AreaOrderer.h"
#include <memory>
#include "Area.h"
using namespace std;
CAreaOrderer* CInnerCurves::area_orderer = NULL;
CInnerCurves::CInnerCurves(shared_ptr<CInnerCurves> pOuter, shared_ptr<CCurve> curve)
:m_pOuter(pOuter)
,m_curve(curve)
{
}
CInnerCurves::~CInnerCurves()
{
}
void CInnerCurves::Insert(shared_ptr<CCurve> pcurve)
{
std::list<shared_ptr<CInnerCurves> > outside_of_these;
std::list<shared_ptr<CInnerCurves> > crossing_these;
// check all inner curves
for(shared_ptr<CInnerCurves> c : m_inner_curves) {
switch(GetOverlapType(*pcurve, *(c->m_curve)))
{
case eOutside:
outside_of_these.push_back(c);
break;
case eInside:
// insert in this inner curve
c->Insert(pcurve);
return;
case eSiblings:
break;
case eCrossing:
crossing_these.push_back(c);
break;
}
}
// add as a new inner
shared_ptr<CInnerCurves> new_item(new CInnerCurves(shared_from_this(), pcurve));
this->m_inner_curves.insert(new_item);
for(shared_ptr<CInnerCurves> c : outside_of_these) {
// move items
c->m_pOuter = new_item;
new_item->m_inner_curves.insert(c);
this->m_inner_curves.erase(c);
}
for(shared_ptr<CInnerCurves> c : crossing_these) {
// unite these
new_item->Unite(c);
this->m_inner_curves.erase(c);
}
}
void CInnerCurves::GetArea(CArea &area, bool outside, bool use_curve)
{
if(use_curve && m_curve)
{
area.m_curves.push_back(*m_curve);
outside = !outside;
}
std::list<shared_ptr<CInnerCurves> > do_after;
for(shared_ptr<CInnerCurves> c: m_inner_curves) {
area.m_curves.push_back(*c->m_curve);
if(!outside)area.m_curves.back().Reverse();
if(outside)c->GetArea(area, !outside, false);
else do_after.push_back(c);
}
for(shared_ptr<CInnerCurves> c : do_after)
c->GetArea(area, !outside, false);
}
void CInnerCurves::Unite(shared_ptr<CInnerCurves> c)
{
// unite all the curves in c, with this one
shared_ptr<CArea> new_area(new CArea());
new_area->m_curves.push_back(*m_curve);
m_unite_area = new_area;
CArea a2;
c->GetArea(a2);
m_unite_area->Union(a2);
m_unite_area->Reorder();
for(std::list<CCurve>::iterator It = m_unite_area->m_curves.begin(); It != m_unite_area->m_curves.end(); It++)
{
CCurve &curve = *It;
if(It == m_unite_area->m_curves.begin())
m_curve = make_shared<CCurve>(curve);
else
{
if(curve.IsClockwise())curve.Reverse();
Insert(std::make_shared<CCurve>(curve));
}
}
}
CAreaOrderer::CAreaOrderer()
:m_top_level(make_shared<CInnerCurves>())
{
}
void CAreaOrderer::Insert(shared_ptr<CCurve> pcurve)
{
CInnerCurves::area_orderer = this;
// make them all anti-clockwise as they come in
if(pcurve->IsClockwise())pcurve->Reverse();
m_top_level->Insert(pcurve);
}
CArea CAreaOrderer::ResultArea()const
{
CArea a;
if(m_top_level)
{
m_top_level->GetArea(a);
}
return a;
}

View File

@@ -1,67 +1,67 @@
// AreaOrderer.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include <memory>
#include <list>
#include <set>
class CArea;
class CCurve;
class CAreaOrderer;
class CInnerCurves: public std::enable_shared_from_this<CInnerCurves>
{
std::shared_ptr<CInnerCurves> m_pOuter;
std::shared_ptr<CCurve> m_curve; // always empty if top level
std::set<std::shared_ptr<CInnerCurves> > m_inner_curves;
std::shared_ptr<CArea> m_unite_area; // new curves made by uniting are stored here
public:
static CAreaOrderer* area_orderer;
CInnerCurves(std::shared_ptr<CInnerCurves> pOuter, std::shared_ptr<CCurve> curve);
CInnerCurves(){}
~CInnerCurves();
void Insert(std::shared_ptr<CCurve> pcurve);
void GetArea(CArea &area, bool outside = true, bool use_curve = true);
void Unite(std::shared_ptr<CInnerCurves> c);
};
class CAreaOrderer
{
public:
std::shared_ptr<CInnerCurves> m_top_level;
CAreaOrderer();
void Insert(std::shared_ptr<CCurve> pcurve);
CArea ResultArea()const;
};
// AreaOrderer.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include <memory>
#include <list>
#include <set>
class CArea;
class CCurve;
class CAreaOrderer;
class CInnerCurves: public std::enable_shared_from_this<CInnerCurves>
{
std::shared_ptr<CInnerCurves> m_pOuter;
std::shared_ptr<CCurve> m_curve; // always empty if top level
std::set<std::shared_ptr<CInnerCurves> > m_inner_curves;
std::shared_ptr<CArea> m_unite_area; // new curves made by uniting are stored here
public:
static CAreaOrderer* area_orderer;
CInnerCurves(std::shared_ptr<CInnerCurves> pOuter, std::shared_ptr<CCurve> curve);
CInnerCurves(){}
~CInnerCurves();
void Insert(std::shared_ptr<CCurve> pcurve);
void GetArea(CArea &area, bool outside = true, bool use_curve = true);
void Unite(std::shared_ptr<CInnerCurves> c);
};
class CAreaOrderer
{
public:
std::shared_ptr<CInnerCurves> m_top_level;
CAreaOrderer();
void Insert(std::shared_ptr<CCurve> pcurve);
CArea ResultArea()const;
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,94 +1,94 @@
// Box2D.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include <string.h> // for memcpy() prototype
#include <math.h> // for sqrt() prototype
class CBox2D{
public:
Point m_minxy;
Point m_maxxy;
bool m_valid;
CBox2D():m_valid(false){}
CBox2D(const Point& minxy, const Point& maxxy):m_minxy(minxy), m_maxxy(maxxy), m_valid(true){}
bool operator==( const CBox2D & rhs ) const
{
if(m_minxy != rhs.m_minxy)return false;
if(m_maxxy != rhs.m_maxxy)return false;
if (m_valid != rhs.m_valid) return(false);
return(true);
}
bool operator!=( const CBox2D & rhs ) const { return(! (*this == rhs)); }
void Insert(const Point &p){ // insert a point
if(m_valid){
if(p.x < m_minxy.x)m_minxy.x = p.x;
if(p.y < m_minxy.y)m_minxy.y = p.y;
if(p.x > m_maxxy.x)m_maxxy.x = p.x;
if(p.y > m_maxxy.y)m_maxxy.y = p.y;
}
else
{
m_valid = true;
m_minxy = p;
m_maxxy = p;
}
}
void Insert(const CBox2D& b){
if(b.m_valid){
if(m_valid){
if(b.m_minxy.x < m_minxy.x)m_minxy.x = b.m_minxy.x;
if(b.m_minxy.y < m_minxy.y)m_minxy.y = b.m_minxy.y;
if(b.m_maxxy.x > m_maxxy.x)m_maxxy.x = b.m_maxxy.x;
if(b.m_maxxy.y > m_maxxy.y)m_maxxy.y = b.m_maxxy.y;
}
else{
m_valid = b.m_valid;
m_minxy = b.m_minxy;
m_maxxy = b.m_maxxy;
}
}
}
Point Centre() const {return (m_minxy + m_maxxy) * 0.5;}
double Width() const {if(m_valid)return m_maxxy.x - m_minxy.x; else return 0.0;}
double Height() const {if(m_valid)return m_maxxy.y - m_minxy.y; else return 0.0;}
double Radius() const {return sqrt(Width() * Width() + Height() * Height()) /2;}
double MinX() const { return(m_minxy.x); }
double MaxX() const { return(m_maxxy.x); }
double MinY() const { return(m_minxy.y); }
double MaxY() const { return(m_maxxy.y); }
};
// Box2D.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include <string.h> // for memcpy() prototype
#include <math.h> // for sqrt() prototype
class CBox2D{
public:
Point m_minxy;
Point m_maxxy;
bool m_valid;
CBox2D():m_valid(false){}
CBox2D(const Point& minxy, const Point& maxxy):m_minxy(minxy), m_maxxy(maxxy), m_valid(true){}
bool operator==( const CBox2D & rhs ) const
{
if(m_minxy != rhs.m_minxy)return false;
if(m_maxxy != rhs.m_maxxy)return false;
if (m_valid != rhs.m_valid) return(false);
return(true);
}
bool operator!=( const CBox2D & rhs ) const { return(! (*this == rhs)); }
void Insert(const Point &p){ // insert a point
if(m_valid){
if(p.x < m_minxy.x)m_minxy.x = p.x;
if(p.y < m_minxy.y)m_minxy.y = p.y;
if(p.x > m_maxxy.x)m_maxxy.x = p.x;
if(p.y > m_maxxy.y)m_maxxy.y = p.y;
}
else
{
m_valid = true;
m_minxy = p;
m_maxxy = p;
}
}
void Insert(const CBox2D& b){
if(b.m_valid){
if(m_valid){
if(b.m_minxy.x < m_minxy.x)m_minxy.x = b.m_minxy.x;
if(b.m_minxy.y < m_minxy.y)m_minxy.y = b.m_minxy.y;
if(b.m_maxxy.x > m_maxxy.x)m_maxxy.x = b.m_maxxy.x;
if(b.m_maxxy.y > m_maxxy.y)m_maxxy.y = b.m_maxxy.y;
}
else{
m_valid = b.m_valid;
m_minxy = b.m_minxy;
m_maxxy = b.m_maxxy;
}
}
}
Point Centre() const {return (m_minxy + m_maxxy) * 0.5;}
double Width() const {if(m_valid)return m_maxxy.x - m_minxy.x; else return 0.0;}
double Height() const {if(m_valid)return m_maxxy.y - m_minxy.y; else return 0.0;}
double Radius() const {return sqrt(Width() * Width() + Height() * Height()) /2;}
double MinX() const { return(m_minxy.x); }
double MaxX() const { return(m_maxxy.x); }
double MinY() const { return(m_minxy.y); }
double MaxY() const { return(m_maxxy.y); }
};

View File

@@ -1,103 +1,103 @@
// Circle.cpp
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#include "Circle.h"
Circle::Circle(const Point& p0, const Point& p1, const Point& p2)
{
// from TangentCircles in http://code.google.com/p/heekscad/source/browse/trunk/src/Geom.cpp
// set default values, in case this fails
m_radius = 0.0;
m_c = Point(0, 0);
double x1 = p0.x;
double y1 = p0.y;
double x2 = p1.x;
double y2 = p1.y;
double x3 = p2.x;
double y3 = p2.y;
double a = 2 * (x1 - x2);
double b = 2 * (y1 - y2);
double d = (x1 * x1 + y1 * y1) - (x2 * x2 + y2 * y2);
double A = 2 * (x1 - x3);
double B = 2 * (y1 - y3);
double D = (x1 * x1 + y1 * y1) - (x3 * x3 + y3 * y3);
double aBmbA = (a*B - b*A); // aB - bA
// x = k + Kr where
double k = (B*d - b*D) / aBmbA;
// y = l + Lr where
double l = (-A*d + a*D)/ aBmbA;
double qa = -1;
double qb = 0.0;
double qc = k*k + x1*x1 -2*k*x1 + l*l + y1*y1 - 2*l*y1;
// solve the quadratic equation, r = (-b +- sqrt(b*b - 4*a*c))/(2 * a)
for(int qs = 0; qs<2; qs++){
double bb = qb*qb;
double ac4 = 4*qa*qc;
if(ac4 <= bb){
double r = (-qb + ((qs == 0) ? 1 : -1) * sqrt(bb - ac4))/(2 * qa);
double x = k;
double y = l;
// set the circle
if(r >= 0.0){
m_c = Point(x, y);
m_radius = r;
}
}
}
}
bool Circle::PointIsOn(const Point& p, double accuracy)
{
double rp = p.dist(m_c);
bool on = fabs(m_radius - rp) < accuracy;
return on;
}
bool Circle::LineIsOn(const Point& p0, const Point& p1, double accuracy)
{
// checks the points are on the arc, to the given accuracy, and the mid point of the line.
if(!PointIsOn(p0, accuracy))return false;
if(!PointIsOn(p1, accuracy))return false;
Point mid = Point((p0 + p1)/2);
if(!PointIsOn(mid, accuracy))return false;
return true;
// Circle.cpp
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#include "Circle.h"
Circle::Circle(const Point& p0, const Point& p1, const Point& p2)
{
// from TangentCircles in http://code.google.com/p/heekscad/source/browse/trunk/src/Geom.cpp
// set default values, in case this fails
m_radius = 0.0;
m_c = Point(0, 0);
double x1 = p0.x;
double y1 = p0.y;
double x2 = p1.x;
double y2 = p1.y;
double x3 = p2.x;
double y3 = p2.y;
double a = 2 * (x1 - x2);
double b = 2 * (y1 - y2);
double d = (x1 * x1 + y1 * y1) - (x2 * x2 + y2 * y2);
double A = 2 * (x1 - x3);
double B = 2 * (y1 - y3);
double D = (x1 * x1 + y1 * y1) - (x3 * x3 + y3 * y3);
double aBmbA = (a*B - b*A); // aB - bA
// x = k + Kr where
double k = (B*d - b*D) / aBmbA;
// y = l + Lr where
double l = (-A*d + a*D)/ aBmbA;
double qa = -1;
double qb = 0.0;
double qc = k*k + x1*x1 -2*k*x1 + l*l + y1*y1 - 2*l*y1;
// solve the quadratic equation, r = (-b +- sqrt(b*b - 4*a*c))/(2 * a)
for(int qs = 0; qs<2; qs++){
double bb = qb*qb;
double ac4 = 4*qa*qc;
if(ac4 <= bb){
double r = (-qb + ((qs == 0) ? 1 : -1) * sqrt(bb - ac4))/(2 * qa);
double x = k;
double y = l;
// set the circle
if(r >= 0.0){
m_c = Point(x, y);
m_radius = r;
}
}
}
}
bool Circle::PointIsOn(const Point& p, double accuracy)
{
double rp = p.dist(m_c);
bool on = fabs(m_radius - rp) < accuracy;
return on;
}
bool Circle::LineIsOn(const Point& p0, const Point& p1, double accuracy)
{
// checks the points are on the arc, to the given accuracy, and the mid point of the line.
if(!PointIsOn(p0, accuracy))return false;
if(!PointIsOn(p1, accuracy))return false;
Point mid = Point((p0 + p1)/2);
if(!PointIsOn(mid, accuracy))return false;
return true;
}

View File

@@ -1,44 +1,44 @@
// Circle.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include "Point.h"
class Circle{
public:
Point m_c;
double m_radius;
Circle(const Point& c, double radius):m_c(c), m_radius(radius){}
Circle(const Point& p0, const Point& p1, const Point& p2); // circle through three points
bool PointIsOn(const Point& p, double accuracy);
bool LineIsOn(const Point& p0, const Point& p1, double accuracy);
// Circle.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include "Point.h"
class Circle{
public:
Point m_c;
double m_radius;
Circle(const Point& c, double radius):m_c(c), m_radius(radius){}
Circle(const Point& p0, const Point& p1, const Point& p2); // circle through three points
bool PointIsOn(const Point& p, double accuracy);
bool LineIsOn(const Point& p0, const Point& p1, double accuracy);
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,130 +1,130 @@
// Curve.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include <vector>
#include <list>
#include <math.h>
#include "Point.h"
#include "Box2D.h"
class Line{
public:
Point p0;
Point v;
// constructors
Line(const Point& P0, const Point& V);
double Dist(const Point& p)const;
};
class CArc;
class CVertex
{
public:
int m_type; // 0 - line ( or start point ), 1 - anti-clockwise arc, -1 - clockwise arc
Point m_p; // end point
Point m_c; // centre point in absolute coordinates
int m_user_data;
CVertex():m_type(0), m_p(Point(0, 0)), m_c(Point(0,0)), m_user_data(0){}
CVertex(int type, const Point& p, const Point& c, int user_data = 0);
CVertex(const Point& p, int user_data = 0);
};
class Span
{
Point NearestPointNotOnSpan(const Point& p)const;
double Parameter(const Point& p)const;
Point NearestPointToSpan(const Span& p, double &d)const;
static const Point null_point;
static const CVertex null_vertex;
public:
bool m_start_span;
Point m_p;
CVertex m_v;
Span();
Span(const Point& p, const CVertex& v, bool start_span = false):m_start_span(start_span), m_p(p), m_v(v){}
Point NearestPoint(const Point& p)const;
Point NearestPoint(const Span& p, double *d = NULL)const;
void GetBox(CBox2D &box);
double IncludedAngle()const;
double GetArea()const;
bool On(const Point& p, double* t = NULL)const;
Point MidPerim(double d)const;
Point MidParam(double param)const;
double Length()const;
Point GetVector(double fraction)const;
void Intersect(const Span& s, std::list<Point> &pts)const; // finds all the intersection points between two spans
};
class CCurve
{
// a closed curve, please make sure you add an end point, the same as the start point
protected:
void AddArcOrLines(bool check_for_arc, std::list<CVertex> &new_vertices, std::list<const CVertex*>& might_be_an_arc, CArc &arc, bool &arc_found, bool &arc_added);
static bool CheckForArc(const CVertex& prev_vt, std::list<const CVertex*>& might_be_an_arc, CArc &arc);
public:
std::list<CVertex> m_vertices;
void append(const CVertex& vertex);
void FitArcs(bool retry=false);
void UnFitArcs();
Point NearestPoint(const Point& p)const;
Point NearestPoint(const CCurve& p, double *d = NULL)const;
Point NearestPoint(const Span& p, double *d = NULL)const;
void GetBox(CBox2D &box);
void Reverse();
double GetArea()const;
bool IsClockwise()const{return GetArea()>0;}
bool IsClosed()const;
void ChangeStart(const Point &p);
void ChangeEnd(const Point &p);
bool Offset(double leftwards_value);
void OffsetForward(double forwards_value, bool refit_arcs = true); // for drag-knife compensation
void Break(const Point &p);
void ExtractSeparateCurves(const std::list<Point> &ordered_points, std::list<CCurve> &separate_curves)const;
double Perim()const;
Point PerimToPoint(double perim)const;
double PointToPerim(const Point& p)const;
void GetSpans(std::list<Span> &spans)const;
void RemoveTinySpans();
void operator+=(const CCurve& p);
void SpanIntersections(const Span& s, std::list<Point> &pts)const;
void CurveIntersections(const CCurve& c, std::list<Point> &pts)const;
};
void tangential_arc(const Point &p0, const Point &p1, const Point &v0, Point &c, int &dir);
// Curve.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include <vector>
#include <list>
#include <math.h>
#include "Point.h"
#include "Box2D.h"
class Line{
public:
Point p0;
Point v;
// constructors
Line(const Point& P0, const Point& V);
double Dist(const Point& p)const;
};
class CArc;
class CVertex
{
public:
int m_type; // 0 - line ( or start point ), 1 - anti-clockwise arc, -1 - clockwise arc
Point m_p; // end point
Point m_c; // centre point in absolute coordinates
int m_user_data;
CVertex():m_type(0), m_p(Point(0, 0)), m_c(Point(0,0)), m_user_data(0){}
CVertex(int type, const Point& p, const Point& c, int user_data = 0);
CVertex(const Point& p, int user_data = 0);
};
class Span
{
Point NearestPointNotOnSpan(const Point& p)const;
double Parameter(const Point& p)const;
Point NearestPointToSpan(const Span& p, double &d)const;
static const Point null_point;
static const CVertex null_vertex;
public:
bool m_start_span;
Point m_p;
CVertex m_v;
Span();
Span(const Point& p, const CVertex& v, bool start_span = false):m_start_span(start_span), m_p(p), m_v(v){}
Point NearestPoint(const Point& p)const;
Point NearestPoint(const Span& p, double *d = NULL)const;
void GetBox(CBox2D &box);
double IncludedAngle()const;
double GetArea()const;
bool On(const Point& p, double* t = NULL)const;
Point MidPerim(double d)const;
Point MidParam(double param)const;
double Length()const;
Point GetVector(double fraction)const;
void Intersect(const Span& s, std::list<Point> &pts)const; // finds all the intersection points between two spans
};
class CCurve
{
// a closed curve, please make sure you add an end point, the same as the start point
protected:
void AddArcOrLines(bool check_for_arc, std::list<CVertex> &new_vertices, std::list<const CVertex*>& might_be_an_arc, CArc &arc, bool &arc_found, bool &arc_added);
static bool CheckForArc(const CVertex& prev_vt, std::list<const CVertex*>& might_be_an_arc, CArc &arc);
public:
std::list<CVertex> m_vertices;
void append(const CVertex& vertex);
void FitArcs(bool retry=false);
void UnFitArcs();
Point NearestPoint(const Point& p)const;
Point NearestPoint(const CCurve& p, double *d = NULL)const;
Point NearestPoint(const Span& p, double *d = NULL)const;
void GetBox(CBox2D &box);
void Reverse();
double GetArea()const;
bool IsClockwise()const{return GetArea()>0;}
bool IsClosed()const;
void ChangeStart(const Point &p);
void ChangeEnd(const Point &p);
bool Offset(double leftwards_value);
void OffsetForward(double forwards_value, bool refit_arcs = true); // for drag-knife compensation
void Break(const Point &p);
void ExtractSeparateCurves(const std::list<Point> &ordered_points, std::list<CCurve> &separate_curves)const;
double Perim()const;
Point PerimToPoint(double perim)const;
double PointToPerim(const Point& p)const;
void GetSpans(std::list<Span> &spans)const;
void RemoveTinySpans();
void operator+=(const CCurve& p);
void SpanIntersections(const Span& s, std::list<Point> &pts)const;
void CurveIntersections(const CCurve& c, std::list<Point> &pts)const;
};
void tangential_arc(const Point &p0, const Point &p1, const Point &v0, Point &c, int &dir);

View File

@@ -1,75 +1,75 @@
// Point.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include <cmath>
#include "kurve/geometry.h"
class Point{
public:
// can be a position, or a vector
double x, y;
Point():x(0.0), y(0.0){}
Point(double X, double Y):x(X), y(Y){}
Point(const double* p):x(p[0]), y(p[1]){}
Point(const Point& p0, const Point& p1):x(p1.x - p0.x), y(p1.y - p0.y){} // vector from p0 to p1
static double tolerance;
const Point operator+(const Point& p)const{return Point(x + p.x, y + p.y);}
const Point operator-(const Point& p)const{return Point(x - p.x, y - p.y);}
const Point operator*(double d)const{return Point(x * d, y * d);}
const Point operator/(double d)const{return Point(x / d, y / d);}
bool operator==(const Point& p)const;
bool operator!=(const Point &p)const{ return !(*this == p);}
double dist(const Point &p)const{double dx = p.x - x; double dy = p.y - y; return sqrt(dx*dx + dy*dy);}
double length()const;
double normalize();
double operator*(const Point &p)const{return (x * p.x + y * p.y);}// dot product
double operator^(const Point &p)const{return (x * p.y - y * p.x);}// cross product m0.m1.sin a = v0 ^ v1
Point operator~(void)const{return Point(-y, x);}// perp to left
Point operator-(void)const{return Point(-x, -y);}// v1 = -v0; (unary minus)
void Rotate(double cosa, double sina){// rotate vector by angle
double temp = -y * sina + x * cosa;
y = x * sina + cosa * y;
x = temp;
}
void Rotate(double angle){if(fabs(angle) < 1.0e-09)return; Rotate(cos(angle), sin(angle));}
void Transform(const geoff_geometry::Matrix &m)
{
geoff_geometry::Point p(x,y);
p = p.Transform(m);
x = p.x;
y = p.y;
}
};
const Point operator*(const double &d, const Point &p);
// Point.h
/*==============================
Copyright (c) 2011-2015 Dan Heeks
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================*/
#pragma once
#include <cmath>
#include "kurve/geometry.h"
class Point{
public:
// can be a position, or a vector
double x, y;
Point():x(0.0), y(0.0){}
Point(double X, double Y):x(X), y(Y){}
Point(const double* p):x(p[0]), y(p[1]){}
Point(const Point& p0, const Point& p1):x(p1.x - p0.x), y(p1.y - p0.y){} // vector from p0 to p1
static double tolerance;
const Point operator+(const Point& p)const{return Point(x + p.x, y + p.y);}
const Point operator-(const Point& p)const{return Point(x - p.x, y - p.y);}
const Point operator*(double d)const{return Point(x * d, y * d);}
const Point operator/(double d)const{return Point(x / d, y / d);}
bool operator==(const Point& p)const;
bool operator!=(const Point &p)const{ return !(*this == p);}
double dist(const Point &p)const{double dx = p.x - x; double dy = p.y - y; return sqrt(dx*dx + dy*dy);}
double length()const;
double normalize();
double operator*(const Point &p)const{return (x * p.x + y * p.y);}// dot product
double operator^(const Point &p)const{return (x * p.y - y * p.x);}// cross product m0.m1.sin a = v0 ^ v1
Point operator~(void)const{return Point(-y, x);}// perp to left
Point operator-(void)const{return Point(-x, -y);}// v1 = -v0; (unary minus)
void Rotate(double cosa, double sina){// rotate vector by angle
double temp = -y * sina + x * cosa;
y = x * sina + cosa * y;
x = temp;
}
void Rotate(double angle){if(fabs(angle) < 1.0e-09)return; Rotate(cos(angle), sin(angle));}
void Transform(const geoff_geometry::Matrix &m)
{
geoff_geometry::Point p(x,y);
p = p.Transform(m);
x = p.x;
y = p.y;
}
};
const Point operator*(const double &d, const Point &p);

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,10 @@
// PythonStuff.h
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
extern void Message(const char*);
void PythonInit();
void PythonFinish();
// PythonStuff.h
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
extern void Message(const char*);
void PythonInit();
void PythonFinish();

File diff suppressed because it is too large Load Diff

View File

@@ -1,395 +1,395 @@
/*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 6.2.0 *
* Date : 2 October 2014 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2014 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Attributions: *
* The code in this library is an extension of Bala Vatti's clipping algorithm: *
* "A generic solution to polygon clipping" *
* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
* http://portal.acm.org/citation.cfm?id=129906 *
* *
* Computer graphics and geometric modeling: implementation and algorithms *
* By Max K. Agoston *
* Springer; 1 edition (January 4, 2005) *
* http://books.google.com/books?q=vatti+clipping+agoston *
* *
* See also: *
* "Polygon Offsetting by Computing Winding Numbers" *
* Paper no. DETC2005-85513 pp. 565-575 *
* ASME 2005 International Design Engineering Technical Conferences *
* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
* September 24-28, 2005 , Long Beach, California, USA *
* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
* *
*******************************************************************************/
#ifndef clipper_hpp
#define clipper_hpp
#define CLIPPER_VERSION "6.2.0"
//use_int32: When enabled 32bit ints are used instead of 64bit ints. This
//improve performance but coordinate values are limited to the range +/- 46340
//#define use_int32
//use_xyz: adds a Z member to IntPoint. Adds a minor cost to performance.
//#define use_xyz
//use_lines: Enables line clipping. Adds a very minor cost to performance.
#define use_lines
//use_deprecated: Enables temporary support for the obsolete functions
//#define use_deprecated
#include <vector>
#include <set>
#include <stdexcept>
#include <cstring>
#include <cstdlib>
#include <ostream>
#include <functional>
#include <queue>
namespace ClipperLib {
enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
enum PolyType { ptSubject, ptClip };
//By far the most widely used winding rules for polygon filling are
//EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
//Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
//see http://glprogramming.com/red/chapter11.html
enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
#ifdef use_int32
typedef int cInt;
static cInt const loRange = 0x7FFF;
static cInt const hiRange = 0x7FFF;
#else
typedef signed long long cInt;
static cInt const loRange = 0x3FFFFFFF;
static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
typedef signed long long long64; //used by Int128 class
typedef unsigned long long ulong64;
#endif
struct IntPoint {
cInt X;
cInt Y;
#ifdef use_xyz
cInt Z;
IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {};
#else
IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {};
#endif
friend inline bool operator== (const IntPoint& a, const IntPoint& b)
{
return a.X == b.X && a.Y == b.Y;
}
friend inline bool operator!= (const IntPoint& a, const IntPoint& b)
{
return a.X != b.X || a.Y != b.Y;
}
};
//------------------------------------------------------------------------------
typedef std::vector< IntPoint > Path;
typedef std::vector< Path > Paths;
inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;}
inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;}
std::ostream& operator <<(std::ostream &s, const IntPoint &p);
std::ostream& operator <<(std::ostream &s, const Path &p);
std::ostream& operator <<(std::ostream &s, const Paths &p);
struct DoublePoint
{
double X;
double Y;
DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
};
//------------------------------------------------------------------------------
#ifdef use_xyz
typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt);
#endif
enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4};
enum JoinType {jtSquare, jtRound, jtMiter};
enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};
class PolyNode;
typedef std::vector< PolyNode* > PolyNodes;
class PolyNode
{
public:
PolyNode();
virtual ~PolyNode(){};
Path Contour;
PolyNodes Childs;
PolyNode* Parent;
PolyNode* GetNext() const;
bool IsHole() const;
bool IsOpen() const;
int ChildCount() const;
private:
unsigned Index; //node index in Parent.Childs
bool m_IsOpen;
JoinType m_jointype;
EndType m_endtype;
PolyNode* GetNextSiblingUp() const;
void AddChild(PolyNode& child);
friend class Clipper; //to access Index
friend class ClipperOffset;
};
class PolyTree: public PolyNode
{
public:
~PolyTree(){Clear();};
PolyNode* GetFirst() const;
void Clear();
int Total() const;
private:
PolyNodes AllNodes;
friend class Clipper; //to access AllNodes
};
bool Orientation(const Path &poly);
double Area(const Path &poly);
int PointInPolygon(const IntPoint &pt, const Path &path);
void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415);
void CleanPolygon(Path& poly, double distance = 1.415);
void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance = 1.415);
void CleanPolygons(Paths& polys, double distance = 1.415);
void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed);
void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed);
void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution);
void PolyTreeToPaths(const PolyTree& polytree, Paths& paths);
void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths);
void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths);
void ReversePath(Path& p);
void ReversePaths(Paths& p);
struct IntRect { cInt left; cInt top; cInt right; cInt bottom; };
//enums that are used internally ...
enum EdgeSide { esLeft = 1, esRight = 2};
//forward declarations (for stuff used internally) ...
struct TEdge;
struct IntersectNode;
struct LocalMinimum;
struct Scanbeam;
struct OutPt;
struct OutRec;
struct Join;
typedef std::vector < OutRec* > PolyOutList;
typedef std::vector < TEdge* > EdgeList;
typedef std::vector < Join* > JoinList;
typedef std::vector < IntersectNode* > IntersectList;
//------------------------------------------------------------------------------
//ClipperBase is the ancestor to the Clipper class. It should not be
//instantiated directly. This class simply abstracts the conversion of sets of
//polygon coordinates into edge objects that are stored in a LocalMinima list.
class ClipperBase
{
public:
ClipperBase();
virtual ~ClipperBase();
bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
virtual void Clear();
IntRect GetBounds();
bool PreserveCollinear() {return m_PreserveCollinear;};
void PreserveCollinear(bool value) {m_PreserveCollinear = value;};
protected:
void DisposeLocalMinimaList();
TEdge* AddBoundsToLML(TEdge *e, bool IsClosed);
void PopLocalMinima();
virtual void Reset();
TEdge* ProcessBound(TEdge* E, bool IsClockwise);
void DoMinimaLML(TEdge* E1, TEdge* E2, bool IsClosed);
TEdge* DescendToMin(TEdge *&E);
void AscendToMax(TEdge *&E, bool Appending, bool IsClosed);
typedef std::vector<LocalMinimum> MinimaList;
MinimaList::iterator m_CurrentLM;
MinimaList m_MinimaList;
bool m_UseFullRange;
EdgeList m_edges;
bool m_PreserveCollinear;
bool m_HasOpenPaths;
};
//------------------------------------------------------------------------------
class Clipper : public virtual ClipperBase
{
public:
Clipper(int initOptions = 0);
~Clipper();
bool Execute(ClipType clipType,
Paths &solution,
PolyFillType subjFillType = pftEvenOdd,
PolyFillType clipFillType = pftEvenOdd);
bool Execute(ClipType clipType,
PolyTree &polytree,
PolyFillType subjFillType = pftEvenOdd,
PolyFillType clipFillType = pftEvenOdd);
bool ReverseSolution() {return m_ReverseOutput;};
void ReverseSolution(bool value) {m_ReverseOutput = value;};
bool StrictlySimple() {return m_StrictSimple;};
void StrictlySimple(bool value) {m_StrictSimple = value;};
//set the callback function for z value filling on intersections (otherwise Z is 0)
#ifdef use_xyz
void ZFillFunction(ZFillCallback zFillFunc);
#endif
protected:
void Reset();
virtual bool ExecuteInternal();
private:
PolyOutList m_PolyOuts;
JoinList m_Joins;
JoinList m_GhostJoins;
IntersectList m_IntersectList;
ClipType m_ClipType;
typedef std::priority_queue<cInt> ScanbeamList;
ScanbeamList m_Scanbeam;
TEdge *m_ActiveEdges;
TEdge *m_SortedEdges;
bool m_ExecuteLocked;
PolyFillType m_ClipFillType;
PolyFillType m_SubjFillType;
bool m_ReverseOutput;
bool m_UsingPolyTree;
bool m_StrictSimple;
#ifdef use_xyz
ZFillCallback m_ZFill; //custom callback
#endif
void SetWindingCount(TEdge& edge);
bool IsEvenOddFillType(const TEdge& edge) const;
bool IsEvenOddAltFillType(const TEdge& edge) const;
void InsertScanbeam(const cInt Y);
cInt PopScanbeam();
void InsertLocalMinimaIntoAEL(const cInt botY);
void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge);
void AddEdgeToSEL(TEdge *edge);
void CopyAELToSEL();
void DeleteFromSEL(TEdge *e);
void DeleteFromAEL(TEdge *e);
void UpdateEdgeIntoAEL(TEdge *&e);
void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
bool IsContributing(const TEdge& edge) const;
bool IsTopHorz(const cInt XPos);
void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
void DoMaxima(TEdge *e);
void ProcessHorizontals(bool IsTopOfScanbeam);
void ProcessHorizontal(TEdge *horzEdge, bool isTopOfScanbeam);
void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
OutRec* GetOutRec(int idx);
void AppendPolygon(TEdge *e1, TEdge *e2);
void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
OutRec* CreateOutRec();
OutPt* AddOutPt(TEdge *e, const IntPoint &pt);
void DisposeAllOutRecs();
void DisposeOutRec(PolyOutList::size_type index);
bool ProcessIntersections(const cInt topY);
void BuildIntersectList(const cInt topY);
void ProcessIntersectList();
void ProcessEdgesAtTopOfScanbeam(const cInt topY);
void BuildResult(Paths& polys);
void BuildResult2(PolyTree& polytree);
void SetHoleState(TEdge *e, OutRec *outrec);
void DisposeIntersectNodes();
bool FixupIntersectionOrder();
void FixupOutPolygon(OutRec &outrec);
bool IsHole(TEdge *e);
bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
void FixHoleLinkage(OutRec &outrec);
void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);
void ClearJoins();
void ClearGhostJoins();
void AddGhostJoin(OutPt *op, const IntPoint offPt);
bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);
void JoinCommonEdges();
void DoSimplePolygons();
void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec);
void FixupFirstLefts2(OutRec* OldOutRec, OutRec* NewOutRec);
#ifdef use_xyz
void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2);
#endif
};
//------------------------------------------------------------------------------
class ClipperOffset
{
public:
ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);
~ClipperOffset();
void AddPath(const Path& path, JoinType joinType, EndType endType);
void AddPaths(const Paths& paths, JoinType joinType, EndType endType);
void Execute(Paths& solution, double delta);
void Execute(PolyTree& solution, double delta);
void Clear();
double MiterLimit;
double ArcTolerance;
private:
Paths m_destPolys;
Path m_srcPoly;
Path m_destPoly;
std::vector<DoublePoint> m_normals;
double m_delta, m_sinA, m_sin, m_cos;
double m_miterLim, m_StepsPerRad;
IntPoint m_lowest;
PolyNode m_polyNodes;
void FixOrientations();
void DoOffset(double delta);
void OffsetPoint(int j, int& k, JoinType jointype);
void DoSquare(int j, int k);
void DoMiter(int j, int k, double r);
void DoRound(int j, int k);
};
//------------------------------------------------------------------------------
class clipperException : public std::exception
{
public:
clipperException(const char* description): m_descr(description) {}
virtual ~clipperException() throw() {}
virtual const char* what() const throw() {return m_descr.c_str();}
private:
std::string m_descr;
};
//------------------------------------------------------------------------------
} //ClipperLib namespace
#endif //clipper_hpp
/*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 6.2.0 *
* Date : 2 October 2014 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2014 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Attributions: *
* The code in this library is an extension of Bala Vatti's clipping algorithm: *
* "A generic solution to polygon clipping" *
* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
* http://portal.acm.org/citation.cfm?id=129906 *
* *
* Computer graphics and geometric modeling: implementation and algorithms *
* By Max K. Agoston *
* Springer; 1 edition (January 4, 2005) *
* http://books.google.com/books?q=vatti+clipping+agoston *
* *
* See also: *
* "Polygon Offsetting by Computing Winding Numbers" *
* Paper no. DETC2005-85513 pp. 565-575 *
* ASME 2005 International Design Engineering Technical Conferences *
* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
* September 24-28, 2005 , Long Beach, California, USA *
* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
* *
*******************************************************************************/
#ifndef clipper_hpp
#define clipper_hpp
#define CLIPPER_VERSION "6.2.0"
//use_int32: When enabled 32bit ints are used instead of 64bit ints. This
//improve performance but coordinate values are limited to the range +/- 46340
//#define use_int32
//use_xyz: adds a Z member to IntPoint. Adds a minor cost to performance.
//#define use_xyz
//use_lines: Enables line clipping. Adds a very minor cost to performance.
#define use_lines
//use_deprecated: Enables temporary support for the obsolete functions
//#define use_deprecated
#include <vector>
#include <set>
#include <stdexcept>
#include <cstring>
#include <cstdlib>
#include <ostream>
#include <functional>
#include <queue>
namespace ClipperLib {
enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
enum PolyType { ptSubject, ptClip };
//By far the most widely used winding rules for polygon filling are
//EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
//Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
//see http://glprogramming.com/red/chapter11.html
enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
#ifdef use_int32
typedef int cInt;
static cInt const loRange = 0x7FFF;
static cInt const hiRange = 0x7FFF;
#else
typedef signed long long cInt;
static cInt const loRange = 0x3FFFFFFF;
static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
typedef signed long long long64; //used by Int128 class
typedef unsigned long long ulong64;
#endif
struct IntPoint {
cInt X;
cInt Y;
#ifdef use_xyz
cInt Z;
IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {};
#else
IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {};
#endif
friend inline bool operator== (const IntPoint& a, const IntPoint& b)
{
return a.X == b.X && a.Y == b.Y;
}
friend inline bool operator!= (const IntPoint& a, const IntPoint& b)
{
return a.X != b.X || a.Y != b.Y;
}
};
//------------------------------------------------------------------------------
typedef std::vector< IntPoint > Path;
typedef std::vector< Path > Paths;
inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;}
inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;}
std::ostream& operator <<(std::ostream &s, const IntPoint &p);
std::ostream& operator <<(std::ostream &s, const Path &p);
std::ostream& operator <<(std::ostream &s, const Paths &p);
struct DoublePoint
{
double X;
double Y;
DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
};
//------------------------------------------------------------------------------
#ifdef use_xyz
typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt);
#endif
enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4};
enum JoinType {jtSquare, jtRound, jtMiter};
enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};
class PolyNode;
typedef std::vector< PolyNode* > PolyNodes;
class PolyNode
{
public:
PolyNode();
virtual ~PolyNode(){};
Path Contour;
PolyNodes Childs;
PolyNode* Parent;
PolyNode* GetNext() const;
bool IsHole() const;
bool IsOpen() const;
int ChildCount() const;
private:
unsigned Index; //node index in Parent.Childs
bool m_IsOpen;
JoinType m_jointype;
EndType m_endtype;
PolyNode* GetNextSiblingUp() const;
void AddChild(PolyNode& child);
friend class Clipper; //to access Index
friend class ClipperOffset;
};
class PolyTree: public PolyNode
{
public:
~PolyTree(){Clear();};
PolyNode* GetFirst() const;
void Clear();
int Total() const;
private:
PolyNodes AllNodes;
friend class Clipper; //to access AllNodes
};
bool Orientation(const Path &poly);
double Area(const Path &poly);
int PointInPolygon(const IntPoint &pt, const Path &path);
void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415);
void CleanPolygon(Path& poly, double distance = 1.415);
void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance = 1.415);
void CleanPolygons(Paths& polys, double distance = 1.415);
void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed);
void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed);
void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution);
void PolyTreeToPaths(const PolyTree& polytree, Paths& paths);
void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths);
void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths);
void ReversePath(Path& p);
void ReversePaths(Paths& p);
struct IntRect { cInt left; cInt top; cInt right; cInt bottom; };
//enums that are used internally ...
enum EdgeSide { esLeft = 1, esRight = 2};
//forward declarations (for stuff used internally) ...
struct TEdge;
struct IntersectNode;
struct LocalMinimum;
struct Scanbeam;
struct OutPt;
struct OutRec;
struct Join;
typedef std::vector < OutRec* > PolyOutList;
typedef std::vector < TEdge* > EdgeList;
typedef std::vector < Join* > JoinList;
typedef std::vector < IntersectNode* > IntersectList;
//------------------------------------------------------------------------------
//ClipperBase is the ancestor to the Clipper class. It should not be
//instantiated directly. This class simply abstracts the conversion of sets of
//polygon coordinates into edge objects that are stored in a LocalMinima list.
class ClipperBase
{
public:
ClipperBase();
virtual ~ClipperBase();
bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
virtual void Clear();
IntRect GetBounds();
bool PreserveCollinear() {return m_PreserveCollinear;};
void PreserveCollinear(bool value) {m_PreserveCollinear = value;};
protected:
void DisposeLocalMinimaList();
TEdge* AddBoundsToLML(TEdge *e, bool IsClosed);
void PopLocalMinima();
virtual void Reset();
TEdge* ProcessBound(TEdge* E, bool IsClockwise);
void DoMinimaLML(TEdge* E1, TEdge* E2, bool IsClosed);
TEdge* DescendToMin(TEdge *&E);
void AscendToMax(TEdge *&E, bool Appending, bool IsClosed);
typedef std::vector<LocalMinimum> MinimaList;
MinimaList::iterator m_CurrentLM;
MinimaList m_MinimaList;
bool m_UseFullRange;
EdgeList m_edges;
bool m_PreserveCollinear;
bool m_HasOpenPaths;
};
//------------------------------------------------------------------------------
class Clipper : public virtual ClipperBase
{
public:
Clipper(int initOptions = 0);
~Clipper();
bool Execute(ClipType clipType,
Paths &solution,
PolyFillType subjFillType = pftEvenOdd,
PolyFillType clipFillType = pftEvenOdd);
bool Execute(ClipType clipType,
PolyTree &polytree,
PolyFillType subjFillType = pftEvenOdd,
PolyFillType clipFillType = pftEvenOdd);
bool ReverseSolution() {return m_ReverseOutput;};
void ReverseSolution(bool value) {m_ReverseOutput = value;};
bool StrictlySimple() {return m_StrictSimple;};
void StrictlySimple(bool value) {m_StrictSimple = value;};
//set the callback function for z value filling on intersections (otherwise Z is 0)
#ifdef use_xyz
void ZFillFunction(ZFillCallback zFillFunc);
#endif
protected:
void Reset();
virtual bool ExecuteInternal();
private:
PolyOutList m_PolyOuts;
JoinList m_Joins;
JoinList m_GhostJoins;
IntersectList m_IntersectList;
ClipType m_ClipType;
typedef std::priority_queue<cInt> ScanbeamList;
ScanbeamList m_Scanbeam;
TEdge *m_ActiveEdges;
TEdge *m_SortedEdges;
bool m_ExecuteLocked;
PolyFillType m_ClipFillType;
PolyFillType m_SubjFillType;
bool m_ReverseOutput;
bool m_UsingPolyTree;
bool m_StrictSimple;
#ifdef use_xyz
ZFillCallback m_ZFill; //custom callback
#endif
void SetWindingCount(TEdge& edge);
bool IsEvenOddFillType(const TEdge& edge) const;
bool IsEvenOddAltFillType(const TEdge& edge) const;
void InsertScanbeam(const cInt Y);
cInt PopScanbeam();
void InsertLocalMinimaIntoAEL(const cInt botY);
void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge);
void AddEdgeToSEL(TEdge *edge);
void CopyAELToSEL();
void DeleteFromSEL(TEdge *e);
void DeleteFromAEL(TEdge *e);
void UpdateEdgeIntoAEL(TEdge *&e);
void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
bool IsContributing(const TEdge& edge) const;
bool IsTopHorz(const cInt XPos);
void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
void DoMaxima(TEdge *e);
void ProcessHorizontals(bool IsTopOfScanbeam);
void ProcessHorizontal(TEdge *horzEdge, bool isTopOfScanbeam);
void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
OutRec* GetOutRec(int idx);
void AppendPolygon(TEdge *e1, TEdge *e2);
void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
OutRec* CreateOutRec();
OutPt* AddOutPt(TEdge *e, const IntPoint &pt);
void DisposeAllOutRecs();
void DisposeOutRec(PolyOutList::size_type index);
bool ProcessIntersections(const cInt topY);
void BuildIntersectList(const cInt topY);
void ProcessIntersectList();
void ProcessEdgesAtTopOfScanbeam(const cInt topY);
void BuildResult(Paths& polys);
void BuildResult2(PolyTree& polytree);
void SetHoleState(TEdge *e, OutRec *outrec);
void DisposeIntersectNodes();
bool FixupIntersectionOrder();
void FixupOutPolygon(OutRec &outrec);
bool IsHole(TEdge *e);
bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
void FixHoleLinkage(OutRec &outrec);
void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);
void ClearJoins();
void ClearGhostJoins();
void AddGhostJoin(OutPt *op, const IntPoint offPt);
bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);
void JoinCommonEdges();
void DoSimplePolygons();
void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec);
void FixupFirstLefts2(OutRec* OldOutRec, OutRec* NewOutRec);
#ifdef use_xyz
void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2);
#endif
};
//------------------------------------------------------------------------------
class ClipperOffset
{
public:
ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);
~ClipperOffset();
void AddPath(const Path& path, JoinType joinType, EndType endType);
void AddPaths(const Paths& paths, JoinType joinType, EndType endType);
void Execute(Paths& solution, double delta);
void Execute(PolyTree& solution, double delta);
void Clear();
double MiterLimit;
double ArcTolerance;
private:
Paths m_destPolys;
Path m_srcPoly;
Path m_destPoly;
std::vector<DoublePoint> m_normals;
double m_delta, m_sinA, m_sin, m_cos;
double m_miterLim, m_StepsPerRad;
IntPoint m_lowest;
PolyNode m_polyNodes;
void FixOrientations();
void DoOffset(double delta);
void OffsetPoint(int j, int& k, JoinType jointype);
void DoSquare(int j, int k);
void DoMiter(int j, int k, double r);
void DoRound(int j, int k);
};
//------------------------------------------------------------------------------
class clipperException : public std::exception
{
public:
clipperException(const char* description): m_descr(description) {}
virtual ~clipperException() throw() {}
virtual const char* what() const throw() {return m_descr.c_str();}
private:
std::string m_descr;
};
//------------------------------------------------------------------------------
} //ClipperLib namespace
#endif //clipper_hpp

File diff suppressed because it is too large Load Diff

View File

@@ -1,158 +1,158 @@
// dxf.h
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
#include <algorithm>
#include <list>
#include <vector>
#include <map>
#include <set>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
//Following is required to be defined on Ubuntu with OCC 6.3.1
#ifndef HAVE_IOSTREAM
#define HAVE_IOSTREAM
#endif
typedef int Aci_t; // AutoCAD color index
typedef enum
{
eUnspecified = 0, // Unspecified (No units)
eInches,
eFeet,
eMiles,
eMillimeters,
eCentimeters,
eMeters,
eKilometers,
eMicroinches,
eMils,
eYards,
eAngstroms,
eNanometers,
eMicrons,
eDecimeters,
eDekameters,
eHectometers,
eGigameters,
eAstronomicalUnits,
eLightYears,
eParsecs
} eDxfUnits_t;
struct SplineData
{
double norm[3];
int degree;
int knots;
int control_points;
int fit_points;
int flag;
std::list<double> starttanx;
std::list<double> starttany;
std::list<double> starttanz;
std::list<double> endtanx;
std::list<double> endtany;
std::list<double> endtanz;
std::list<double> knot;
std::list<double> weight;
std::list<double> controlx;
std::list<double> controly;
std::list<double> controlz;
std::list<double> fitx;
std::list<double> fity;
std::list<double> fitz;
};
class CDxfWrite{
private:
std::ofstream* m_ofs;
bool m_fail;
public:
CDxfWrite(const char* filepath);
~CDxfWrite();
bool Failed(){return m_fail;}
void WriteLine(const double* s, const double* e, const char* layer_name );
void WritePoint(const double*, const char*);
void WriteArc(const double* s, const double* e, const double* c, bool dir, const char* layer_name );
void WriteEllipse(const double* c, double major_radius, double minor_radius, double rotation, double start_angle, double end_angle, bool dir, const char* layer_name );
void WriteCircle(const double* c, double radius, const char* layer_name );
};
// derive a class from this and implement it's virtual functions
class CDxfRead{
private:
std::ifstream* m_ifs;
bool m_fail;
char m_str[1024];
char m_unused_line[1024];
eDxfUnits_t m_eUnits;
char m_layer_name[1024];
char m_section_name[1024];
char m_block_name[1024];
bool m_ignore_errors;
typedef std::map< std::string,Aci_t > LayerAciMap_t;
LayerAciMap_t m_layer_aci; // layer names -> layer color aci map
bool ReadUnits();
bool ReadLayer();
bool ReadLine();
bool ReadText();
bool ReadArc();
bool ReadCircle();
bool ReadEllipse();
bool ReadPoint();
bool ReadSpline();
bool ReadLwPolyLine();
bool ReadPolyLine();
bool ReadVertex(double *pVertex, bool *bulge_found, double *bulge);
void OnReadArc(double start_angle, double end_angle, double radius, const double* c);
void OnReadCircle(const double* c, double radius);
void OnReadEllipse(const double* c, const double* m, double ratio, double start_angle, double end_angle);
bool ReadInsert();
void get_line();
void put_line(const char *value);
void DerefACI();
protected:
Aci_t m_aci; // manifest color name or 256 for layer color
public:
CDxfRead(const char* filepath); // this opens the file
~CDxfRead(); // this closes the file
bool Failed(){return m_fail;}
void DoRead(const bool ignore_errors = false); // this reads the file and calls the following functions
double mm( const double & value ) const;
bool IgnoreErrors() const { return(m_ignore_errors); }
virtual void OnReadLine(const double* /*s*/, const double* /*e*/){}
virtual void OnReadPoint(const double* /*s*/){}
virtual void OnReadText(const double* /*point*/, const double /*height*/, const char* /*text*/){}
virtual void OnReadArc(const double* /*s*/, const double* /*e*/, const double* /*c*/, bool /*dir*/){}
virtual void OnReadCircle(const double* /*s*/, const double* /*c*/, bool /*dir*/){}
virtual void OnReadEllipse(const double* /*c*/, double /*major_radius*/, double /*minor_radius*/, double /*rotation*/, double /*start_angle*/, double /*end_angle*/, bool /*dir*/){}
virtual void OnReadSpline(struct SplineData& /*sd*/){}
virtual void OnReadInsert(const double* /*point*/, const double* /*scale*/, const char* /*name*/, double /*rotation*/){}
virtual void AddGraphics() const { }
std::string LayerName() const;
};
// dxf.h
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
#include <algorithm>
#include <list>
#include <vector>
#include <map>
#include <set>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
//Following is required to be defined on Ubuntu with OCC 6.3.1
#ifndef HAVE_IOSTREAM
#define HAVE_IOSTREAM
#endif
typedef int Aci_t; // AutoCAD color index
typedef enum
{
eUnspecified = 0, // Unspecified (No units)
eInches,
eFeet,
eMiles,
eMillimeters,
eCentimeters,
eMeters,
eKilometers,
eMicroinches,
eMils,
eYards,
eAngstroms,
eNanometers,
eMicrons,
eDecimeters,
eDekameters,
eHectometers,
eGigameters,
eAstronomicalUnits,
eLightYears,
eParsecs
} eDxfUnits_t;
struct SplineData
{
double norm[3];
int degree;
int knots;
int control_points;
int fit_points;
int flag;
std::list<double> starttanx;
std::list<double> starttany;
std::list<double> starttanz;
std::list<double> endtanx;
std::list<double> endtany;
std::list<double> endtanz;
std::list<double> knot;
std::list<double> weight;
std::list<double> controlx;
std::list<double> controly;
std::list<double> controlz;
std::list<double> fitx;
std::list<double> fity;
std::list<double> fitz;
};
class CDxfWrite{
private:
std::ofstream* m_ofs;
bool m_fail;
public:
CDxfWrite(const char* filepath);
~CDxfWrite();
bool Failed(){return m_fail;}
void WriteLine(const double* s, const double* e, const char* layer_name );
void WritePoint(const double*, const char*);
void WriteArc(const double* s, const double* e, const double* c, bool dir, const char* layer_name );
void WriteEllipse(const double* c, double major_radius, double minor_radius, double rotation, double start_angle, double end_angle, bool dir, const char* layer_name );
void WriteCircle(const double* c, double radius, const char* layer_name );
};
// derive a class from this and implement it's virtual functions
class CDxfRead{
private:
std::ifstream* m_ifs;
bool m_fail;
char m_str[1024];
char m_unused_line[1024];
eDxfUnits_t m_eUnits;
char m_layer_name[1024];
char m_section_name[1024];
char m_block_name[1024];
bool m_ignore_errors;
typedef std::map< std::string,Aci_t > LayerAciMap_t;
LayerAciMap_t m_layer_aci; // layer names -> layer color aci map
bool ReadUnits();
bool ReadLayer();
bool ReadLine();
bool ReadText();
bool ReadArc();
bool ReadCircle();
bool ReadEllipse();
bool ReadPoint();
bool ReadSpline();
bool ReadLwPolyLine();
bool ReadPolyLine();
bool ReadVertex(double *pVertex, bool *bulge_found, double *bulge);
void OnReadArc(double start_angle, double end_angle, double radius, const double* c);
void OnReadCircle(const double* c, double radius);
void OnReadEllipse(const double* c, const double* m, double ratio, double start_angle, double end_angle);
bool ReadInsert();
void get_line();
void put_line(const char *value);
void DerefACI();
protected:
Aci_t m_aci; // manifest color name or 256 for layer color
public:
CDxfRead(const char* filepath); // this opens the file
~CDxfRead(); // this closes the file
bool Failed(){return m_fail;}
void DoRead(const bool ignore_errors = false); // this reads the file and calls the following functions
double mm( const double & value ) const;
bool IgnoreErrors() const { return(m_ignore_errors); }
virtual void OnReadLine(const double* /*s*/, const double* /*e*/){}
virtual void OnReadPoint(const double* /*s*/){}
virtual void OnReadText(const double* /*point*/, const double /*height*/, const char* /*text*/){}
virtual void OnReadArc(const double* /*s*/, const double* /*e*/, const double* /*c*/, bool /*dir*/){}
virtual void OnReadCircle(const double* /*s*/, const double* /*c*/, bool /*dir*/){}
virtual void OnReadEllipse(const double* /*c*/, double /*major_radius*/, double /*minor_radius*/, double /*rotation*/, double /*start_angle*/, double /*end_angle*/, bool /*dir*/){}
virtual void OnReadSpline(struct SplineData& /*sd*/){}
virtual void OnReadInsert(const double* /*point*/, const double* /*scale*/, const char* /*name*/, double /*rotation*/){}
virtual void AddGraphics() const { }
std::string LayerName() const;
};

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,376 +1,376 @@
////////////////////////////////////////////////////////////////////////////////////////////////
// 2d geometry classes - implements 2d kurve offset for use in dll
//
// g.j.hawkesford August 2003
//
// This program is released under the BSD license. See the file COPYING for details.
//
////////////////////////////////////////////////////////////////////////////////////////////////
#include "geometry.h"
using namespace geoff_geometry;
namespace geoff_geometry {
static Kurve eliminateLoops(const Kurve& k , const Kurve& originalk, double offset, int& ret);
static bool DoesIntersInterfere(const Point& pInt, const Kurve& k, double offset);
int Kurve::Offset(vector<Kurve*>&OffsetKurves, double offset, int direction, int method, int& ret)const {
switch(method) {
case NO_ELIMINATION:
case BASIC_OFFSET:
{
Kurve* ko = new Kurve;
int n = OffsetMethod1(*ko, offset, direction, method, ret);
OffsetKurves.push_back(ko);
return n;
}
default:
FAILURE(L"Requested Offsetting Method not available");
}
return 0;
}
int Kurve::OffsetMethod1(Kurve& kOffset, double off, int direction, int method, int& ret)const
{
// offset kurve with simple span elimination
// direction 1 = left, -1 = right
// ret = 0 - kurve offset ok
// = 1 - kurve has differential scale (not allowed)
// = 2 - offset failed
// = 3 - offset too large
if(this == &kOffset) FAILURE(L"Illegal Call - 'this' must not be kOffset");
double offset = (direction == GEOFF_LEFT)?off : -off;
if(fabs(offset) < geoff_geometry::TOLERANCE || m_nVertices < 2) {
kOffset = *this;
ret = 0;
return 1;
}
Span curSpan, curSpanOff; // current & offset spans
Span prevSpanOff; // previous offset span
Point p0, p1; // Offset span intersections
// offset Kurve
kOffset = Matrix(*this);
if(m_mirrored) offset = -offset;
int RollDir = ( off < 0 ) ? direction : - direction; // Roll arc direction
double scalex;
if(!GetScale(scalex)) {
ret = 1;
return 0; // differential scale
}
offset /= scalex;
bool bClosed = Closed();
int nspans = nSpans();
if(bClosed) {
Get(nspans, curSpan, true); // assign previous span for closed
prevSpanOff = curSpan.Offset(offset);
nspans++; // read first again
}
for(int spannumber = 1; spannumber <= nspans; spannumber++) {
if(spannumber > nSpans())
Get(1, curSpan, true); // closed kurve - read first span again
else
Get(spannumber, curSpan, true);
if(!curSpan.NullSpan) {
int numint = 0;
curSpanOff = curSpan.Offset(offset);
curSpanOff.ID = 0;
if(!kOffset.m_started) {
kOffset.Start(curSpanOff.p0);
kOffset.AddSpanID(0);
}
if(spannumber > 1) {
// see if tangent
double d = curSpanOff.p0.Dist(prevSpanOff.p1);
if((d > geoff_geometry::TOLERANCE) && (curSpanOff.NullSpan == false && prevSpanOff.NullSpan == false)) {
// see if offset spans intersect
double cp = prevSpanOff.ve ^ curSpanOff.vs;
bool inters = (cp > 0 && direction == GEOFF_LEFT) || (cp < 0 && direction == GEOFF_RIGHT);
if(inters) {
double t[4];
numint = prevSpanOff.Intof(curSpanOff, p0, p1, t);
}
if(numint == 1) {
// intersection - modify previous endpoint
kOffset.Replace(kOffset.m_nVertices-1, prevSpanOff.dir, p0, prevSpanOff.pc, prevSpanOff.ID);
}
else {
// 0 or 2 intersections, add roll around (remove -ve loops in elimination function)
if(kOffset.Add(RollDir, curSpanOff.p0, curSpan.p0, false)) kOffset.AddSpanID(ROLL_AROUND);
}
}
}
// add span
if(spannumber < m_nVertices) {
curSpanOff.ID = spannumber;
kOffset.Add(curSpanOff, false);
}
else if(numint == 1) // or replace the closed first span
kOffset.Replace(0, 0, p0, Point(0, 0), 0);
}
if(!curSpanOff.NullSpan)prevSpanOff = curSpanOff;
} // end of main pre-offsetting loop
#ifdef _DEBUG
//testDraw->AddKurve("", &kOffset, 0, GREEN);
// outXML oxml(L"c:\\temp\\eliminateLoops.xml");
// oxml.startElement(L"eliminateLoops");
// oxml.Write(kOffset, L"kOffset");
// oxml.endElement();
#endif
// eliminate loops
if(method == NO_ELIMINATION) {
ret = 0;
return 1;
}
kOffset = eliminateLoops(kOffset, *this, offset, ret);
if(ret == 0 && bClosed) {
// check for inverted offsets of closed kurves
if(kOffset.Closed()) {
double a = Area();
int dir = (a < 0);
double ao = kOffset.Area();
int dirOffset = ao < 0;
if(dir != dirOffset)
ret = 3;
else {
// check area change compatible with offset direction - catastrophic failure
bool bigger = (a > 0 && offset > 0) || (a < 0 && offset < 0);
if(bigger && fabs(ao) < fabs(a)) ret = 2;
}
}
else
ret = 2; // started closed but now open??
}
return (ret == 0)?1 : 0;
}
static Kurve eliminateLoops(const Kurve& k , const Kurve& originalk, double offset, int& ret) {
// a simple loop elimination routine based on first offset ideas in Peps
// this needs extensive work for future
// start point mustn't disappear & only one valid offset is determined
//
// ret = 0 for ok
// ret = 2 for impossible geometry
Span sp0, sp1;
Point pInt, pIntOther;
Kurve ko; // eliminated output
ko = Matrix(k);
int kinVertex = 0;
while(kinVertex <= k.nSpans()) {
bool clipped = false ; // not in a clipped section (assumption with this simple method)
sp0.dir = k.Get(kinVertex, sp0.p0, sp0.pc);
sp0.ID = k.GetSpanID(kinVertex++);
if (kinVertex == 1) {
ko.Start(sp0.p0); // start point mustn't disappear for this simple method
ko.AddSpanID(sp0.ID);
}
if (kinVertex <= k.nSpans()) { // any more?
int ksaveVertex = kinVertex ;
sp0.dir = k.Get(kinVertex, sp0.p1, sp0.pc); // first span
sp0.ID = k.GetSpanID(kinVertex++);
sp0.SetProperties(true);
int ksaveVertex1 = kinVertex; // mark position AA
if (kinVertex <= k.nSpans()) { // get the next but one span
sp1.dir = k.Get(kinVertex, sp1.p0, sp1.pc);
sp1.ID = k.GetSpanID(kinVertex++);
int ksaveVertex2 = kinVertex; // mark position BB
int fwdCount = 0;
while(kinVertex <= k.nSpans()) {
sp1.dir = k.Get(kinVertex, sp1.p1, sp1.pc); // check span
sp1.ID = k.GetSpanID(kinVertex++);
sp1.SetProperties(true);
double t[4];
int numint = sp0.Intof(sp1, pInt, pIntOther, t); // find span intersections
if(numint && sp0.p0.Dist(pInt) < geoff_geometry::TOLERANCE ) numint=0; // check that intersection is not at the start of the check span
if(numint ) {
if(numint == 2) {
// choose first intercept on sp0
Span spd = sp0;
spd.p1 = pInt;
spd.SetProperties(true);
double dd = spd.length;
spd.p1 = pIntOther;
spd.SetProperties(true);
if(dd > spd.length) pInt = pIntOther;
numint = 1;
}
ksaveVertex = ksaveVertex1 ;
clipped = true ; // in a clipped section
if(DoesIntersInterfere(pInt, originalk, offset) == false) {
sp0.p1 = pInt; // ok so truncate this span to the intersection
clipped = false; // end of clipped section
break;
}
// no valid intersection found so carry on
}
sp1.p0 = sp1.p1 ; // next
ksaveVertex1 = ksaveVertex2 ; // pos AA = BB
ksaveVertex2 = kinVertex; // mark
if((kinVertex > k.nSpans() || fwdCount++ > 25) && clipped == false) break;
}
}
if(clipped) {
ret = 2; // still in a clipped section - error
return ko;
}
ko.Add(sp0, false);
kinVertex = ksaveVertex;
}
}
ret = 0;
return ko; // no more spans - seems ok
}
static bool DoesIntersInterfere(const Point& pInt, const Kurve& k, double offset) {
// check that intersections don't interfere with the original kurve
Span sp;
Point dummy;
int kCheckVertex = 0;
k.Get(kCheckVertex++, sp.p0, sp.pc);
offset = fabs(offset) - geoff_geometry::TOLERANCE;
while(kCheckVertex <= k.nSpans()) {
sp.dir = k.Get(kCheckVertex++, sp.p1, sp.pc);
sp.SetProperties(true);
// check for interference
if(Dist(sp, pInt, dummy) < offset) return true;
sp.p0 = sp.p1;
}
return false; // intersection is ok
}
}
static struct iso {
Span sp;
Span off;
} isodata;
static void isoRadius(Span& before, Span& blend, Span& after, double radius);
int Kurve::OffsetISOMethod(Kurve& kOut, double off, int direction, bool BlendAll)const {
// produces a special offset Kurve - observing so-called ISO radii
// eg line/arc/line tangent - keep arc radius constant
// this method also considers arc/arc/arc etc.
// interior radius must be smallest of triplet for above.
// parameters:-
// Output kOut resulting kurve
// Input off offset amount
// Input direction offset direction (LEFT or RIGHT)
// Input BlendAall if false only consider ISO radius for LINE/ARC/LINE
// if true consider all blended radii (ARC/ARC/ARC etc.)
double offset = (direction == GEOFF_LEFT)?off : -off;
if(FEQZ(off) || nSpans() < 1) {
kOut = *this;
return 1;
}
double cptol = 1.0e-05;
std::vector<iso> spans;
for(int i = 0; i < nSpans(); i++) { // store all spans and offsets
Get(i+1, isodata.sp, true, true);
isodata.off = isodata.sp.Offset(offset);
spans.push_back(isodata);
}
for(int i = 0; i < nSpans() - 1; i++) // calculate intersections for none tangent spans
if(fabs(spans[i].off.ve ^ spans[i+1].off.vs) > cptol) spans[i].off.JoinSeparateSpans(spans[i+1].off);
for(int i = 1; i < nSpans() - 1; i++) { // deal with isoradii
if(spans[i].off.dir) {
if(BlendAll) { // interior radius should be smaller than neighbours
if(spans[i-1].sp.dir)
if(spans[i-1].sp.radius < spans[i].sp.radius) continue;
if(spans[i+1].sp.dir)
if(spans[i+1].sp.radius < spans[i].sp.radius) continue;
}
else {
if((spans[i-1].off.dir || spans[i+1].off.dir)) continue; // linear neighbours only
}
if((fabs(spans[i-1].sp.ve ^ spans[i].sp.vs) < cptol) && (fabs(spans[i].sp.ve ^ spans[i+1].sp.vs) < cptol)) {
// isoradius - calculate the new offset radius and modify neighbouring spans
isoRadius(spans[i-1].off, spans[i].off, spans[i+1].off, spans[i].sp.radius);
}
}
}
kOut.Start(spans[0].off.p0); // start point
for(int i = 0; i < nSpans(); i++)
kOut.Add(spans[i].off.dir, spans[i].off.p1, spans[i].off.pc); // output all spans
return 1;
}
static void isoRadius(Span& before, Span& blend, Span& after, double radius) {
// calculate the new offset radius and modify neighbouring spans
int direction = ((before.ve ^ after.vs) > 0)? 1 : -1; // offset direction
Span beforeOff = before.Offset(direction * radius);
Span afterOff = after.Offset(direction * radius);
int turnLeft = ((before.ve ^ after.vs) > 0)? 1 : -1;
if(before.dir == LINEAR) {
CLine b(beforeOff);
if(after.dir == LINEAR) {
CLine a(afterOff);
blend.pc = b.Intof(a);
}
else {
Circle a(afterOff);
b.Intof(turnLeft * after.dir, a, blend.pc);
}
}
else {
Circle b(beforeOff);
if(after.dir == LINEAR) {
CLine a(afterOff);
a.Intof(-turnLeft * before.dir, b, blend.pc);
}
else {
// arc arc
Circle a(afterOff);
int leftright = ((Vector2d(b.pc, blend.pc) ^ Vector2d(b.pc, a.pc)) < 0)? 1 : -1;
b.Intof(leftright, a, blend.pc);
}
}
before.p1 = blend.p0 = before.Near(blend.pc);
after.p0 = blend.p1 = after.Near(blend.pc);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// 2d geometry classes - implements 2d kurve offset for use in dll
//
// g.j.hawkesford August 2003
//
// This program is released under the BSD license. See the file COPYING for details.
//
////////////////////////////////////////////////////////////////////////////////////////////////
#include "geometry.h"
using namespace geoff_geometry;
namespace geoff_geometry {
static Kurve eliminateLoops(const Kurve& k , const Kurve& originalk, double offset, int& ret);
static bool DoesIntersInterfere(const Point& pInt, const Kurve& k, double offset);
int Kurve::Offset(vector<Kurve*>&OffsetKurves, double offset, int direction, int method, int& ret)const {
switch(method) {
case NO_ELIMINATION:
case BASIC_OFFSET:
{
Kurve* ko = new Kurve;
int n = OffsetMethod1(*ko, offset, direction, method, ret);
OffsetKurves.push_back(ko);
return n;
}
default:
FAILURE(L"Requested Offsetting Method not available");
}
return 0;
}
int Kurve::OffsetMethod1(Kurve& kOffset, double off, int direction, int method, int& ret)const
{
// offset kurve with simple span elimination
// direction 1 = left, -1 = right
// ret = 0 - kurve offset ok
// = 1 - kurve has differential scale (not allowed)
// = 2 - offset failed
// = 3 - offset too large
if(this == &kOffset) FAILURE(L"Illegal Call - 'this' must not be kOffset");
double offset = (direction == GEOFF_LEFT)?off : -off;
if(fabs(offset) < geoff_geometry::TOLERANCE || m_nVertices < 2) {
kOffset = *this;
ret = 0;
return 1;
}
Span curSpan, curSpanOff; // current & offset spans
Span prevSpanOff; // previous offset span
Point p0, p1; // Offset span intersections
// offset Kurve
kOffset = Matrix(*this);
if(m_mirrored) offset = -offset;
int RollDir = ( off < 0 ) ? direction : - direction; // Roll arc direction
double scalex;
if(!GetScale(scalex)) {
ret = 1;
return 0; // differential scale
}
offset /= scalex;
bool bClosed = Closed();
int nspans = nSpans();
if(bClosed) {
Get(nspans, curSpan, true); // assign previous span for closed
prevSpanOff = curSpan.Offset(offset);
nspans++; // read first again
}
for(int spannumber = 1; spannumber <= nspans; spannumber++) {
if(spannumber > nSpans())
Get(1, curSpan, true); // closed kurve - read first span again
else
Get(spannumber, curSpan, true);
if(!curSpan.NullSpan) {
int numint = 0;
curSpanOff = curSpan.Offset(offset);
curSpanOff.ID = 0;
if(!kOffset.m_started) {
kOffset.Start(curSpanOff.p0);
kOffset.AddSpanID(0);
}
if(spannumber > 1) {
// see if tangent
double d = curSpanOff.p0.Dist(prevSpanOff.p1);
if((d > geoff_geometry::TOLERANCE) && (curSpanOff.NullSpan == false && prevSpanOff.NullSpan == false)) {
// see if offset spans intersect
double cp = prevSpanOff.ve ^ curSpanOff.vs;
bool inters = (cp > 0 && direction == GEOFF_LEFT) || (cp < 0 && direction == GEOFF_RIGHT);
if(inters) {
double t[4];
numint = prevSpanOff.Intof(curSpanOff, p0, p1, t);
}
if(numint == 1) {
// intersection - modify previous endpoint
kOffset.Replace(kOffset.m_nVertices-1, prevSpanOff.dir, p0, prevSpanOff.pc, prevSpanOff.ID);
}
else {
// 0 or 2 intersections, add roll around (remove -ve loops in elimination function)
if(kOffset.Add(RollDir, curSpanOff.p0, curSpan.p0, false)) kOffset.AddSpanID(ROLL_AROUND);
}
}
}
// add span
if(spannumber < m_nVertices) {
curSpanOff.ID = spannumber;
kOffset.Add(curSpanOff, false);
}
else if(numint == 1) // or replace the closed first span
kOffset.Replace(0, 0, p0, Point(0, 0), 0);
}
if(!curSpanOff.NullSpan)prevSpanOff = curSpanOff;
} // end of main pre-offsetting loop
#ifdef _DEBUG
//testDraw->AddKurve("", &kOffset, 0, GREEN);
// outXML oxml(L"c:\\temp\\eliminateLoops.xml");
// oxml.startElement(L"eliminateLoops");
// oxml.Write(kOffset, L"kOffset");
// oxml.endElement();
#endif
// eliminate loops
if(method == NO_ELIMINATION) {
ret = 0;
return 1;
}
kOffset = eliminateLoops(kOffset, *this, offset, ret);
if(ret == 0 && bClosed) {
// check for inverted offsets of closed kurves
if(kOffset.Closed()) {
double a = Area();
int dir = (a < 0);
double ao = kOffset.Area();
int dirOffset = ao < 0;
if(dir != dirOffset)
ret = 3;
else {
// check area change compatible with offset direction - catastrophic failure
bool bigger = (a > 0 && offset > 0) || (a < 0 && offset < 0);
if(bigger && fabs(ao) < fabs(a)) ret = 2;
}
}
else
ret = 2; // started closed but now open??
}
return (ret == 0)?1 : 0;
}
static Kurve eliminateLoops(const Kurve& k , const Kurve& originalk, double offset, int& ret) {
// a simple loop elimination routine based on first offset ideas in Peps
// this needs extensive work for future
// start point mustn't disappear & only one valid offset is determined
//
// ret = 0 for ok
// ret = 2 for impossible geometry
Span sp0, sp1;
Point pInt, pIntOther;
Kurve ko; // eliminated output
ko = Matrix(k);
int kinVertex = 0;
while(kinVertex <= k.nSpans()) {
bool clipped = false ; // not in a clipped section (assumption with this simple method)
sp0.dir = k.Get(kinVertex, sp0.p0, sp0.pc);
sp0.ID = k.GetSpanID(kinVertex++);
if (kinVertex == 1) {
ko.Start(sp0.p0); // start point mustn't disappear for this simple method
ko.AddSpanID(sp0.ID);
}
if (kinVertex <= k.nSpans()) { // any more?
int ksaveVertex = kinVertex ;
sp0.dir = k.Get(kinVertex, sp0.p1, sp0.pc); // first span
sp0.ID = k.GetSpanID(kinVertex++);
sp0.SetProperties(true);
int ksaveVertex1 = kinVertex; // mark position AA
if (kinVertex <= k.nSpans()) { // get the next but one span
sp1.dir = k.Get(kinVertex, sp1.p0, sp1.pc);
sp1.ID = k.GetSpanID(kinVertex++);
int ksaveVertex2 = kinVertex; // mark position BB
int fwdCount = 0;
while(kinVertex <= k.nSpans()) {
sp1.dir = k.Get(kinVertex, sp1.p1, sp1.pc); // check span
sp1.ID = k.GetSpanID(kinVertex++);
sp1.SetProperties(true);
double t[4];
int numint = sp0.Intof(sp1, pInt, pIntOther, t); // find span intersections
if(numint && sp0.p0.Dist(pInt) < geoff_geometry::TOLERANCE ) numint=0; // check that intersection is not at the start of the check span
if(numint ) {
if(numint == 2) {
// choose first intercept on sp0
Span spd = sp0;
spd.p1 = pInt;
spd.SetProperties(true);
double dd = spd.length;
spd.p1 = pIntOther;
spd.SetProperties(true);
if(dd > spd.length) pInt = pIntOther;
numint = 1;
}
ksaveVertex = ksaveVertex1 ;
clipped = true ; // in a clipped section
if(DoesIntersInterfere(pInt, originalk, offset) == false) {
sp0.p1 = pInt; // ok so truncate this span to the intersection
clipped = false; // end of clipped section
break;
}
// no valid intersection found so carry on
}
sp1.p0 = sp1.p1 ; // next
ksaveVertex1 = ksaveVertex2 ; // pos AA = BB
ksaveVertex2 = kinVertex; // mark
if((kinVertex > k.nSpans() || fwdCount++ > 25) && clipped == false) break;
}
}
if(clipped) {
ret = 2; // still in a clipped section - error
return ko;
}
ko.Add(sp0, false);
kinVertex = ksaveVertex;
}
}
ret = 0;
return ko; // no more spans - seems ok
}
static bool DoesIntersInterfere(const Point& pInt, const Kurve& k, double offset) {
// check that intersections don't interfere with the original kurve
Span sp;
Point dummy;
int kCheckVertex = 0;
k.Get(kCheckVertex++, sp.p0, sp.pc);
offset = fabs(offset) - geoff_geometry::TOLERANCE;
while(kCheckVertex <= k.nSpans()) {
sp.dir = k.Get(kCheckVertex++, sp.p1, sp.pc);
sp.SetProperties(true);
// check for interference
if(Dist(sp, pInt, dummy) < offset) return true;
sp.p0 = sp.p1;
}
return false; // intersection is ok
}
}
static struct iso {
Span sp;
Span off;
} isodata;
static void isoRadius(Span& before, Span& blend, Span& after, double radius);
int Kurve::OffsetISOMethod(Kurve& kOut, double off, int direction, bool BlendAll)const {
// produces a special offset Kurve - observing so-called ISO radii
// eg line/arc/line tangent - keep arc radius constant
// this method also considers arc/arc/arc etc.
// interior radius must be smallest of triplet for above.
// parameters:-
// Output kOut resulting kurve
// Input off offset amount
// Input direction offset direction (LEFT or RIGHT)
// Input BlendAall if false only consider ISO radius for LINE/ARC/LINE
// if true consider all blended radii (ARC/ARC/ARC etc.)
double offset = (direction == GEOFF_LEFT)?off : -off;
if(FEQZ(off) || nSpans() < 1) {
kOut = *this;
return 1;
}
double cptol = 1.0e-05;
std::vector<iso> spans;
for(int i = 0; i < nSpans(); i++) { // store all spans and offsets
Get(i+1, isodata.sp, true, true);
isodata.off = isodata.sp.Offset(offset);
spans.push_back(isodata);
}
for(int i = 0; i < nSpans() - 1; i++) // calculate intersections for none tangent spans
if(fabs(spans[i].off.ve ^ spans[i+1].off.vs) > cptol) spans[i].off.JoinSeparateSpans(spans[i+1].off);
for(int i = 1; i < nSpans() - 1; i++) { // deal with isoradii
if(spans[i].off.dir) {
if(BlendAll) { // interior radius should be smaller than neighbours
if(spans[i-1].sp.dir)
if(spans[i-1].sp.radius < spans[i].sp.radius) continue;
if(spans[i+1].sp.dir)
if(spans[i+1].sp.radius < spans[i].sp.radius) continue;
}
else {
if((spans[i-1].off.dir || spans[i+1].off.dir)) continue; // linear neighbours only
}
if((fabs(spans[i-1].sp.ve ^ spans[i].sp.vs) < cptol) && (fabs(spans[i].sp.ve ^ spans[i+1].sp.vs) < cptol)) {
// isoradius - calculate the new offset radius and modify neighbouring spans
isoRadius(spans[i-1].off, spans[i].off, spans[i+1].off, spans[i].sp.radius);
}
}
}
kOut.Start(spans[0].off.p0); // start point
for(int i = 0; i < nSpans(); i++)
kOut.Add(spans[i].off.dir, spans[i].off.p1, spans[i].off.pc); // output all spans
return 1;
}
static void isoRadius(Span& before, Span& blend, Span& after, double radius) {
// calculate the new offset radius and modify neighbouring spans
int direction = ((before.ve ^ after.vs) > 0)? 1 : -1; // offset direction
Span beforeOff = before.Offset(direction * radius);
Span afterOff = after.Offset(direction * radius);
int turnLeft = ((before.ve ^ after.vs) > 0)? 1 : -1;
if(before.dir == LINEAR) {
CLine b(beforeOff);
if(after.dir == LINEAR) {
CLine a(afterOff);
blend.pc = b.Intof(a);
}
else {
Circle a(afterOff);
b.Intof(turnLeft * after.dir, a, blend.pc);
}
}
else {
Circle b(beforeOff);
if(after.dir == LINEAR) {
CLine a(afterOff);
a.Intof(-turnLeft * before.dir, b, blend.pc);
}
else {
// arc arc
Circle a(afterOff);
int leftright = ((Vector2d(b.pc, blend.pc) ^ Vector2d(b.pc, a.pc)) < 0)? 1 : -1;
b.Intof(leftright, a, blend.pc);
}
}
before.p1 = blend.p0 = before.Near(blend.pc);
after.p0 = blend.p1 = after.Near(blend.pc);
}

View File

@@ -1,9 +1,9 @@
import area
p = area.Point(0,0)
m = area.Matrix([1,0,0,12, 0,1,0,0, 0,0,1,0, 0,0,0,1])
p.Transform(m)
print (p.x, p.y)
import area
p = area.Point(0,0)
m = area.Matrix([1,0,0,12, 0,1,0,0, 0,0,1,0, 0,0,0,1])
p.Transform(m)
print (p.x, p.y)