Debian Codegraph @

src/Gui/View3DPy.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <QColor>
24 #include <QDir>
25 #include <QFileInfo>
26 #include <QImage>
27
28 #include <Inventor/SoPickedPoint.h>
29 #include <Inventor/actions/SoWriteAction.h>
30 #include <Inventor/annex/HardCopy/SoVectorizePSAction.h>
31 #include <Inventor/draggers/SoDragger.h>
32 #include <Inventor/nodes/SoCamera.h>
33 #include <Inventor/nodes/SoOrthographicCamera.h>
34 #include <Inventor/nodes/SoPerspectiveCamera.h>
35
36 #include <App/Application.h>
37 #include <App/Document.h>
38 #include <App/DocumentObject.h>
39 #include <App/DocumentObjectPy.h>
40 #include <App/GeoFeature.h>
41 #include <Base/Console.h>
42 #include <Base/Exception.h>
43 #include <Base/GeometryPyCXX.h>
44 #include <Base/Interpreter.h>
45 #include <Base/PlacementPy.h>
46 #include <Base/PyWrapParseTupleAndKeywords.h>
47 #include <Base/RotationPy.h>
48 #include <Base/VectorPy.h>
49
50 #include "View3DPy.h"
51
52 #include "Camera.h"
53 #include "Document.h"
54 #include "Inventor/SoMouseWheelEvent.h"
55 #include "Navigation/NavigationStyle.h"
56 #include "PythonWrapper.h"
57 #include "SoFCDB.h"
58 #include "SoFCOffscreenRenderer.h"
59 #include "SoFCSelectionAction.h"
60 #include "SoFCVectorizeSVGAction.h"
61 #include "SoFCVectorizeU3DAction.h"
62 #include "View3DInventor.h"
63 #include "View3DInventorViewer.h"
64 #include "ViewProviderDocumentObject.h"
65 #include "ViewProviderExtern.h"
66
67
68 using namespace Gui;
69
70
71 void View3DInventorPy::init_type()
72 {
73 behaviors().name("View3DInventorPy");
74 behaviors().doc("Python binding class for the Inventor viewer class");
75 // you must have overwritten the virtual functions
76 behaviors().supportRepr();
77 behaviors().supportGetattr();
78 behaviors().supportSetattr();
79
80 add_varargs_method("fitAll", &View3DInventorPy::fitAll, "fitAll()");
81 add_keyword_method("boxZoom", &View3DInventorPy::boxZoom, "boxZoom()");
82
83 add_noargs_method("viewBottom", &View3DInventorPy::viewBottom, "viewBottom()");
84 add_noargs_method("viewFront", &View3DInventorPy::viewFront, "viewFront()");
85 add_noargs_method("viewLeft", &View3DInventorPy::viewLeft, "viewLeft()");
86 add_noargs_method("viewRear", &View3DInventorPy::viewRear, "viewRear()");
87 add_noargs_method("viewRight", &View3DInventorPy::viewRight, "viewRight()");
88 add_noargs_method("viewTop", &View3DInventorPy::viewTop, "viewTop()");
89 add_noargs_method(
90 "viewAxometric",
91 &View3DInventorPy::viewIsometric,
92 "viewAxonometric()"
93 ); // for backward compatibility
94 add_noargs_method("viewAxonometric", &View3DInventorPy::viewIsometric, "viewAxonometric()");
95 add_noargs_method("viewIsometric", &View3DInventorPy::viewIsometric, "viewIsometric()");
96 add_noargs_method("viewDimetric", &View3DInventorPy::viewDimetric, "viewDimetric()");
97 add_noargs_method("viewTrimetric", &View3DInventorPy::viewTrimetric, "viewTrimetric()");
98 add_varargs_method(
99 "viewDefaultOrientation",
100 &View3DInventorPy::viewDefaultOrientation,
101 "viewDefaultOrientation(ori_str = '', scale = -1.0): sets camera rotation to a predefined "
102 "one, \n"
103 "and camera position and zoom to show certain amount of model space. \n"
104 "ori_string can be 'Top', 'Bottom', 'Front', 'Rear', 'Left', 'Right', \n"
105 "'Isometric', 'Dimetric', 'Trimetric', 'Custom'. If empty, the value is \n"
106 "fetched from Parameters.\n"
107 "scale sets distance from camera to origin, and height of the screen in \n"
108 "model space, so that a sphere of diameter <scale> fits the height of the\n"
109 "viewport. If zero, scaling is not done. If negative, the value is \n"
110 "fetched from Parameters."
111 );
112 add_noargs_method("viewRotateLeft", &View3DInventorPy::viewRotateLeft, "viewRotateLeft()");
113 add_noargs_method("viewRotateRight", &View3DInventorPy::viewRotateRight, "viewRotateRight()");
114 add_noargs_method("zoomIn", &View3DInventorPy::zoomIn, "zoomIn()");
115 add_noargs_method("zoomOut", &View3DInventorPy::zoomOut, "zoomOut()");
116 add_varargs_method("viewPosition", &View3DInventorPy::viewPosition, "viewPosition()");
117 add_varargs_method("startAnimating", &View3DInventorPy::startAnimating, "startAnimating()");
118 add_noargs_method("stopAnimating", &View3DInventorPy::stopAnimating, "stopAnimating()");
119 add_varargs_method(
120 "setAnimationEnabled",
121 &View3DInventorPy::setAnimationEnabled,
122 "setAnimationEnabled()"
123 );
124 add_noargs_method("isAnimationEnabled", &View3DInventorPy::isAnimationEnabled, "isAnimationEnabled()");
125 add_varargs_method(
126 "setPopupMenuEnabled",
127 &View3DInventorPy::setPopupMenuEnabled,
128 "setPopupMenuEnabled()"
129 );
130 add_noargs_method("isPopupMenuEnabled", &View3DInventorPy::isPopupMenuEnabled, "isPopupMenuEnabled()");
131 add_varargs_method("dump", &View3DInventorPy::dump, "dump(filename, [onlyVisible=False])");
132 add_varargs_method("dumpNode", &View3DInventorPy::dumpNode, "dumpNode(node)");
133 add_varargs_method("setStereoType", &View3DInventorPy::setStereoType, "setStereoType()");
134 add_noargs_method("getStereoType", &View3DInventorPy::getStereoType, "getStereoType()");
135 add_noargs_method("listStereoTypes", &View3DInventorPy::listStereoTypes, "listStereoTypes()");
136 add_varargs_method("saveImage", &View3DInventorPy::saveImage, "saveImage()");
137 add_varargs_method("saveVectorGraphic", &View3DInventorPy::saveVectorGraphic, "saveVectorGraphic()");
138 add_noargs_method("getCamera", &View3DInventorPy::getCamera, "getCamera()");
139 add_noargs_method("getCameraNode", &View3DInventorPy::getCameraNode, "getCameraNode()");
140 add_noargs_method(
141 "getViewDirection",
142 &View3DInventorPy::getViewDirection,
143 "getViewDirection() --> tuple of floats\n"
144 "returns the direction vector the view is currently pointing at as tuple with xyz values\n"
145 );
146 add_noargs_method(
147 "getUpDirection",
148 &View3DInventorPy::getUpDirection,
149 "getUpDirection() --> tuple of integers\n"
150 "Returns the up direction vector\n"
151 );
152 add_varargs_method(
153 "setViewDirection",
154 &View3DInventorPy::setViewDirection,
155 "setViewDirection(tuple) --> None\n"
156 "Sets the direction the view is pointing at. The direction must be given as tuple with\n"
157 "three coordinates xyz"
158 );
159 add_varargs_method("setCamera", &View3DInventorPy::setCamera, "setCamera()");
160 add_varargs_method(
161 "setCameraOrientation",
162 &View3DInventorPy::setCameraOrientation,
163 "setCameraOrientation()"
164 );
165 add_noargs_method(
166 "getCameraOrientation",
167 &View3DInventorPy::getCameraOrientation,
168 "getCameraOrientation()"
169 );
170 add_noargs_method("getCameraType", &View3DInventorPy::getCameraType, "getCameraType()");
171 add_varargs_method("setCameraType", &View3DInventorPy::setCameraType, "setCameraType()");
172 add_noargs_method("listCameraTypes", &View3DInventorPy::listCameraTypes, "listCameraTypes()");
173 add_noargs_method(
174 "getCursorPos",
175 &View3DInventorPy::getCursorPos,
176 "getCursorPos() -> tuple of integers\n"
177 "\n"
178 "Return the current cursor position relative to the coordinate system of the\n"
179 "viewport region.\n"
180 );
181 add_varargs_method(
182 "getObjectInfo",
183 &View3DInventorPy::getObjectInfo,
184 "getObjectInfo(tuple(int,int), [pick_radius]) -> dictionary or None\n"
185 "\n"
186 "Return a dictionary with the name of document, object and component. The\n"
187 "dictionary also contains the coordinates of the appropriate 3d point of\n"
188 "the underlying geometry in the scenegraph.\n"
189 "If no geometry was found 'None' is returned, instead.\n"
190 );
191 add_varargs_method(
192 "getObjectsInfo",
193 &View3DInventorPy::getObjectsInfo,
194 "getObjectsInfo(tuple(int,int), [pick_radius]) -> dictionary or None\n"
195 "\n"
196 "Does the same as getObjectInfo() but returns a list of dictionaries or None.\n"
197 );
198 add_noargs_method("getSize", &View3DInventorPy::getSize, "getSize()");
199 add_varargs_method(
200 "getObjectInfoRay",
201 &View3DInventorPy::getObjectInfoRay,
202 "getObjectInfoRay(tuple(3D vector,3D vector) or tuple of 6 floats) -> dictionary or None\n"
203 "\n"
204 "Vectors represent start point and direction of intersection ray\n"
205 "Return a dictionary with the name of document, object and component. The\n"
206 "dictionary also contains the coordinates of the appropriate 3d point of\n"
207 "the underlying geometry in the scenegraph.\n"
208 "If no geometry was found 'None' is returned, instead.\n"
209 );
210 add_varargs_method(
211 "getPoint",
212 &View3DInventorPy::getPointOnFocalPlane,
213 "Same as getPointOnFocalPlane"
214 );
215 add_varargs_method(
216 "getPointOnFocalPlane",
217 &View3DInventorPy::getPointOnFocalPlane,
218 "getPointOnFocalPlane(pixel coords (as integer)) -> 3D vector\n"
219 "\n"
220 "Return the according 3D point on the focal plane to the given 2D point (in\n"
221 "pixel coordinates).\n"
222 );
223 add_varargs_method(
224 "getPointOnScreen",
225 &View3DInventorPy::getPointOnViewport,
226 "Same as getPointOnViewport"
227 );
228 add_varargs_method(
229 "getPointOnViewport",
230 &View3DInventorPy::getPointOnViewport,
231 "getPointOnViewport(3D vector) -> pixel coords (as integer)\n"
232 "\n"
233 "Return the projected 3D point (in pixel coordinates).\n"
234 );
235 add_varargs_method(
236 "projectPointToLine",
237 &View3DInventorPy::projectPointToLine,
238 "projectPointToLine(pixel coords (as integer)) -> line defined by two points\n"
239 "\n"
240 "Return the projecting 3D line to the given 2D point"
241 );
242 add_varargs_method("addEventCallback", &View3DInventorPy::addEventCallback, "addEventCallback()");
243 add_varargs_method(
244 "removeEventCallback",
245 &View3DInventorPy::removeEventCallback,
246 "removeEventCallback()"
247 );
248 add_varargs_method("setAnnotation", &View3DInventorPy::setAnnotation, "setAnnotation()");
249 add_varargs_method("removeAnnotation", &View3DInventorPy::removeAnnotation, "removeAnnotation()");
250 add_noargs_method("getSceneGraph", &View3DInventorPy::getSceneGraph, "getSceneGraph()");
251 add_noargs_method("getViewer", &View3DInventorPy::getViewer, "getViewer()");
252 add_varargs_method(
253 "addEventCallbackPivy",
254 &View3DInventorPy::addEventCallbackPivy,
255 "addEventCallbackPivy()"
256 );
257 add_varargs_method(
258 "removeEventCallbackPivy",
259 &View3DInventorPy::removeEventCallbackPivy,
260 "removeEventCallbackPivy()"
261 );
262 add_varargs_method(
263 "addEventCallbackSWIG",
264 &View3DInventorPy::addEventCallbackPivy,
265 "Deprecated -- use addEventCallbackPivy()"
266 );
267 add_varargs_method(
268 "removeEventCallbackSWIG",
269 &View3DInventorPy::removeEventCallbackPivy,
270 "Deprecated -- use removeEventCallbackPivy()"
271 );
272 add_noargs_method(
273 "listNavigationTypes",
274 &View3DInventorPy::listNavigationTypes,
275 "listNavigationTypes()"
276 );
277 add_noargs_method("getNavigationType", &View3DInventorPy::getNavigationType, "getNavigationType()");
278 add_varargs_method("setNavigationType", &View3DInventorPy::setNavigationType, "setNavigationType()");
279 add_varargs_method(
280 "setAxisCross",
281 &View3DInventorPy::setAxisCross,
282 "switch the big axis-cross on and off"
283 );
284 add_noargs_method(
285 "hasAxisCross",
286 &View3DInventorPy::hasAxisCross,
287 "check if the big axis-cross is on or off()"
288 );
289 add_varargs_method(
290 "addDraggerCallback",
291 &View3DInventorPy::addDraggerCallback,
292 "addDraggerCallback(SoDragger, String CallbackType, function)\n"
293 "Add a DraggerCalback function to the coin node\n"
294 "Possibles types :\n"
295 "'addFinishCallback','addStartCallback','addMotionCallback','addValueChangedCallback'\n"
296 );
297 add_varargs_method(
298 "removeDraggerCallback",
299 &View3DInventorPy::removeDraggerCallback,
300 "removeDraggerCallback(SoDragger, String CallbackType, function)\n"
301 "Remove the DraggerCalback function from the coin node\n"
302 "Possibles types :\n"
303 "'addFinishCallback','addStartCallback','addMotionCallback','addValueChangedCallback'\n"
304 );
305 add_varargs_method(
306 "getViewProvidersOfType",
307 &View3DInventorPy::getViewProvidersOfType,
308 "getViewProvidersOfType(name)\nreturns a list of view providers for the given type"
309 );
310 add_noargs_method(
311 "redraw",
312 &View3DInventorPy::redraw,
313 "redraw(): renders the scene on screen (useful for animations)"
314 );
315 add_varargs_method(
316 "setName",
317 &View3DInventorPy::setName,
318 "setName(str): sets a name to this viewer\nThe name sets the widget's windowTitle and "
319 "appears on the viewer tab"
320 );
321 add_keyword_method(
322 "toggleClippingPlane",
323 &View3DInventorPy::toggleClippingPlane,
324 "toggleClippingPlane(toggle=-1, beforeEditing=False, noManip=True, pla=App.Placement()\n"
325 "Toggle a global clipping plane\n\n"
326 "toggle: -1 toggle, 1 show, 0 hide\n"
327 "beforeEditing: whether to insert the clipping node before or after editing root node\n"
328 "noManip: whether to create a manipulator\n"
329 "pla: clipping plane placement"
330 );
331 add_noargs_method(
332 "hasClippingPlane",
333 &View3DInventorPy::hasClippingPlane,
334 "hasClippingPlane(): check whether this clipping plane is active"
335 );
336 add_noargs_method(
337 "graphicsView",
338 &View3DInventorPy::graphicsView,
339 "graphicsView(): Access this view as QGraphicsView"
340 );
341 add_varargs_method(
342 "setCornerCrossVisible",
343 &View3DInventorPy::setCornerCrossVisible,
344 "setCornerCrossVisible(bool): Defines corner axis cross visibility"
345 );
346 add_noargs_method(
347 "isCornerCrossVisible",
348 &View3DInventorPy::isCornerCrossVisible,
349 "isCornerCrossVisible(): Returns current corner axis cross visibility"
350 );
351 add_varargs_method(
352 "setCornerCrossSize",
353 &View3DInventorPy::setCornerCrossSize,
354 "setCornerCrossSize(int): Defines corner axis cross size"
355 );
356 add_noargs_method(
357 "getCornerCrossSize",
358 &View3DInventorPy::getCornerCrossSize,
359 "getCornerCrossSize(): Returns current corner axis cross size"
360 );
361 add_noargs_method(
362 "cast_to_base",
363 &View3DInventorPy::cast_to_base,
364 "cast_to_base() cast to MDIView class"
365 );
366 }
367
368 View3DInventorPy::View3DInventorPy(View3DInventor* vi)
369 : base(vi)
370 {}
371
372 View3DInventorPy::~View3DInventorPy()
373 {
374 Base::PyGILStateLocker lock;
375 for (auto it : callbacks) {
376 Py_DECREF(it);
377 }
378 }
379
380 View3DInventor* View3DInventorPy::getView3DInventorPtr()
381 {
382 return qobject_cast<View3DInventor*>(base.getMDIViewPtr());
383 }
384
385 Py::Object View3DInventorPy::repr()
386 {
387 if (!getView3DInventorPtr()) {
388 throw Py::RuntimeError("Cannot print representation of deleted object");
389 }
390
391 return Py::String("View3DInventor");
392 }
393
394 View3DInventorPy::method_varargs_handler View3DInventorPy::pycxx_handler = nullptr;
395
396 PyObject* View3DInventorPy::method_varargs_ext_handler(PyObject* _self_and_name_tuple, PyObject* _args)
397 {
398 try {
399 return pycxx_handler(_self_and_name_tuple, _args);
400 }
401 catch (const Base::Exception& e) {
402 throw Py::RuntimeError(e.what());
403 }
404 catch (const std::exception& e) {
405 throw Py::RuntimeError(e.what());
406 }
407 catch (const Py::Exception&) {
408 throw;
409 }
410 catch (...) {
411 throw Py::RuntimeError("Unknown C++ exception");
412 }
413 }
414
415 // Since with PyCXX it's not possible to make a sub-class of MDIViewPy
416 // a trick is to use MDIViewPy as class member and override getattr() to
417 // join the attributes of both classes. This way all methods of MDIViewPy
418 // appear for SheetViewPy, too.
419 Py::Object View3DInventorPy::getattribute(const char* attr)
420 {
421 if (!getView3DInventorPtr()) {
422 throw Py::RuntimeError("Cannot print representation of deleted object");
423 }
424 std::string name(attr);
425 if (name == "__dict__" || name == "__class__") {
426 Py::Dict dict_self(BaseType::getattr("__dict__"));
427 Py::Dict dict_base(base.getattr("__dict__"));
428 for (const auto& it : dict_base) {
429 dict_self.setItem(it.first, it.second);
430 }
431 return dict_self;
432 }
433
434 try {
435 return BaseType::getattr(attr);
436 }
437 catch (Py::AttributeError& e) {
438 e.clear();
439 return base.getattr(attr);
440 }
441 }
442
443 Py::Object View3DInventorPy::getattr(const char* attr)
444 {
445 if (!getView3DInventorPtr()) {
446 std::ostringstream s_out;
447 s_out << "Cannot access attribute '" << attr << "' of deleted object";
448 throw Py::RuntimeError(s_out.str());
449 }
450 else {
451 // see if an active object has the same name
452 App::DocumentObject* docObj = getView3DInventorPtr()->getActiveObject<App::DocumentObject*>(
453 attr
454 );
455 if (docObj) {
456 return Py::Object(docObj->getPyObject(), true);
457 }
458 else {
459 // else looking for a method with the name and call it
460 Py::Object obj = getattribute(attr);
461 if (PyCFunction_Check(obj.ptr())) {
462 auto op = reinterpret_cast<PyCFunctionObject*>(obj.ptr());
463 if (op->m_ml->ml_flags == METH_VARARGS) {
464 if (!pycxx_handler) {
465 pycxx_handler = op->m_ml->ml_meth;
466 }
467 op->m_ml->ml_meth = method_varargs_ext_handler;
468 }
469 }
470 return obj;
471 }
472 }
473 }
474
475 int View3DInventorPy::setattr(const char* attr, const Py::Object& value)
476 {
477 if (!getView3DInventorPtr()) {
478 std::string s;
479 std::ostringstream s_out;
480 s_out << "Cannot access attribute '" << attr << "' of deleted object";
481 throw Py::RuntimeError(s_out.str());
482 }
483 else {
484 return BaseType::setattr(attr, value);
485 }
486 }
487
488 Py::Object View3DInventorPy::fitAll(const Py::Tuple& args)
489 {
490 double factor = 1.0;
491 if (!PyArg_ParseTuple(args.ptr(), "|d", &factor)) {
492 throw Py::Exception();
493 }
494
495 try {
496 getView3DInventorPtr()->getViewer()->viewAll((float)factor);
497 }
498 catch (const Base::Exception& e) {
499 throw Py::RuntimeError(e.what());
500 }
501 catch (const std::exception& e) {
502 throw Py::RuntimeError(e.what());
503 }
504 catch (...) {
505 throw Py::RuntimeError("Unknown C++ exception");
506 }
507 return Py::None();
508 }
509
510 Py::Object View3DInventorPy::boxZoom(const Py::Tuple& args, const Py::Dict& kwds)
511 {
512 static const std::array<const char*, 5> kwds_box {"XMin", "YMin", "XMax", "YMax", nullptr};
513 short xmin, ymin, xmax, ymax;
514 if (!Base::Wrapped_ParseTupleAndKeywords(
515 args.ptr(),
516 kwds.ptr(),
517 "hhhh",
518 kwds_box,
519 &xmin,
520 &ymin,
521 &xmax,
522 &ymax
523 )) {
524 throw Py::Exception();
525 }
526
527 SbBox2s box(xmin, ymin, xmax, ymax);
528 getView3DInventorPtr()->getViewer()->boxZoom(box);
529 return Py::None();
530 }
531
532 Py::Object View3DInventorPy::viewBottom()
533 {
534 try {
535 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Bottom));
536 }
537 catch (const Base::Exception& e) {
538 throw Py::RuntimeError(e.what());
539 }
540 catch (const std::exception& e) {
541 throw Py::RuntimeError(e.what());
542 }
543 catch (...) {
544 throw Py::RuntimeError("Unknown C++ exception");
545 }
546
547 return Py::None();
548 }
549
550 Py::Object View3DInventorPy::viewFront()
551 {
552 try {
553 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Front));
554 }
555 catch (const Base::Exception& e) {
556 throw Py::RuntimeError(e.what());
557 }
558 catch (const std::exception& e) {
559 throw Py::RuntimeError(e.what());
560 }
561 catch (...) {
562 throw Py::RuntimeError("Unknown C++ exception");
563 }
564
565 return Py::None();
566 }
567
568 Py::Object View3DInventorPy::viewLeft()
569 {
570 try {
571 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Left));
572 }
573 catch (const Base::Exception& e) {
574 throw Py::RuntimeError(e.what());
575 }
576 catch (const std::exception& e) {
577 throw Py::RuntimeError(e.what());
578 }
579 catch (...) {
580 throw Py::RuntimeError("Unknown C++ exception");
581 }
582
583 return Py::None();
584 }
585
586 Py::Object View3DInventorPy::viewRear()
587 {
588 try {
589 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Rear));
590 }
591 catch (const Base::Exception& e) {
592 throw Py::RuntimeError(e.what());
593 }
594 catch (const std::exception& e) {
595 throw Py::RuntimeError(e.what());
596 }
597 catch (...) {
598 throw Py::RuntimeError("Unknown C++ exception");
599 }
600
601 return Py::None();
602 }
603
604 Py::Object View3DInventorPy::viewRight()
605 {
606 try {
607 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Right));
608 }
609 catch (const Base::Exception& e) {
610 throw Py::RuntimeError(e.what());
611 }
612 catch (const std::exception& e) {
613 throw Py::RuntimeError(e.what());
614 }
615 catch (...) {
616 throw Py::RuntimeError("Unknown C++ exception");
617 }
618
619 return Py::None();
620 }
621
622 Py::Object View3DInventorPy::viewTop()
623 {
624 try {
625 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Top));
626 }
627 catch (const Base::Exception& e) {
628 throw Py::RuntimeError(e.what());
629 }
630 catch (const std::exception& e) {
631 throw Py::RuntimeError(e.what());
632 }
633 catch (...) {
634 throw Py::RuntimeError("Unknown C++ exception");
635 }
636
637 return Py::None();
638 }
639
640 Py::Object View3DInventorPy::viewIsometric()
641 {
642 try {
643 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Isometric));
644 }
645 catch (const Base::Exception& e) {
646 throw Py::RuntimeError(e.what());
647 }
648 catch (const std::exception& e) {
649 throw Py::RuntimeError(e.what());
650 }
651 catch (...) {
652 throw Py::RuntimeError("Unknown C++ exception");
653 }
654
655 return Py::None();
656 }
657
658 Py::Object View3DInventorPy::viewDimetric()
659 {
660 try {
661 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Dimetric));
662 }
663 catch (const Base::Exception& e) {
664 throw Py::RuntimeError(e.what());
665 }
666 catch (const std::exception& e) {
667 throw Py::RuntimeError(e.what());
668 }
669 catch (...) {
670 throw Py::RuntimeError("Unknown C++ exception");
671 }
672
673 return Py::None();
674 }
675
676 Py::Object View3DInventorPy::viewTrimetric()
677 {
678 try {
679 getView3DInventorPtr()->getViewer()->setCameraOrientation(Camera::rotation(Camera::Trimetric));
680 }
681 catch (const Base::Exception& e) {
682 throw Py::RuntimeError(e.what());
683 }
684 catch (const std::exception& e) {
685 throw Py::RuntimeError(e.what());
686 }
687 catch (...) {
688 throw Py::RuntimeError("Unknown C++ exception");
689 }
690
691 return Py::None();
692 }
693
694 Py::Object View3DInventorPy::viewDefaultOrientation(const Py::Tuple& args)
695 {
696 char* view = nullptr;
697 double scale = -1.0;
698 if (!PyArg_ParseTuple(args.ptr(), "|zd", &view, &scale)) {
699 throw Py::Exception();
700 }
701
702 try {
703 std::string newDocView;
704 SbRotation rot(0, 0, 0, 1);
705 if (view) {
706 newDocView = view;
707 }
708 else {
709 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
710 "User parameter:BaseApp/Preferences/View"
711 );
712 newDocView = hGrp->GetASCII("NewDocumentCameraOrientation", "Trimetric");
713 }
714
715 if (newDocView == "Top") {
716 rot = Camera::rotation(Camera::Top);
717 }
718 else if (newDocView == "Bottom") {
719 rot = Camera::rotation(Camera::Bottom);
720 }
721 else if (newDocView == "Front") {
722 rot = Camera::rotation(Camera::Front);
723 }
724 else if (newDocView == "Rear") {
725 rot = Camera::rotation(Camera::Rear);
726 }
727 else if (newDocView == "Left") {
728 rot = Camera::rotation(Camera::Left);
729 }
730 else if (newDocView == "Right") {
731 rot = Camera::rotation(Camera::Right);
732 }
733 else if (newDocView == "Isometric") {
734 rot = Camera::rotation(Camera::Isometric);
735 }
736 else if (newDocView == "Dimetric") {
737 rot = Camera::rotation(Camera::Dimetric);
738 }
739 else if (newDocView == "Trimetric") {
740 rot = Camera::rotation(Camera::Trimetric);
741 }
742 else if (newDocView == "Custom") {
743 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
744 "User parameter:BaseApp/Preferences/View/Custom"
745 );
746 auto q0 = static_cast<float>(hGrp->GetFloat("Q0", 0));
747 auto q1 = static_cast<float>(hGrp->GetFloat("Q1", 0));
748 auto q2 = static_cast<float>(hGrp->GetFloat("Q2", 0));
749 auto q3 = static_cast<float>(hGrp->GetFloat("Q3", 1));
750 rot.setValue(q0, q1, q2, q3);
751 }
752
753 SoCamera* cam = getView3DInventorPtr()->getViewer()->getCamera();
754 cam->orientation = rot;
755
756 if (scale < 0.0) {
757 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
758 "User parameter:BaseApp/Preferences/View"
759 );
760 scale = hGrp->GetFloat("NewDocumentCameraScale", 100.0);
761 }
762
763 setDefaultCameraHeight(scale);
764 }
765 catch (const Base::Exception& e) {
766 throw Py::RuntimeError(e.what());
767 }
768 catch (const std::exception& e) {
769 throw Py::RuntimeError(e.what());
770 }
771 catch (...) {
772 throw Py::RuntimeError("Unknown C++ exception");
773 }
774
775 return Py::None();
776 }
777
778 void View3DInventorPy::setDefaultCameraHeight(float scale)
779 {
780 if (scale > 1e-7) {
781 SoCamera* cam = getView3DInventorPtr()->getViewer()->getCamera();
782 SbRotation rot = cam->orientation.getValue();
783
784 double f = 0.0; // focal dist
785 if (cam->isOfType(SoOrthographicCamera::getClassTypeId())) {
786 static_cast<SoOrthographicCamera*>(cam)->height = scale;
787 f = scale;
788 }
789 else if (cam->isOfType(SoPerspectiveCamera::getClassTypeId())) {
790 // nothing to do
791 double ang = static_cast<SoPerspectiveCamera*>(cam)->heightAngle.getValue();
792 f = 0.5 * scale / sin(ang * 0.5);
793 }
794
795 SbVec3f lookDir;
796 rot.multVec(SbVec3f(0, 0, -1), lookDir);
797 SbVec3f pos = lookDir * -f;
798 cam->focalDistance = f;
799 cam->position = pos;
800 }
801 }
802
803 Py::Object View3DInventorPy::viewRotateLeft()
804 {
805 try {
806 SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera();
807 SbRotation rot = cam->orientation.getValue();
808 SbVec3f vdir(0, 0, -1);
809 rot.multVec(vdir, vdir);
810 SbRotation nrot(vdir, (float)std::numbers::pi / 2);
811 cam->orientation.setValue(rot * nrot);
812 }
813 catch (const Base::Exception& e) {
814 throw Py::RuntimeError(e.what());
815 }
816 catch (const std::exception& e) {
817 throw Py::RuntimeError(e.what());
818 }
819 catch (...) {
820 throw Py::RuntimeError("Unknown C++ exception");
821 }
822
823 return Py::None();
824 }
825
826 Py::Object View3DInventorPy::viewRotateRight()
827 {
828 try {
829 SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera();
830 SbRotation rot = cam->orientation.getValue();
831 SbVec3f vdir(0, 0, -1);
832 rot.multVec(vdir, vdir);
833 SbRotation nrot(vdir, (float)-std::numbers::pi / 2);
834 cam->orientation.setValue(rot * nrot);
835 }
836 catch (const Base::Exception& e) {
837 throw Py::RuntimeError(e.what());
838 }
839 catch (const std::exception& e) {
840 throw Py::RuntimeError(e.what());
841 }
842 catch (...) {
843 throw Py::RuntimeError("Unknown C++ exception");
844 }
845
846 return Py::None();
847 }
848
849 Py::Object View3DInventorPy::zoomIn()
850 {
851 try {
852 getView3DInventorPtr()->getViewer()->navigationStyle()->zoomIn();
853 }
854 catch (const Base::Exception& e) {
855 throw Py::RuntimeError(e.what());
856 }
857 catch (const std::exception& e) {
858 throw Py::RuntimeError(e.what());
859 }
860 catch (...) {
861 throw Py::RuntimeError("Unknown C++ exception");
862 }
863
864 return Py::None();
865 }
866
867 Py::Object View3DInventorPy::zoomOut()
868 {
869 try {
870 getView3DInventorPtr()->getViewer()->navigationStyle()->zoomOut();
871 }
872 catch (const Base::Exception& e) {
873 throw Py::RuntimeError(e.what());
874 }
875 catch (const std::exception& e) {
876 throw Py::RuntimeError(e.what());
877 }
878 catch (...) {
879 throw Py::RuntimeError("Unknown C++ exception");
880 }
881
882 return Py::None();
883 }
884
885 Py::Object View3DInventorPy::setCameraOrientation(const Py::Tuple& args)
886 {
887 PyObject* o;
888 PyObject* m = Py_False;
889 if (!PyArg_ParseTuple(args.ptr(), "O|O!", &o, &PyBool_Type, &m)) {
890 throw Py::Exception();
891 }
892
893 try {
894 if (PyTuple_Check(o)) {
895 Py::Tuple tuple(o);
896 float q0 = (float)Py::Float(tuple[0]);
897 float q1 = (float)Py::Float(tuple[1]);
898 float q2 = (float)Py::Float(tuple[2]);
899 float q3 = (float)Py::Float(tuple[3]);
900 getView3DInventorPtr()->getViewer()->setCameraOrientation(
901 SbRotation(q0, q1, q2, q3),
902 Base::asBoolean(m)
903 );
904 }
905 else if (PyObject_TypeCheck(o, &Base::RotationPy::Type)) {
906 Base::Rotation r = static_cast<Base::Rotation>(Py::Rotation(o, false));
907 double q0, q1, q2, q3;
908 r.getValue(q0, q1, q2, q3);
909 getView3DInventorPtr()->getViewer()->setCameraOrientation(
910 SbRotation((float)q0, (float)q1, (float)q2, (float)q3),
911 Base::asBoolean(m)
912 );
913 }
914 else {
915 throw Py::ValueError("Neither tuple nor rotation object");
916 }
917 }
918 catch (const Py::Exception&) {
919 throw; // re-throw
920 }
921 catch (const Base::Exception& e) {
922 throw Py::RuntimeError(e.what());
923 }
924 catch (const std::exception& e) {
925 throw Py::RuntimeError(e.what());
926 }
927 catch (...) {
928 throw Py::RuntimeError("Unknown C++ exception");
929 }
930
931 return Py::None();
932 }
933
934 Py::Object View3DInventorPy::getCameraOrientation()
935 {
936 SbRotation rot = getView3DInventorPtr()->getViewer()->getCameraOrientation();
937 float q0, q1, q2, q3;
938 rot.getValue(q0, q1, q2, q3);
939 return Py::Rotation(Base::Rotation(q0, q1, q2, q3));
940 }
941
942 Py::Object View3DInventorPy::viewPosition(const Py::Tuple& args)
943 {
944 PyObject* p = nullptr;
945 int steps; // Unused but kept as parameter to not break the Python interface
946 int duration = -1; // Duration in ms, will be replaced with User
947 // parameter:BaseApp/Preferences/View/AnimationDuration when not explicitly
948 // provided
949 if (!PyArg_ParseTuple(args.ptr(), "|O!ii", &Base::PlacementPy::Type, &p, &steps, &duration)) {
950 throw Py::Exception();
951 }
952
953 if (p) {
954 Base::Placement* plm = static_cast<Base::PlacementPy*>(p)->getPlacementPtr();
955 Base::Rotation rot = plm->getRotation();
956 Base::Vector3d pos = plm->getPosition();
957 double q0, q1, q2, q3;
958 rot.getValue(q0, q1, q2, q3);
959 getView3DInventorPtr()->getViewer()->moveCameraTo(
960 SbRotation((float)q0, (float)q1, (float)q2, (float)q3),
961 SbVec3f((float)pos.x, (float)pos.y, (float)pos.z),
962 duration
963 );
964 }
965
966 SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera();
967 if (!cam) {
968 return Py::None();
969 }
970
971 SbRotation rot = cam->orientation.getValue();
972 SbVec3f pos = cam->position.getValue();
973 float q0, q1, q2, q3;
974 rot.getValue(q0, q1, q2, q3);
975 Base::Placement plm(Base::Vector3d(pos[0], pos[1], pos[2]), Base::Rotation(q0, q1, q2, q3));
976 return Py::Placement(plm);
977 }
978
979 Py::Object View3DInventorPy::startAnimating(const Py::Tuple& args)
980 {
981 float x, y, z;
982 float velocity;
983 if (!PyArg_ParseTuple(args.ptr(), "ffff", &x, &y, &z, &velocity)) {
984 throw Py::Exception();
985 }
986 getView3DInventorPtr()->getViewer()->startSpinningAnimation(SbVec3f(x, y, z), velocity);
987 return Py::None();
988 }
989
990 Py::Object View3DInventorPy::stopAnimating()
991 {
992 getView3DInventorPtr()->getViewer()->stopAnimating();
993 return Py::None();
994 }
995
996 Py::Object View3DInventorPy::setAnimationEnabled(const Py::Tuple& args)
997 {
998 int ok;
999 if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) {
1000 throw Py::Exception();
1001 }
1002 getView3DInventorPtr()->getViewer()->setAnimationEnabled(ok != 0);
1003 return Py::None();
1004 }
1005
1006 Py::Object View3DInventorPy::isAnimationEnabled()
1007 {
1008 SbBool ok = getView3DInventorPtr()->getViewer()->isAnimationEnabled();
1009 return Py::Boolean(ok ? true : false);
1010 }
1011
1012 Py::Object View3DInventorPy::setPopupMenuEnabled(const Py::Tuple& args)
1013 {
1014 int ok;
1015 if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) {
1016 throw Py::Exception();
1017 }
1018 getView3DInventorPtr()->getViewer()->setPopupMenuEnabled(ok != 0);
1019 return Py::None();
1020 }
1021
1022 Py::Object View3DInventorPy::isPopupMenuEnabled()
1023 {
1024 SbBool ok = getView3DInventorPtr()->getViewer()->isPopupMenuEnabled();
1025 return Py::Boolean(ok ? true : false);
1026 }
1027
1028 Py::Object View3DInventorPy::saveImage(const Py::Tuple& args)
1029 {
1030 char* cFileName = nullptr;
1031 const char* cColor = "Current";
1032 const char* cComment = "$MIBA";
1033 int w = -1, h = -1;
1034 int s = View3DInventorViewer::getNumSamples();
1035
1036 if (!PyArg_ParseTuple(args.ptr(), "et|iissi", "utf-8", &cFileName, &w, &h, &cColor, &cComment, &s)) {
1037 throw Py::Exception();
1038 }
1039
1040 std::string encodedName = std::string(cFileName);
1041 PyMem_Free(cFileName);
1042 QFileInfo fi(QString::fromUtf8(encodedName.c_str()));
1043
1044 if (!fi.absoluteDir().exists()) {
1045 throw Py::RuntimeError("Directory where to save image doesn't exist");
1046 }
1047
1048 QColor bg;
1049 QString colname = QString::fromLatin1(cColor);
1050 if (colname.compare(QLatin1String("Current"), Qt::CaseInsensitive) == 0) {
1051 bg = QColor(); // assign an invalid color here
1052 }
1053 else {
1054 bg = QColor(colname);
1055 }
1056
1057 QImage img;
1058 getView3DInventorPtr()->getViewer()->savePicture(w, h, s, bg, img);
1059
1060 SoFCOffscreenRenderer& renderer = SoFCOffscreenRenderer::instance();
1061 SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera();
1062 renderer.writeToImageFile(encodedName.c_str(), cComment, cam->getViewVolume().getMatrix(), img);
1063
1064 return Py::None();
1065 }
1066
1067 Py::Object View3DInventorPy::saveVectorGraphic(const Py::Tuple& args)
1068 {
1069 char* filename;
1070 int ps = 4;
1071 const char* name = "white";
1072
1073 if (!PyArg_ParseTuple(args.ptr(), "s|is", &filename, &ps, &name)) {
1074 throw Py::Exception();
1075 }
1076
1077 std::unique_ptr<SoVectorizeAction> vo;
1078 Base::FileInfo fi(filename);
1079 if (fi.hasExtension({"ps", "eps"})) {
1080 vo = std::unique_ptr<SoVectorizeAction>(new SoVectorizePSAction());
1081 // vo->setGouraudThreshold(0.0f);
1082 }
1083 else if (fi.hasExtension("svg")) {
1084 vo = std::unique_ptr<SoVectorizeAction>(new SoFCVectorizeSVGAction());
1085 }
1086 else if (fi.hasExtension("idtf")) {
1087 vo = std::unique_ptr<SoVectorizeAction>(new SoFCVectorizeU3DAction());
1088 }
1089 else {
1090 throw Py::RuntimeError("Not supported vector graphic");
1091 }
1092
1093 SoVectorOutput* out = vo->getOutput();
1094 if (!out || !out->openFile(filename)) {
1095 std::ostringstream a_out;
1096 a_out << "Cannot open file '" << filename << "'";
1097 throw Py::RuntimeError(a_out.str());
1098 }
1099
1100 QColor bg;
1101 QString colname = QString::fromLatin1(name);
1102 if (colname.compare(QLatin1String("Current"), Qt::CaseInsensitive) == 0) {
1103 bg = getView3DInventorPtr()->getViewer()->backgroundColor();
1104 }
1105 else {
1106 bg = QColor(colname);
1107 }
1108
1109 getView3DInventorPtr()->getViewer()->saveGraphic(ps, bg, vo.get());
1110 out->closeFile();
1111 return Py::None();
1112 }
1113
1114 Py::Object View3DInventorPy::getCameraNode()
1115 {
1116 try {
1117 SoNode* camera = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera();
1118 PyObject* proxy = nullptr;
1119 std::string type;
1120 type = "So"; // seems that So prefix is missing in camera node
1121 type += camera->getTypeId().getName().getString();
1122 type += " *";
1123 proxy = Base::Interpreter()
1124 .createSWIGPointerObj("pivy.coin", type.c_str(), static_cast<void*>(camera), 1);
1125 camera->ref();
1126 return Py::Object(proxy, true);
1127 }
1128 catch (const Base::Exception& e) {
1129 throw Py::RuntimeError(e.what());
1130 }
1131 }
1132
1133 Py::Object View3DInventorPy::getCamera()
1134 {
1135 SoOutput out;
1136 char buffer[512];
1137 out.setBuffer(buffer, 512, nullptr);
1138
1139 try {
1140 SoWriteAction wa(&out);
1141 SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera();
1142 if (cam) {
1143 wa.apply(cam);
1144 }
1145 else {
1146 buffer[0] = '\0';
1147 }
1148 return Py::String(buffer);
1149 }
1150 catch (const Base::Exception& e) {
1151 throw Py::RuntimeError(e.what());
1152 }
1153 catch (const std::exception& e) {
1154 throw Py::RuntimeError(e.what());
1155 }
1156 catch (...) {
1157 throw Py::RuntimeError("Unknown C++ exception");
1158 }
1159 }
1160
1161 Py::Object View3DInventorPy::getViewDirection()
1162 {
1163 try {
1164 SbVec3f dvec = getView3DInventorPtr()->getViewer()->getViewDirection();
1165 return Py::Vector(Base::Vector3f(dvec[0], dvec[1], dvec[2]));
1166 }
1167 catch (const Base::Exception& e) {
1168 throw Py::RuntimeError(e.what());
1169 }
1170 catch (const std::exception& e) {
1171 throw Py::RuntimeError(e.what());
1172 }
1173 catch (...) {
1174 throw Py::RuntimeError("Unknown C++ exception");
1175 }
1176 }
1177
1178
1179 Py::Object View3DInventorPy::getUpDirection()
1180 {
1181 try {
1182 SbVec3f dvec = getView3DInventorPtr()->getViewer()->getUpDirection();
1183 return Py::Vector(Base::Vector3f(dvec[0], dvec[1], dvec[2]));
1184 }
1185 catch (const Base::Exception& e) {
1186 throw Py::RuntimeError(e.what());
1187 }
1188 catch (const std::exception& e) {
1189 throw Py::RuntimeError(e.what());
1190 }
1191 catch (...) {
1192 throw Py::RuntimeError("Unknown C++ exception");
1193 }
1194 }
1195
1196 Py::Object View3DInventorPy::setViewDirection(const Py::Tuple& args)
1197 {
1198 PyObject* object;
1199 if (!PyArg_ParseTuple(args.ptr(), "O", &object)) {
1200 throw Py::Exception();
1201 }
1202
1203 try {
1204 if (PyTuple_Check(object)) {
1205 Py::Tuple tuple(object);
1206 Py::Float x(tuple.getItem(0));
1207 Py::Float y(tuple.getItem(1));
1208 Py::Float z(tuple.getItem(2));
1209 SbVec3f dir;
1210 dir.setValue((float)x, (float)y, (float)z);
1211 if (dir.length() < 0.001f) {
1212 throw Py::ValueError("Null vector cannot be used to set direction");
1213 }
1214 getView3DInventorPtr()->getViewer()->setViewDirection(dir);
1215 return Py::None();
1216 }
1217 }
1218 catch (const Py::Exception&) {
1219 throw; // re-throw
1220 }
1221 catch (const Base::Exception& e) {
1222 throw Py::RuntimeError(e.what());
1223 }
1224 catch (const std::exception& e) {
1225 throw Py::RuntimeError(e.what());
1226 }
1227 catch (...) {
1228 throw Py::RuntimeError("Unknown C++ exception");
1229 }
1230
1231 return Py::None();
1232 }
1233
1234
1235 Py::Object View3DInventorPy::setCamera(const Py::Tuple& args)
1236 {
1237 char* buffer;
1238 if (!PyArg_ParseTuple(args.ptr(), "s", &buffer)) {
1239 throw Py::Exception();
1240 }
1241
1242 try {
1243 getView3DInventorPtr()->setCamera(buffer);
1244 return Py::None();
1245 }
1246 catch (const Base::Exception& e) {
1247 throw Py::RuntimeError(e.what());
1248 }
1249 catch (const std::exception& e) {
1250 throw Py::RuntimeError(e.what());
1251 }
1252 catch (...) {
1253 throw Py::RuntimeError("Unknown C++ exception");
1254 }
1255 }
1256
1257 // FIXME: Once View3DInventor inherits from PropertyContainer we can use PropertyEnumeration.
1258 const char* CameraTypeEnums[] = {"Orthographic", "Perspective", nullptr};
1259
1260 Py::Object View3DInventorPy::getCameraType()
1261 {
1262 SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera();
1263 if (!cam) {
1264 throw Py::RuntimeError("No camera set!");
1265 }
1266 else if (cam->getTypeId() == SoOrthographicCamera::getClassTypeId()) {
1267 return Py::String(CameraTypeEnums[0]);
1268 }
1269 else if (cam->getTypeId() == SoPerspectiveCamera::getClassTypeId()) {
1270 return Py::String(CameraTypeEnums[1]);
1271 }
1272 else {
1273 throw Py::TypeError("Unknown camera type");
1274 }
1275 }
1276
1277 Py::Object View3DInventorPy::setCameraType(const Py::Tuple& args)
1278 {
1279 int cameratype = -1;
1280 if (!PyArg_ParseTuple(args.ptr(), "i", &cameratype)) {
1281 char* modename;
1282 PyErr_Clear();
1283 if (!PyArg_ParseTuple(args.ptr(), "s", &modename)) {
1284 throw Py::Exception();
1285 }
1286 for (int i = 0; i < 2; i++) {
1287 if (strncmp(CameraTypeEnums[i], modename, 20) == 0) {
1288 cameratype = i;
1289 break;
1290 }
1291 }
1292
1293 if (cameratype < 0) {
1294 std::string s;
1295 std::ostringstream s_out;
1296 s_out << "Unknown camera type '" << modename << "'";
1297 throw Py::NameError(s_out.str());
1298 }
1299 }
1300
1301 if (cameratype < 0 || cameratype > 1) {
1302 throw Py::IndexError("Out of range");
1303 }
1304 if (cameratype == 0) {
1305 getView3DInventorPtr()->getViewer()->setCameraType(SoOrthographicCamera::getClassTypeId());
1306 }
1307 else {
1308 getView3DInventorPtr()->getViewer()->setCameraType(SoPerspectiveCamera::getClassTypeId());
1309 }
1310 return Py::None();
1311 }
1312
1313 Py::Object View3DInventorPy::listCameraTypes()
1314 {
1315 try {
1316 Py::List list(2);
1317 for (int i = 0; i < 2; i++) {
1318 list[i] = Py::String(CameraTypeEnums[i]);
1319 }
1320 return list;
1321 }
1322 catch (const Base::Exception& e) {
1323 throw Py::RuntimeError(e.what());
1324 }
1325 catch (const std::exception& e) {
1326 throw Py::RuntimeError(e.what());
1327 }
1328 catch (...) {
1329 throw Py::RuntimeError("Unknown C++ exception");
1330 }
1331 }
1332
1333 Py::Object View3DInventorPy::dump(const Py::Tuple& args)
1334 {
1335 char* filename;
1336 PyObject* onlyVisible = Py_False;
1337 if (!PyArg_ParseTuple(args.ptr(), "s|O!", &filename, &PyBool_Type, &onlyVisible)) {
1338 throw Py::Exception();
1339 }
1340
1341 try {
1342 getView3DInventorPtr()->dump(filename, Base::asBoolean(onlyVisible));
1343 return Py::None();
1344 }
1345 catch (const Base::Exception& e) {
1346 throw Py::RuntimeError(e.what());
1347 }
1348 catch (const std::exception& e) {
1349 throw Py::RuntimeError(e.what());
1350 }
1351 catch (...) {
1352 throw Py::RuntimeError("Unknown C++ exception");
1353 }
1354 }
1355
1356 Py::Object View3DInventorPy::dumpNode(const Py::Tuple& args)
1357 {
1358 PyObject* object;
1359 if (!PyArg_ParseTuple(args.ptr(), "O", &object)) {
1360 throw Py::Exception();
1361 }
1362
1363 void* ptr = nullptr;
1364 try {
1365 Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoNode *", object, &ptr, 0);
1366 if (!ptr) {
1367 throw Py::RuntimeError("Conversion of SoNode failed");
1368 }
1369 }
1370 catch (const Base::Exception& e) {
1371 throw Py::RuntimeError(e.what());
1372 }
1373 auto node = static_cast<SoNode*>(ptr);
1374 return Py::String(SoFCDB::writeNodesToString(node));
1375 }
1376
1377 // FIXME: Once View3DInventor inherits from PropertyContainer we can use PropertyEnumeration.
1378 const char* StereoTypeEnums[]
1379 = {"Mono", "Anaglyph", "QuadBuffer", "InterleavedRows", "InterleavedColumns", nullptr};
1380
1381 Py::Object View3DInventorPy::setStereoType(const Py::Tuple& args)
1382 {
1383 int stereomode = -1;
1384 if (!PyArg_ParseTuple(args.ptr(), "i", &stereomode)) {
1385 char* modename;
1386 PyErr_Clear();
1387 if (!PyArg_ParseTuple(args.ptr(), "s", &modename)) {
1388 throw Py::Exception();
1389 }
1390 for (int i = 0; i < 5; i++) {
1391 if (strncmp(StereoTypeEnums[i], modename, 20) == 0) {
1392 stereomode = i;
1393 break;
1394 }
1395 }
1396
1397 if (stereomode < 0) {
1398 std::string s;
1399 std::ostringstream s_out;
1400 s_out << "Unknown stereo type '" << modename << "'";
1401 throw Py::NameError(s_out.str());
1402 }
1403 }
1404
1405 try {
1406 if (stereomode < 0 || stereomode > 4) {
1407 throw Py::IndexError("Out of range");
1408 }
1409 Quarter::SoQTQuarterAdaptor::StereoMode mode = Quarter::SoQTQuarterAdaptor::StereoMode(
1410 stereomode
1411 );
1412 getView3DInventorPtr()->getViewer()->setStereoMode(mode);
1413 return Py::None();
1414 }
1415 catch (const Base::Exception& e) {
1416 throw Py::RuntimeError(e.what());
1417 }
1418 catch (const std::exception& e) {
1419 throw Py::RuntimeError(e.what());
1420 }
1421 catch (...) {
1422 throw Py::RuntimeError("Unknown C++ exception");
1423 }
1424 }
1425
1426 Py::Object View3DInventorPy::getStereoType()
1427 {
1428 try {
1429 int mode = int(getView3DInventorPtr()->getViewer()->stereoMode());
1430 if (mode < 0 || mode > 4) {
1431 throw Py::ValueError("Invalid stereo mode");
1432 }
1433 return Py::String(StereoTypeEnums[mode]);
1434 }
1435 catch (const Base::Exception& e) {
1436 throw Py::RuntimeError(e.what());
1437 }
1438 catch (const std::exception& e) {
1439 throw Py::RuntimeError(e.what());
1440 }
1441 catch (...) {
1442 throw Py::RuntimeError("Unknown C++ exception");
1443 }
1444 }
1445
1446 Py::Object View3DInventorPy::listStereoTypes()
1447 {
1448 try {
1449 Py::List list(5);
1450 for (int i = 0; i < 5; i++) {
1451 list[i] = Py::String(StereoTypeEnums[i]);
1452 }
1453
1454 return list;
1455 }
1456 catch (const Base::Exception& e) {
1457 throw Py::RuntimeError(e.what());
1458 }
1459 catch (const std::exception& e) {
1460 throw Py::RuntimeError(e.what());
1461 }
1462 catch (...) {
1463 throw Py::RuntimeError("Unknown C++ exception");
1464 }
1465 }
1466
1467 Py::Object View3DInventorPy::getCursorPos()
1468 {
1469 try {
1470 QPoint pos = getView3DInventorPtr()->mapFromGlobal(QCursor::pos());
1471 auto viewer = getView3DInventorPtr()->getViewer();
1472 SbVec2s vec = viewer->fromQPoint(pos);
1473 Py::Tuple tuple(2);
1474 tuple.setItem(0, Py::Long(vec[0]));
1475 tuple.setItem(1, Py::Long(vec[1]));
1476 return tuple;
1477 }
1478 catch (const Py::Exception&) {
1479 throw;
1480 }
1481 }
1482
1483 Py::Object View3DInventorPy::getObjectInfo(const Py::Tuple& args)
1484 {
1485 PyObject* object;
1486 float r = getView3DInventorPtr()->getViewer()->getPickRadius();
1487 if (!PyArg_ParseTuple(args.ptr(), "O|f", &object, &r)) {
1488 throw Py::Exception();
1489 }
1490
1491 try {
1492 // Note: For gcc (4.2) we need the 'const' keyword to avoid the compiler error:
1493 // conversion from 'Py::seqref<Py::Object>' to non-scalar type 'Py::Long' requested
1494 // We should report this problem to the PyCXX project as in the documentation an
1495 // example without the 'const' keyword is used.
1496 // Or we can also write Py::Long x(tuple[0]);
1497 const Py::Tuple tuple(object);
1498 Py::Long x(tuple[0]);
1499 Py::Long y(tuple[1]);
1500
1501 // As this method could be called during a SoHandleEventAction scene
1502 // graph traversal we must not use a second SoHandleEventAction as
1503 // we will get Coin warnings because of multiple scene graph traversals
1504 // which is regarded as error-prone.
1505 SoRayPickAction action(
1506 getView3DInventorPtr()->getViewer()->getSoRenderManager()->getViewportRegion()
1507 );
1508 action.setPoint(SbVec2s((long)x, (long)y));
1509 action.setRadius(r);
1510 action.apply(getView3DInventorPtr()->getViewer()->getSoRenderManager()->getSceneGraph());
1511 SoPickedPoint* Point = action.getPickedPoint();
1512
1513 Py::Object ret = Py::None();
1514 if (Point) {
1515 Py::Dict dict;
1516 SbVec3f pt = Point->getPoint();
1517 dict.setItem("x", Py::Float(pt[0]));
1518 dict.setItem("y", Py::Float(pt[1]));
1519 dict.setItem("z", Py::Float(pt[2]));
1520
1521 ViewProvider* vp = getView3DInventorPtr()->getViewer()->getViewProviderByPath(
1522 Point->getPath()
1523 );
1524 if (vp && vp->isDerivedFrom<ViewProviderDocumentObject>()) {
1525 if (!vp->isSelectable()) {
1526 return ret;
1527 }
1528 auto vpd = static_cast<ViewProviderDocumentObject*>(vp);
1529 if (vp->useNewSelectionModel()) {
1530 std::string subname;
1531 if (!vp->getElementPicked(Point, subname)) {
1532 return ret;
1533 }
1534 auto obj = vpd->getObject();
1535 if (!obj) {
1536 return ret;
1537 }
1538 if (!subname.empty()) {
1539 App::ElementNamePair elementName;
1540 auto sobj = App::GeoFeature::resolveElement(obj, subname.c_str(), elementName);
1541 if (!sobj) {
1542 return ret;
1543 }
1544 if (sobj != obj) {
1545 dict.setItem("ParentObject", Py::Object(obj->getPyObject(), true));
1546 dict.setItem("SubName", Py::String(subname));
1547 obj = sobj;
1548 }
1549 subname = !elementName.oldName.empty() ? elementName.oldName
1550 : elementName.newName;
1551 }
1552 dict.setItem("Document", Py::String(obj->getDocument()->getName()));
1553 dict.setItem("Object", Py::String(obj->getNameInDocument()));
1554 dict.setItem("Component", Py::String(subname));
1555 }
1556 else {
1557 dict.setItem("Document", Py::String(vpd->getObject()->getDocument()->getName()));
1558 dict.setItem("Object", Py::String(vpd->getObject()->getNameInDocument()));
1559 // search for a SoFCSelection node
1560 SoFCDocumentObjectAction objaction;
1561 objaction.apply(Point->getPath());
1562 if (objaction.isHandled()) {
1563 dict.setItem("Component", Py::String(objaction.componentName.getString()));
1564 }
1565 }
1566
1567 // ok, found the node of interest
1568 ret = dict;
1569 }
1570 else {
1571 // custom nodes not in a VP: search for a SoFCSelection node
1572 SoFCDocumentObjectAction objaction;
1573 objaction.apply(Point->getPath());
1574 if (objaction.isHandled()) {
1575 dict.setItem("Document", Py::String(objaction.documentName.getString()));
1576 dict.setItem("Object", Py::String(objaction.objectName.getString()));
1577 dict.setItem("Component", Py::String(objaction.componentName.getString()));
1578 // ok, found the node of interest
1579 ret = dict;
1580 }
1581 }
1582 }
1583
1584 return ret;
1585 }
1586 catch (const Py::Exception&) {
1587 throw;
1588 }
1589 }
1590
1591 Py::Object View3DInventorPy::getObjectsInfo(const Py::Tuple& args)
1592 {
1593 PyObject* object;
1594 float r = getView3DInventorPtr()->getViewer()->getPickRadius();
1595 if (!PyArg_ParseTuple(args.ptr(), "O|f", &object, &r)) {
1596 throw Py::Exception();
1597 }
1598
1599 try {
1600 // Note: For gcc (4.2) we need the 'const' keyword to avoid the compiler error:
1601 // conversion from 'Py::seqref<Py::Object>' to non-scalar type 'Py::Long' requested
1602 // We should report this problem to the PyCXX project as in the documentation an
1603 // example without the 'const' keyword is used.
1604 // Or we can also write Py::Long x(tuple[0]);
1605 const Py::Tuple tuple(object);
1606 Py::Long x(tuple[0]);
1607 Py::Long y(tuple[1]);
1608
1609 // As this method could be called during a SoHandleEventAction scene
1610 // graph traversal we must not use a second SoHandleEventAction as
1611 // we will get Coin warnings because of multiple scene graph traversals
1612 // which is regarded as error-prone.
1613 SoRayPickAction action(
1614 getView3DInventorPtr()->getViewer()->getSoRenderManager()->getViewportRegion()
1615 );
1616 action.setPickAll(true);
1617 action.setRadius(r);
1618 action.setPoint(SbVec2s((long)x, (long)y));
1619 action.apply(getView3DInventorPtr()->getViewer()->getSoRenderManager()->getSceneGraph());
1620 const SoPickedPointList& pp = action.getPickedPointList();
1621
1622 Py::Object ret = Py::None();
1623 if (pp.getLength() > 0) {
1624 Py::List list;
1625 for (int i = 0; i < pp.getLength(); i++) {
1626 Py::Dict dict;
1627 auto point = static_cast<SoPickedPoint*>(pp.get(i));
1628 SbVec3f pt = point->getPoint();
1629 dict.setItem("x", Py::Float(pt[0]));
1630 dict.setItem("y", Py::Float(pt[1]));
1631 dict.setItem("z", Py::Float(pt[2]));
1632
1633 ViewProvider* vp = getView3DInventorPtr()->getViewer()->getViewProviderByPath(
1634 point->getPath()
1635 );
1636 if (vp && vp->isDerivedFrom<ViewProviderDocumentObject>()) {
1637 if (!vp->isSelectable()) {
1638 continue;
1639 }
1640 auto vpd = static_cast<ViewProviderDocumentObject*>(vp);
1641 if (vp->useNewSelectionModel()) {
1642 std::string subname;
1643 if (!vp->getElementPicked(point, subname)) {
1644 continue;
1645 }
1646 auto obj = vpd->getObject();
1647 if (!obj) {
1648 continue;
1649 }
1650 if (!subname.empty()) {
1651 App::ElementNamePair elementName;
1652 auto sobj
1653 = App::GeoFeature::resolveElement(obj, subname.c_str(), elementName);
1654 if (!sobj) {
1655 continue;
1656 }
1657 if (sobj != obj) {
1658 dict.setItem("ParentObject", Py::Object(obj->getPyObject(), true));
1659 dict.setItem("SubName", Py::String(subname));
1660 obj = sobj;
1661 }
1662 subname = !elementName.oldName.empty() ? elementName.oldName
1663 : elementName.newName;
1664 }
1665 dict.setItem("Document", Py::String(obj->getDocument()->getName()));
1666 dict.setItem("Object", Py::String(obj->getNameInDocument()));
1667 dict.setItem("Component", Py::String(subname));
1668 }
1669 else {
1670 dict.setItem("Document", Py::String(vpd->getObject()->getDocument()->getName()));
1671 dict.setItem("Object", Py::String(vpd->getObject()->getNameInDocument()));
1672 // search for a SoFCSelection node
1673 SoFCDocumentObjectAction objaction;
1674 objaction.apply(point->getPath());
1675 if (objaction.isHandled()) {
1676 dict.setItem("Component", Py::String(objaction.componentName.getString()));
1677 }
1678 }
1679 // ok, found the node of interest
1680 list.append(dict);
1681 }
1682 else {
1683 // custom nodes not in a VP: search for a SoFCSelection node
1684 SoFCDocumentObjectAction objaction;
1685 objaction.apply(point->getPath());
1686 if (objaction.isHandled()) {
1687 dict.setItem("Document", Py::String(objaction.documentName.getString()));
1688 dict.setItem("Object", Py::String(objaction.objectName.getString()));
1689 dict.setItem("Component", Py::String(objaction.componentName.getString()));
1690 // ok, found the node of interest
1691 ret = dict;
1692 }
1693 }
1694 }
1695
1696 ret = list;
1697 }
1698
1699 return ret;
1700 }
1701 catch (const Py::Exception&) {
1702 throw;
1703 }
1704 }
1705
1706 Py::Object View3DInventorPy::getObjectInfoRay(const Py::Tuple& args)
1707 {
1708 PyObject* vs;
1709 PyObject* vd;
1710 double vsx, vsy, vsz;
1711 double vdx, vdy, vdz;
1712 Py::Object ret = Py::None();
1713 if (PyArg_ParseTuple(args.ptr(), "O!O!", &Base::VectorPy::Type, &vs, &Base::VectorPy::Type, &vd)) {
1714 Base::Vector3d* startvec = static_cast<Base::VectorPy*>(vs)->getVectorPtr();
1715 Base::Vector3d* dirvec = static_cast<Base::VectorPy*>(vd)->getVectorPtr();
1716 try {
1717 RayPickInfo pinfo = getView3DInventorPtr()->getObjInfoRay(startvec, dirvec);
1718 if (!pinfo.isValid) {
1719 return ret;
1720 }
1721 Py::Dict dict;
1722 dict.setItem("PickedPoint", Py::asObject(new Base::VectorPy(pinfo.point)));
1723 dict.setItem("Document", Py::String(pinfo.document));
1724 dict.setItem("Object", Py::String(pinfo.object));
1725 if (pinfo.parentObject) {
1726 dict.setItem("ParentObject", Py::String(pinfo.parentObject.value()));
1727 }
1728 if (pinfo.component) {
1729 dict.setItem("Component", Py::String(pinfo.component.value()));
1730 }
1731 if (pinfo.subName) {
1732 dict.setItem("SubName", Py::String(pinfo.subName.value()));
1733 }
1734 ret = dict;
1735 }
1736 catch (const Py::Exception&) {
1737 throw;
1738 }
1739 }
1740 else {
1741 PyErr_Clear();
1742 if (!PyArg_ParseTuple(args.ptr(), "dddddd", &vsx, &vsy, &vsz, &vdx, &vdy, &vdz)) {
1743 throw Py::TypeError("Wrong arguments, two Vectors or six floats expected");
1744 }
1745 }
1746 return ret;
1747 }
1748
1749 Py::Object View3DInventorPy::getSize()
1750 {
1751 try {
1752 SbVec2s size = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getSize();
1753 Py::Tuple tuple(2);
1754 tuple.setItem(0, Py::Long(size[0]));
1755 tuple.setItem(1, Py::Long(size[1]));
1756 return tuple;
1757 }
1758 catch (const Py::Exception&) {
1759 throw;
1760 }
1761 }
1762
1763 Py::Object View3DInventorPy::getPointOnFocalPlane(const Py::Tuple& args)
1764 {
1765 short x, y;
1766 if (!PyArg_ParseTuple(args.ptr(), "hh", &x, &y)) {
1767 PyErr_Clear();
1768 Py::Tuple t(args[0]);
1769 x = (int)Py::Long(t[0]);
1770 y = (int)Py::Long(t[1]);
1771 }
1772 try {
1773 SbVec3f pt = getView3DInventorPtr()->getViewer()->getPointOnFocalPlane(SbVec2s(x, y));
1774 return Py::Vector(Base::Vector3f(pt[0], pt[1], pt[2]));
1775 }
1776 catch (const Base::Exception& e) {
1777 throw Py::RuntimeError(e.what());
1778 }
1779 catch (const Py::Exception&) {
1780 throw;
1781 }
1782 }
1783
1784 Py::Object View3DInventorPy::getPointOnViewport(const Py::Tuple& args)
1785 {
1786 PyObject* v;
1787 double vx, vy, vz;
1788 if (PyArg_ParseTuple(args.ptr(), "O!", &Base::VectorPy::Type, &v)) {
1789 Base::Vector3d* vec = static_cast<Base::VectorPy*>(v)->getVectorPtr();
1790 vx = vec->x;
1791 vy = vec->y;
1792 vz = vec->z;
1793 }
1794 else {
1795 PyErr_Clear();
1796 if (!PyArg_ParseTuple(args.ptr(), "ddd", &vx, &vy, &vz)) {
1797 throw Py::TypeError("Wrong argument, Vector or three floats expected expected");
1798 }
1799 }
1800
1801 try {
1802 SbVec2s pt = getView3DInventorPtr()->getViewer()->getPointOnViewport(SbVec3f(vx, vy, vz));
1803 Py::Tuple tuple(2);
1804 tuple.setItem(0, Py::Long(pt[0]));
1805 tuple.setItem(1, Py::Long(pt[1]));
1806
1807 return tuple;
1808 }
1809 catch (const Base::Exception& e) {
1810 throw Py::RuntimeError(e.what());
1811 }
1812 catch (const Py::Exception&) {
1813 throw;
1814 }
1815 }
1816
1817 Py::Object View3DInventorPy::projectPointToLine(const Py::Tuple& args)
1818 {
1819 short x, y;
1820 if (!PyArg_ParseTuple(args.ptr(), "hh", &x, &y)) {
1821 PyErr_Clear();
1822 Py::Tuple t(args[0]);
1823 x = (int)Py::Long(t[0]);
1824 y = (int)Py::Long(t[1]);
1825 }
1826 try {
1827 SbVec3f pt1, pt2;
1828 getView3DInventorPtr()->getViewer()->projectPointToLine(SbVec2s(x, y), pt1, pt2);
1829 Py::Tuple tuple(2);
1830 tuple.setItem(0, Py::Vector(Base::Vector3f(pt1[0], pt1[1], pt1[2])));
1831 tuple.setItem(1, Py::Vector(Base::Vector3f(pt2[0], pt2[1], pt2[2])));
1832 return tuple;
1833 }
1834 catch (const Base::Exception& e) {
1835 throw Py::RuntimeError(e.what());
1836 }
1837 catch (const Py::Exception&) {
1838 throw;
1839 }
1840 }
1841
1842 Py::Object View3DInventorPy::listNavigationTypes()
1843 {
1844 std::vector<Base::Type> types;
1845 Py::List styles;
1846 Base::Type::getAllDerivedFrom(UserNavigationStyle::getClassTypeId(), types);
1847 for (auto it = types.begin() + 1; it != types.end(); ++it) {
1848 styles.append(Py::String(it->getName()));
1849 }
1850 return styles;
1851 }
1852
1853 Py::Object View3DInventorPy::getNavigationType()
1854 {
1855 std::string name = getView3DInventorPtr()->getViewer()->navigationStyle()->getTypeId().getName();
1856 return Py::String(name);
1857 }
1858
1859 Py::Object View3DInventorPy::setNavigationType(const Py::Tuple& args)
1860 {
1861 char* style;
1862 if (!PyArg_ParseTuple(args.ptr(), "s", &style)) {
1863 throw Py::Exception();
1864 }
1865 Base::Type type = Base::Type::fromName(style);
1866 getView3DInventorPtr()->getViewer()->setNavigationType(type);
1867 return Py::None();
1868 }
1869
1870 void View3DInventorPy::eventCallback(void* ud, SoEventCallback* n)
1871 {
1872 Base::PyGILStateLocker lock;
1873 try {
1874 Py::Dict dict;
1875 const SoEvent* e = n->getEvent();
1876 if (!e) { // invalid event
1877 return;
1878 }
1879 // Type
1880 dict.setItem("Type", Py::String(std::string(e->getTypeId().getName().getString())));
1881 // Time
1882 dict.setItem(
1883 "Time",
1884 Py::String(std::string(e->getTime().formatDate("%Y-%m-%d %H:%M:%S").getString()))
1885 );
1886 SbVec2s p = n->getEvent()->getPosition();
1887 Py::Tuple pos(2);
1888 pos.setItem(0, Py::Long(p[0]));
1889 pos.setItem(1, Py::Long(p[1]));
1890 // Position
1891 dict.setItem("Position", pos);
1892 // Shift, Ctrl, Alt down
1893 dict.setItem("ShiftDown", Py::Object((e->wasShiftDown() ? Py_True : Py_False)));
1894 dict.setItem("CtrlDown", Py::Object((e->wasCtrlDown() ? Py_True : Py_False)));
1895 dict.setItem("AltDown", Py::Object((e->wasAltDown() ? Py_True : Py_False)));
1896 if (e->isOfType(SoButtonEvent::getClassTypeId())) {
1897 std::string state;
1898 const auto be = static_cast<const SoButtonEvent*>(e);
1899 switch (be->getState()) {
1900 case SoButtonEvent::UP:
1901 state = "UP";
1902 break;
1903 case SoButtonEvent::DOWN:
1904 state = "DOWN";
1905 break;
1906 default:
1907 state = "UNKNOWN";
1908 break;
1909 }
1910
1911 dict.setItem("State", Py::String(state));
1912 }
1913 if (e->isOfType(SoKeyboardEvent::getClassTypeId())) {
1914 const auto ke = static_cast<const SoKeyboardEvent*>(e);
1915 switch (ke->getKey()) {
1916 case SoKeyboardEvent::ANY:
1917 dict.setItem("Key", Py::String("ANY"));
1918 break;
1919 case SoKeyboardEvent::UNDEFINED:
1920 dict.setItem("Key", Py::String("UNDEFINED"));
1921 break;
1922 case SoKeyboardEvent::LEFT_SHIFT:
1923 case SoKeyboardEvent::RIGHT_SHIFT:
1924 dict.setItem("Key", Py::String("SHIFT"));
1925 break;
1926 case SoKeyboardEvent::LEFT_CONTROL:
1927 case SoKeyboardEvent::RIGHT_CONTROL:
1928 dict.setItem("Key", Py::String("CONTROL"));
1929 break;
1930 case SoKeyboardEvent::LEFT_ALT:
1931 case SoKeyboardEvent::RIGHT_ALT:
1932 dict.setItem("Key", Py::String("ALT"));
1933 break;
1934 case SoKeyboardEvent::HOME:
1935 dict.setItem("Key", Py::String("HOME"));
1936 break;
1937 case SoKeyboardEvent::LEFT_ARROW:
1938 dict.setItem("Key", Py::String("LEFT_ARROW"));
1939 break;
1940 case SoKeyboardEvent::UP_ARROW:
1941 dict.setItem("Key", Py::String("UP_ARROW"));
1942 break;
1943 case SoKeyboardEvent::RIGHT_ARROW:
1944 dict.setItem("Key", Py::String("RIGHT_ARROW"));
1945 break;
1946 case SoKeyboardEvent::DOWN_ARROW:
1947 dict.setItem("Key", Py::String("DOWN_ARROW"));
1948 break;
1949 case SoKeyboardEvent::PAGE_UP:
1950 dict.setItem("Key", Py::String("PAGE_UP"));
1951 break;
1952 case SoKeyboardEvent::PAGE_DOWN:
1953 dict.setItem("Key", Py::String("PAGE_DOWN"));
1954 break;
1955 case SoKeyboardEvent::END:
1956 dict.setItem("Key", Py::String("END"));
1957 break;
1958 case SoKeyboardEvent::PAD_ENTER:
1959 dict.setItem("Key", Py::String("PAD_ENTER"));
1960 break;
1961 case SoKeyboardEvent::PAD_F1:
1962 dict.setItem("Key", Py::String("PAD_F1"));
1963 break;
1964 case SoKeyboardEvent::PAD_F2:
1965 dict.setItem("Key", Py::String("PAD_F2"));
1966 break;
1967 case SoKeyboardEvent::PAD_F3:
1968 dict.setItem("Key", Py::String("PAD_F3"));
1969 break;
1970 case SoKeyboardEvent::PAD_F4:
1971 dict.setItem("Key", Py::String("PAD_F4"));
1972 break;
1973 case SoKeyboardEvent::PAD_0:
1974 dict.setItem("Key", Py::String("PAD_0"));
1975 break;
1976 case SoKeyboardEvent::PAD_1:
1977 dict.setItem("Key", Py::String("PAD_1"));
1978 break;
1979 case SoKeyboardEvent::PAD_2:
1980 dict.setItem("Key", Py::String("PAD_2"));
1981 break;
1982 case SoKeyboardEvent::PAD_3:
1983 dict.setItem("Key", Py::String("PAD_3"));
1984 break;
1985 case SoKeyboardEvent::PAD_4:
1986 dict.setItem("Key", Py::String("PAD_4"));
1987 break;
1988 case SoKeyboardEvent::PAD_5:
1989 dict.setItem("Key", Py::String("PAD_5"));
1990 break;
1991 case SoKeyboardEvent::PAD_6:
1992 dict.setItem("Key", Py::String("PAD_6"));
1993 break;
1994 case SoKeyboardEvent::PAD_7:
1995 dict.setItem("Key", Py::String("PAD_7"));
1996 break;
1997 case SoKeyboardEvent::PAD_8:
1998 dict.setItem("Key", Py::String("PAD_8"));
1999 break;
2000 case SoKeyboardEvent::PAD_9:
2001 dict.setItem("Key", Py::String("PAD_9"));
2002 break;
2003 case SoKeyboardEvent::PAD_ADD:
2004 dict.setItem("Key", Py::String("PAD_ADD"));
2005 break;
2006 case SoKeyboardEvent::PAD_SUBTRACT:
2007 dict.setItem("Key", Py::String("PAD_SUBTRACT"));
2008 break;
2009 case SoKeyboardEvent::PAD_MULTIPLY:
2010 dict.setItem("Key", Py::String("PAD_MULTIPLY"));
2011 break;
2012 case SoKeyboardEvent::PAD_DIVIDE:
2013 dict.setItem("Key", Py::String("PAD_DIVIDE"));
2014 break;
2015 case SoKeyboardEvent::PAD_TAB:
2016 dict.setItem("Key", Py::String("PAD_TAB"));
2017 break;
2018 case SoKeyboardEvent::PAD_DELETE:
2019 dict.setItem("Key", Py::String("PAD_DELETE"));
2020 break;
2021 case SoKeyboardEvent::F1:
2022 dict.setItem("Key", Py::String("F1"));
2023 break;
2024 case SoKeyboardEvent::F2:
2025 dict.setItem("Key", Py::String("F2"));
2026 break;
2027 case SoKeyboardEvent::F3:
2028 dict.setItem("Key", Py::String("F3"));
2029 break;
2030 case SoKeyboardEvent::F4:
2031 dict.setItem("Key", Py::String("F4"));
2032 break;
2033 case SoKeyboardEvent::F5:
2034 dict.setItem("Key", Py::String("F5"));
2035 break;
2036 case SoKeyboardEvent::F6:
2037 dict.setItem("Key", Py::String("F6"));
2038 break;
2039 case SoKeyboardEvent::F7:
2040 dict.setItem("Key", Py::String("F7"));
2041 break;
2042 case SoKeyboardEvent::F8:
2043 dict.setItem("Key", Py::String("F8"));
2044 break;
2045 case SoKeyboardEvent::F9:
2046 dict.setItem("Key", Py::String("F9"));
2047 break;
2048 case SoKeyboardEvent::F10:
2049 dict.setItem("Key", Py::String("F10"));
2050 break;
2051 case SoKeyboardEvent::F11:
2052 dict.setItem("Key", Py::String("F11"));
2053 break;
2054 case SoKeyboardEvent::F12:
2055 dict.setItem("Key", Py::String("F12"));
2056 break;
2057 case SoKeyboardEvent::BACKSPACE:
2058 dict.setItem("Key", Py::String("BACKSPACE"));
2059 break;
2060 case SoKeyboardEvent::TAB:
2061 dict.setItem("Key", Py::String("TAB"));
2062 break;
2063 case SoKeyboardEvent::RETURN:
2064 dict.setItem("Key", Py::String("RETURN"));
2065 break;
2066 case SoKeyboardEvent::PAUSE:
2067 dict.setItem("Key", Py::String("PAUSE"));
2068 break;
2069 case SoKeyboardEvent::SCROLL_LOCK:
2070 dict.setItem("Key", Py::String("SCROLL_LOCK"));
2071 break;
2072 case SoKeyboardEvent::ESCAPE:
2073 dict.setItem("Key", Py::String("ESCAPE"));
2074 break;
2075 case SoKeyboardEvent::KEY_DELETE:
2076 dict.setItem("Key", Py::String("DELETE"));
2077 break;
2078 case SoKeyboardEvent::PRINT:
2079 dict.setItem("Key", Py::String("PRINT"));
2080 break;
2081 case SoKeyboardEvent::INSERT:
2082 dict.setItem("Key", Py::String("INSERT"));
2083 break;
2084 case SoKeyboardEvent::NUM_LOCK:
2085 dict.setItem("Key", Py::String("NUM_LOCK"));
2086 break;
2087 case SoKeyboardEvent::CAPS_LOCK:
2088 dict.setItem("Key", Py::String("CAPS_LOCK"));
2089 break;
2090 case SoKeyboardEvent::SHIFT_LOCK:
2091 dict.setItem("Key", Py::String("SHIFT_LOCK"));
2092 break;
2093 case SoKeyboardEvent::SPACE:
2094 dict.setItem("Key", Py::String("SPACE"));
2095 break;
2096 case SoKeyboardEvent::APOSTROPHE:
2097 dict.setItem("Key", Py::String("APOSTROPHE"));
2098 break;
2099 case SoKeyboardEvent::COMMA:
2100 dict.setItem("Key", Py::String("COMMA"));
2101 break;
2102 case SoKeyboardEvent::MINUS:
2103 dict.setItem("Key", Py::String("MINUS"));
2104 break;
2105 case SoKeyboardEvent::PERIOD:
2106 dict.setItem("Key", Py::String("PERIOD"));
2107 break;
2108 case SoKeyboardEvent::SLASH:
2109 dict.setItem("Key", Py::String("SLASH"));
2110 break;
2111 case SoKeyboardEvent::SEMICOLON:
2112 dict.setItem("Key", Py::String("SEMICOLON"));
2113 break;
2114 case SoKeyboardEvent::EQUAL:
2115 dict.setItem("Key", Py::String("EQUAL"));
2116 break;
2117 case SoKeyboardEvent::BRACKETLEFT:
2118 dict.setItem("Key", Py::String("BRACKETLEFT"));
2119 break;
2120 case SoKeyboardEvent::BACKSLASH:
2121 dict.setItem("Key", Py::String("BACKSLASH"));
2122 break;
2123 case SoKeyboardEvent::BRACKETRIGHT:
2124 dict.setItem("Key", Py::String("BRACKETRIGHT"));
2125 break;
2126 case SoKeyboardEvent::GRAVE:
2127 dict.setItem("Key", Py::String("GRAVE"));
2128 break;
2129 default:
2130 dict.setItem("Key", Py::Char(ke->getPrintableCharacter()));
2131 break;
2132 }
2133 }
2134 if (e->isOfType(SoMouseButtonEvent::getClassTypeId())) {
2135 const auto mbe = static_cast<const SoMouseButtonEvent*>(e);
2136 std::string button;
2137 switch (mbe->getButton()) {
2138 case SoMouseButtonEvent::BUTTON1:
2139 button = "BUTTON1";
2140 break;
2141 case SoMouseButtonEvent::BUTTON2:
2142 button = "BUTTON2";
2143 break;
2144 case SoMouseButtonEvent::BUTTON3:
2145 button = "BUTTON3";
2146 break;
2147 case SoMouseButtonEvent::BUTTON4:
2148 button = "BUTTON4";
2149 break;
2150 case SoMouseButtonEvent::BUTTON5:
2151 button = "BUTTON5";
2152 break;
2153 default:
2154 button = "ANY";
2155 break;
2156 }
2157
2158 dict.setItem("Button", Py::String(button));
2159 }
2160 if (e->isOfType(SoMouseWheelEvent::getClassTypeId())) {
2161 const auto mwe = static_cast<const SoMouseWheelEvent*>(e);
2162 dict.setItem("Delta", Py::Long(mwe->getDelta()));
2163 }
2164 if (e->isOfType(SoSpaceballButtonEvent::getClassTypeId())) {
2165 const auto sbe = static_cast<const SoSpaceballButtonEvent*>(e);
2166 std::string button;
2167 switch (sbe->getButton()) {
2168 case SoSpaceballButtonEvent::BUTTON1:
2169 button = "BUTTON1";
2170 break;
2171 case SoSpaceballButtonEvent::BUTTON2:
2172 button = "BUTTON2";
2173 break;
2174 case SoSpaceballButtonEvent::BUTTON3:
2175 button = "BUTTON3";
2176 break;
2177 case SoSpaceballButtonEvent::BUTTON4:
2178 button = "BUTTON4";
2179 break;
2180 case SoSpaceballButtonEvent::BUTTON5:
2181 button = "BUTTON5";
2182 break;
2183 case SoSpaceballButtonEvent::BUTTON6:
2184 button = "BUTTON6";
2185 break;
2186 case SoSpaceballButtonEvent::BUTTON7:
2187 button = "BUTTON7";
2188 break;
2189 default:
2190 button = "ANY";
2191 break;
2192 }
2193
2194 dict.setItem("Button", Py::String(button));
2195 }
2196 if (e->isOfType(SoMotion3Event::getClassTypeId())) {
2197 const auto me = static_cast<const SoMotion3Event*>(e);
2198 const SbVec3f& m = me->getTranslation();
2199 const SbRotation& r = me->getRotation();
2200 Py::Tuple mov(3);
2201 mov.setItem(0, Py::Float(m[0]));
2202 mov.setItem(1, Py::Float(m[1]));
2203 mov.setItem(2, Py::Float(m[2]));
2204 dict.setItem("Translation", mov);
2205 Py::Tuple rot(4);
2206 rot.setItem(0, Py::Float(r.getValue()[0]));
2207 rot.setItem(1, Py::Float(r.getValue()[1]));
2208 rot.setItem(2, Py::Float(r.getValue()[2]));
2209 rot.setItem(3, Py::Float(r.getValue()[3]));
2210 dict.setItem("Rotation", rot);
2211 }
2212
2213 // now run the method
2214 Py::Callable method(reinterpret_cast<PyObject*>(ud));
2215 Py::Tuple args(1);
2216 args.setItem(0, dict);
2217 method.apply(args);
2218 }
2219 catch (const Py::Exception& e) {
2220 Py::Object o = Py::type(e);
2221 if (o.isString()) {
2222 Py::String s(o);
2223 Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str());
2224 }
2225 else {
2226 Py::String s(o.repr());
2227 Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str());
2228 }
2229 // Prints message to console window if we are in interactive mode
2230 PyErr_Print();
2231 }
2232 }
2233
2234 Py::Object View3DInventorPy::addEventCallback(const Py::Tuple& args)
2235 {
2236 char* eventtype;
2237 PyObject* method;
2238 if (!PyArg_ParseTuple(args.ptr(), "sO", &eventtype, &method)) {
2239 throw Py::Exception();
2240 }
2241 try {
2242 if (PyCallable_Check(method) == 0) {
2243 throw Py::TypeError("object is not callable");
2244 }
2245 SoType eventId = SoType::fromName(eventtype);
2246 if (eventId.isBad() || !eventId.isDerivedFrom(SoEvent::getClassTypeId())) {
2247 std::string s;
2248 std::ostringstream s_out;
2249 s_out << eventtype << " is not a valid event type";
2250 throw Py::TypeError(s_out.str());
2251 }
2252
2253 getView3DInventorPtr()->getViewer()->addEventCallback(
2254 eventId,
2255 View3DInventorPy::eventCallback,
2256 method
2257 );
2258 callbacks.push_back(method);
2259 Py_INCREF(method);
2260 return Py::Callable(method, false);
2261 }
2262 catch (const Py::Exception&) {
2263 throw;
2264 }
2265 }
2266
2267 Py::Object View3DInventorPy::removeEventCallback(const Py::Tuple& args)
2268 {
2269 char* eventtype;
2270 PyObject* method;
2271 if (!PyArg_ParseTuple(args.ptr(), "sO", &eventtype, &method)) {
2272 throw Py::Exception();
2273 }
2274 try {
2275 if (PyCallable_Check(method) == 0) {
2276 throw Py::RuntimeError("object is not callable");
2277 }
2278 SoType eventId = SoType::fromName(eventtype);
2279 if (eventId.isBad() || !eventId.isDerivedFrom(SoEvent::getClassTypeId())) {
2280 std::string s;
2281 std::ostringstream s_out;
2282 s_out << eventtype << " is not a valid event type";
2283 throw Py::TypeError(s_out.str());
2284 }
2285
2286 getView3DInventorPtr()->getViewer()->removeEventCallback(
2287 eventId,
2288 View3DInventorPy::eventCallback,
2289 method
2290 );
2291 callbacks.remove(method);
2292 Py_DECREF(method);
2293 return Py::None();
2294 }
2295 catch (const Py::Exception&) {
2296 throw;
2297 }
2298 }
2299
2300 Py::Object View3DInventorPy::setAnnotation(const Py::Tuple& args)
2301 {
2302 char *psAnnoName, *psBuffer;
2303 if (!PyArg_ParseTuple(args.ptr(), "ss", &psAnnoName, &psBuffer)) {
2304 throw Py::Exception();
2305 }
2306 ViewProviderExtern* view = nullptr;
2307 try {
2308 view = new ViewProviderExtern();
2309 view->setModeByString(psAnnoName, psBuffer);
2310 }
2311 catch (const Base::Exception& e) {
2312 delete view;
2313 throw Py::RuntimeError(e.what());
2314 }
2315
2316 getView3DInventorPtr()->getGuiDocument()->setAnnotationViewProvider(psAnnoName, view);
2317 return Py::None();
2318 }
2319
2320 Py::Object View3DInventorPy::removeAnnotation(const Py::Tuple& args)
2321 {
2322 char* psAnnoName;
2323 if (!PyArg_ParseTuple(args.ptr(), "s", &psAnnoName)) {
2324 throw Py::Exception();
2325 }
2326 ViewProvider* view = nullptr;
2327 view = getView3DInventorPtr()->getGuiDocument()->getAnnotationViewProvider(psAnnoName);
2328 if (view) {
2329 getView3DInventorPtr()->getGuiDocument()->removeAnnotationViewProvider(psAnnoName);
2330 return Py::None();
2331 }
2332 else {
2333 std::string s;
2334 std::ostringstream s_out;
2335 s_out << "No such annotation '" << psAnnoName << "'";
2336 throw Py::KeyError(s_out.str());
2337 }
2338 }
2339
2340 Py::Object View3DInventorPy::getSceneGraph()
2341 {
2342 try {
2343 SoNode* scene = getView3DInventorPtr()->getViewer()->getSceneGraph();
2344 if (scene == nullptr) {
2345 return Py::None();
2346 }
2347 PyObject* proxy = nullptr;
2348 proxy = Base::Interpreter()
2349 .createSWIGPointerObj("pivy.coin", "SoSeparator *", static_cast<void*>(scene), 1);
2350 scene->ref();
2351 return Py::Object(proxy, true);
2352 }
2353 catch (const Base::Exception& e) {
2354 throw Py::RuntimeError(e.what());
2355 }
2356 }
2357
2358 Py::Object View3DInventorPy::getViewer()
2359 {
2360 View3DInventorViewer* viewer = getView3DInventorPtr()->getViewer();
2361 return Py::Object(viewer->getPyObject(), true);
2362 }
2363
2364 void View3DInventorPy::eventCallbackPivy(void* ud, SoEventCallback* n)
2365 {
2366 Base::PyGILStateLocker lock;
2367 const SoEvent* e = n->getEvent();
2368 std::string type = e->getTypeId().getName().getString();
2369 type += " *";
2370
2371 PyObject* proxy = nullptr;
2372 try {
2373 proxy = Base::Interpreter().createSWIGPointerObj(
2374 "pivy.coin",
2375 type.c_str(),
2376 const_cast<void*>(static_cast<const void*>(e)),
2377 0
2378 );
2379 // now run the method
2380 Py::Object event(proxy, true);
2381 Py::Callable method(static_cast<PyObject*>(ud));
2382 Py::Tuple args(1);
2383 args.setItem(0, event);
2384 method.apply(args);
2385 }
2386 catch (const Base::Exception&) {
2387 return;
2388 }
2389 catch (const Py::Exception& e) {
2390 Py::Object o = Py::type(e);
2391 if (o.isString()) {
2392 Py::String s(o);
2393 Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str());
2394 }
2395 else {
2396 Py::String s(o.repr());
2397 Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str());
2398 }
2399 // Prints message to console window if we are in interactive mode
2400 PyErr_Print();
2401 }
2402 }
2403
2404 void View3DInventorPy::eventCallbackPivyEx(void* ud, SoEventCallback* n)
2405 {
2406 Base::PyGILStateLocker lock;
2407 std::string type = "SoEventCallback *";
2408
2409 PyObject* proxy = nullptr;
2410 try {
2411 proxy = Base::Interpreter()
2412 .createSWIGPointerObj("pivy.coin", type.c_str(), static_cast<void*>(n), 0);
2413 // now run the method
2414 Py::Object event(proxy, true);
2415 Py::Callable method(reinterpret_cast<PyObject*>(ud));
2416 Py::Tuple args(1);
2417 args.setItem(0, event);
2418 method.apply(args);
2419 }
2420 catch (const Base::Exception&) {
2421 return;
2422 }
2423 catch (const Py::Exception& e) {
2424 Py::Object o = Py::type(e);
2425 if (o.isString()) {
2426 Py::String s(o);
2427 Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str());
2428 }
2429 else {
2430 Py::String s(o.repr());
2431 Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str());
2432 }
2433 // Prints message to console window if we are in interactive mode
2434 PyErr_Print();
2435 }
2436 }
2437
2438 Py::Object View3DInventorPy::addEventCallbackPivy(const Py::Tuple& args)
2439 {
2440 PyObject* proxy;
2441 PyObject* method;
2442 int ex = 1; // if 1, use eventCallbackPivyEx
2443 if (!PyArg_ParseTuple(args.ptr(), "OO|i", &proxy, &method, &ex)) {
2444 throw Py::Exception();
2445 }
2446
2447 void* ptr = nullptr;
2448 try {
2449 Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoType *", proxy, &ptr, 0);
2450 if (!ptr) {
2451 throw Py::RuntimeError("Conversion of SoType failed");
2452 }
2453 }
2454 catch (const Base::Exception& e) {
2455 throw Py::RuntimeError(e.what());
2456 }
2457
2458 auto eventId = static_cast<SoType*>(ptr);
2459 if (eventId->isBad() || !eventId->isDerivedFrom(SoEvent::getClassTypeId())) {
2460 std::string s;
2461 std::ostringstream s_out;
2462 s_out << eventId->getName().getString() << "is not a valid event type";
2463 throw Py::TypeError(s_out.str());
2464 }
2465
2466 try {
2467 if (PyCallable_Check(method) == 0) {
2468 throw Py::TypeError("object is not callable");
2469 }
2470
2471 SoEventCallbackCB* callback
2472 = (ex == 1 ? View3DInventorPy::eventCallbackPivyEx : View3DInventorPy::eventCallbackPivy);
2473 getView3DInventorPtr()->getViewer()->addEventCallback(*eventId, callback, method);
2474 callbacks.push_back(method);
2475 Py_INCREF(method);
2476 return Py::Callable(method, false);
2477 }
2478 catch (const Py::Exception&) {
2479 throw;
2480 }
2481 }
2482
2483 Py::Object View3DInventorPy::removeEventCallbackPivy(const Py::Tuple& args)
2484 {
2485 PyObject* proxy;
2486 PyObject* method;
2487 int ex = 1; // if 1, use eventCallbackPivyEx
2488 if (!PyArg_ParseTuple(args.ptr(), "OO|i", &proxy, &method, &ex)) {
2489 throw Py::Exception();
2490 }
2491
2492 void* ptr = nullptr;
2493 try {
2494 Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoType *", proxy, &ptr, 0);
2495 if (!ptr) {
2496 throw Py::RuntimeError("Conversion of SoType failed");
2497 }
2498 }
2499 catch (const Base::Exception& e) {
2500 throw Py::RuntimeError(e.what());
2501 }
2502
2503 auto eventId = static_cast<SoType*>(ptr);
2504 if (eventId->isBad() || !eventId->isDerivedFrom(SoEvent::getClassTypeId())) {
2505 std::string s;
2506 std::ostringstream s_out;
2507 s_out << eventId->getName().getString() << "is not a valid event type";
2508 throw Py::TypeError(s_out.str());
2509 }
2510
2511 try {
2512 if (PyCallable_Check(method) == 0) {
2513 throw Py::TypeError("object is not callable");
2514 }
2515
2516 SoEventCallbackCB* callback
2517 = (ex == 1 ? View3DInventorPy::eventCallbackPivyEx : View3DInventorPy::eventCallbackPivy);
2518 getView3DInventorPtr()->getViewer()->removeEventCallback(*eventId, callback, method);
2519 callbacks.remove(method);
2520 Py_DECREF(method);
2521 return Py::Callable(method, false);
2522 }
2523 catch (const Py::Exception&) {
2524 throw;
2525 }
2526 }
2527
2528 Py::Object View3DInventorPy::setAxisCross(const Py::Tuple& args)
2529 {
2530 int ok;
2531 if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) {
2532 throw Py::Exception();
2533 }
2534 getView3DInventorPtr()->getViewer()->setAxisCross(ok != 0);
2535 return Py::None();
2536 }
2537
2538 Py::Object View3DInventorPy::hasAxisCross()
2539 {
2540 SbBool ok = getView3DInventorPtr()->getViewer()->hasAxisCross();
2541 return Py::Boolean(ok ? true : false);
2542 }
2543
2544 void View3DInventorPy::draggerCallback(void* ud, SoDragger* n)
2545 {
2546 Base::PyGILStateLocker lock;
2547 PyObject* proxy = nullptr;
2548 try {
2549 proxy = Base::Interpreter()
2550 .createSWIGPointerObj("pivy.coin", "SoDragger *", static_cast<void*>(n), 0);
2551 // call the method
2552 Py::Object dragger(proxy, true);
2553 Py::Callable method(reinterpret_cast<PyObject*>(ud));
2554 Py::Tuple args(1);
2555 args.setItem(0, dragger);
2556 method.apply(args);
2557 }
2558 catch (const Base::Exception& e) {
2559 throw Py::RuntimeError(e.what());
2560 }
2561 catch (const Py::Exception& e) {
2562 Py::Object o = Py::type(e);
2563 if (o.isString()) {
2564 Py::String s(o);
2565 Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str());
2566 }
2567 else {
2568 Py::String s(o.repr());
2569 Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str());
2570 }
2571 // Prints message to console window if we are in interactive mode
2572 PyErr_Print();
2573 }
2574 }
2575
2576 Py::Object View3DInventorPy::addDraggerCallback(const Py::Tuple& args)
2577 {
2578 PyObject* dragger;
2579 char* type;
2580 PyObject* method;
2581 if (!PyArg_ParseTuple(args.ptr(), "OsO", &dragger, &type, &method)) {
2582 throw Py::Exception();
2583 }
2584
2585
2586 // Check if dragger is a SoDragger object and cast
2587 void* ptr = nullptr;
2588 try {
2589 Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoDragger *", dragger, &ptr, 0);
2590 if (!ptr) {
2591 throw Py::RuntimeError("Conversion of SoDragger failed");
2592 }
2593 }
2594 catch (const Base::Exception&) {
2595 throw Py::TypeError("The first argument must be of type SoDragger");
2596 }
2597 auto drag = static_cast<SoDragger*>(ptr);
2598
2599 // Check if method is callable
2600 if (PyCallable_Check(method) == 0) {
2601 throw Py::TypeError("the method is not callable");
2602 }
2603
2604 try {
2605 if (strcmp(type, "addFinishCallback") == 0) {
2606 drag->addFinishCallback(draggerCallback, method);
2607 }
2608 else if (strcmp(type, "addStartCallback") == 0) {
2609 drag->addStartCallback(draggerCallback, method);
2610 }
2611 else if (strcmp(type, "addMotionCallback") == 0) {
2612 drag->addMotionCallback(draggerCallback, method);
2613 }
2614 else if (strcmp(type, "addValueChangedCallback") == 0) {
2615 drag->addValueChangedCallback(draggerCallback, method);
2616 }
2617 else {
2618 std::string s;
2619 std::ostringstream s_out;
2620 s_out << type << " is not a valid dragger callback type";
2621 throw Py::TypeError(s_out.str());
2622 }
2623
2624 callbacks.push_back(method);
2625 Py_INCREF(method);
2626 return Py::Callable(method, false);
2627 }
2628 catch (const Py::Exception&) {
2629 throw;
2630 }
2631 }
2632
2633 Py::Object View3DInventorPy::removeDraggerCallback(const Py::Tuple& args)
2634 {
2635 PyObject* dragger;
2636 char* type;
2637 PyObject* method;
2638 if (!PyArg_ParseTuple(args.ptr(), "OsO", &dragger, &type, &method)) {
2639 throw Py::Exception();
2640 }
2641
2642 // Check if dragger is a SoDragger object and cast
2643 void* ptr = nullptr;
2644 try {
2645 Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoDragger *", dragger, &ptr, 0);
2646 if (!ptr) {
2647 throw Py::RuntimeError("Conversion of SoDragger failed");
2648 }
2649 }
2650 catch (const Base::Exception&) {
2651 throw Py::TypeError("The first argument must be of type SoDragger");
2652 }
2653
2654 auto drag = static_cast<SoDragger*>(ptr);
2655 try {
2656 if (strcmp(type, "addFinishCallback") == 0) {
2657 drag->removeFinishCallback(draggerCallback, method);
2658 }
2659 else if (strcmp(type, "addStartCallback") == 0) {
2660 drag->removeStartCallback(draggerCallback, method);
2661 }
2662 else if (strcmp(type, "addMotionCallback") == 0) {
2663 drag->removeMotionCallback(draggerCallback, method);
2664 }
2665 else if (strcmp(type, "addValueChangedCallback") == 0) {
2666 drag->removeValueChangedCallback(draggerCallback, method);
2667 }
2668 else {
2669 std::string s;
2670 std::ostringstream s_out;
2671 s_out << type << " is not a valid dragger callback type";
2672 throw Py::TypeError(s_out.str());
2673 }
2674
2675 callbacks.remove(method);
2676 Py_DECREF(method);
2677 return Py::Callable(method, false);
2678 }
2679 catch (const Py::Exception&) {
2680 throw;
2681 }
2682 }
2683
2684 Py::Object View3DInventorPy::getViewProvidersOfType(const Py::Tuple& args)
2685 {
2686 char* name;
2687 if (!PyArg_ParseTuple(args.ptr(), "s", &name)) {
2688 throw Py::Exception();
2689 }
2690
2691 std::vector<ViewProvider*> vps = getView3DInventorPtr()->getViewer()->getViewProvidersOfType(
2692 Base::Type::fromName(name)
2693 );
2694 Py::List list;
2695 for (const auto& vp : vps) {
2696 list.append(Py::asObject(vp->getPyObject()));
2697 }
2698
2699 return list;
2700 }
2701
2702 Py::Object View3DInventorPy::redraw()
2703 {
2704 getView3DInventorPtr()->getViewer()->redraw();
2705 return Py::None();
2706 }
2707
2708 Py::Object View3DInventorPy::setName(const Py::Tuple& args)
2709 {
2710 char* buffer;
2711 if (!PyArg_ParseTuple(args.ptr(), "s", &buffer)) {
2712 throw Py::Exception();
2713 }
2714
2715 try {
2716 getView3DInventorPtr()->setWindowTitle(QString::fromUtf8(buffer));
2717 return Py::None();
2718 }
2719 catch (const Base::Exception& e) {
2720 throw Py::RuntimeError(e.what());
2721 }
2722 catch (const std::exception& e) {
2723 throw Py::RuntimeError(e.what());
2724 }
2725 catch (...) {
2726 throw Py::RuntimeError("Unknown C++ exception");
2727 }
2728 }
2729
2730 Py::Object View3DInventorPy::toggleClippingPlane(const Py::Tuple& args, const Py::Dict& kwds)
2731 {
2732 static const std::array<const char*, 5> keywords {"toggle", "beforeEditing", "noManip", "pla", nullptr};
2733 int toggle = -1;
2734 PyObject* beforeEditing = Py_False;
2735 PyObject* noManip = Py_True;
2736 PyObject* pyPla = Py_None;
2737 if (!Base::Wrapped_ParseTupleAndKeywords(
2738 args.ptr(),
2739 kwds.ptr(),
2740 "|iO!O!O!",
2741 keywords,
2742 &toggle,
2743 &PyBool_Type,
2744 &beforeEditing,
2745 &PyBool_Type,
2746 &noManip,
2747 &Base::PlacementPy::Type,
2748 &pyPla
2749 )) {
2750 throw Py::Exception();
2751 }
2752
2753 Base::Placement pla;
2754 if (pyPla != Py_None) {
2755 pla = *static_cast<Base::PlacementPy*>(pyPla)->getPlacementPtr();
2756 }
2757 getView3DInventorPtr()->getViewer()->toggleClippingPlane(
2758 toggle,
2759 Base::asBoolean(beforeEditing),
2760 Base::asBoolean(noManip),
2761 pla
2762 );
2763 return Py::None();
2764 }
2765
2766 Py::Object View3DInventorPy::hasClippingPlane()
2767 {
2768 return Py::Boolean(getView3DInventorPtr()->getViewer()->hasClippingPlane());
2769 }
2770
2771 Py::Object View3DInventorPy::graphicsView()
2772 {
2773 PythonWrapper wrap;
2774 wrap.loadWidgetsModule();
2775 return wrap.fromQWidget(getView3DInventorPtr()->getViewer(), "QGraphicsView");
2776 }
2777
2778 Py::Object View3DInventorPy::setCornerCrossVisible(const Py::Tuple& args)
2779 {
2780 int ok;
2781 if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) {
2782 throw Py::Exception();
2783 }
2784 getView3DInventorPtr()->getViewer()->setFeedbackVisibility(ok != 0);
2785 getView3DInventorPtr()->getViewer()->redraw(); // added because isViewing() returns False when
2786 // focus is in Python Console
2787 return Py::None();
2788 }
2789
2790 Py::Object View3DInventorPy::isCornerCrossVisible()
2791 {
2792 bool ok = getView3DInventorPtr()->getViewer()->isFeedbackVisible();
2793 return Py::Boolean(ok ? true : false);
2794 }
2795
2796 Py::Object View3DInventorPy::setCornerCrossSize(const Py::Tuple& args)
2797 {
2798 int size = 0;
2799 if (!PyArg_ParseTuple(args.ptr(), "i", &size)) {
2800 throw Py::Exception();
2801 }
2802 getView3DInventorPtr()->getViewer()->setFeedbackSize(size);
2803 getView3DInventorPtr()->getViewer()->redraw(); // added because isViewing() returns False when
2804 // focus is in Python Console
2805 return Py::None();
2806 }
2807
2808 Py::Object View3DInventorPy::getCornerCrossSize()
2809 {
2810 int size = getView3DInventorPtr()->getViewer()->getFeedbackSize();
2811 return Py::Long(size);
2812 }
2813
2814 Py::Object View3DInventorPy::cast_to_base()
2815 {
2816 return Gui::MDIViewPy::create(getView3DInventorPtr());
2817 }