Code

Use visual/geometric bbox (as specified in Selector tool preferences) when converting...
[inkscape.git] / src / box3d.cpp
1 #define __SP_BOX3D_C__
3 /*
4  * SVG <box3d> implementation
5  *
6  * Authors:
7  *   Maximilian Albert <Anhalter42@gmx.de>
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * Copyright (C) 2007      Authors
12  * Copyright (C) 1999-2002 Lauris Kaplinski
13  * Copyright (C) 2000-2001 Ximian, Inc.
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #include <glibmm/i18n.h>
19 #include "attributes.h"
20 #include "xml/document.h"
21 #include "xml/repr.h"
23 #include "box3d.h"
24 #include "box3d-side.h"
25 #include "box3d-context.h"
26 #include "proj_pt.h"
27 #include "transf_mat_3x4.h"
28 #include "perspective-line.h"
29 #include "inkscape.h"
30 #include "persp3d.h"
31 #include "line-geometry.h"
32 #include "persp3d-reference.h"
33 #include "uri.h"
34 #include "2geom/geom.h"
35 #include "sp-guide.h"
36 #include "sp-namedview.h"
37 #include "prefs-utils.h"
39 #include "desktop.h"
40 #include "macros.h"
42 static void box3d_class_init(SPBox3DClass *klass);
43 static void box3d_init(SPBox3D *box3d);
45 static void box3d_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
46 static void box3d_release(SPObject *object);
47 static void box3d_set(SPObject *object, unsigned int key, const gchar *value);
48 static void box3d_update(SPObject *object, SPCtx *ctx, guint flags);
49 static Inkscape::XML::Node *box3d_write(SPObject *object, Inkscape::XML::Node *repr, guint flags);
51 static gchar *box3d_description(SPItem *item);
52 static NR::Matrix box3d_set_transform(SPItem *item, NR::Matrix const &xform);
54 static void box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box);
55 static void box3d_ref_modified(SPObject *href, guint flags, SPBox3D *box);
56 //static void box3d_ref_changed(SPObject *old_ref, SPObject *ref, Persp3D *persp);
57 //static void box3d_ref_modified(SPObject *href, guint flags, Persp3D *persp);
59 static SPGroupClass *parent_class;
61 static gint counter = 0;
63 GType
64 box3d_get_type(void)
65 {
66     static GType type = 0;
68     if (!type) {
69         GTypeInfo info = {
70             sizeof(SPBox3DClass),
71             NULL,   /* base_init */
72             NULL,   /* base_finalize */
73             (GClassInitFunc) box3d_class_init,
74             NULL,   /* class_finalize */
75             NULL,   /* class_data */
76             sizeof(SPBox3D),
77             16,     /* n_preallocs */
78             (GInstanceInitFunc) box3d_init,
79             NULL,   /* value_table */
80         };
81         type = g_type_register_static(SP_TYPE_GROUP, "SPBox3D", &info, (GTypeFlags) 0);
82     }
84     return type;
85 }
87 static void
88 box3d_class_init(SPBox3DClass *klass)
89 {
90     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
91     SPItemClass *item_class = (SPItemClass *) klass;
93     parent_class = (SPGroupClass *) g_type_class_ref(SP_TYPE_GROUP);
95     sp_object_class->build = box3d_build;
96     sp_object_class->release = box3d_release;
97     sp_object_class->set = box3d_set;
98     sp_object_class->write = box3d_write;
99     sp_object_class->update = box3d_update;
101     item_class->description = box3d_description;
102     item_class->set_transform = box3d_set_transform;
105 static void
106 box3d_init(SPBox3D *box)
108     box->persp_href = NULL;
109     box->persp_ref = new Persp3DReference(SP_OBJECT(box));
110     new (&box->modified_connection) sigc::connection();
113 static void
114 box3d_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
116     if (((SPObjectClass *) (parent_class))->build) {
117         ((SPObjectClass *) (parent_class))->build(object, document, repr);
118     }
120     SPBox3D *box = SP_BOX3D (object);
121     box->my_counter = counter++;
123     /* we initialize the z-orders to zero so that they are updated during dragging */
124     for (int i = 0; i < 6; ++i) {
125         box->z_orders[i] = 0;
126     }
128     // TODO: Create/link to the correct perspective
130     SPDocument *doc = SP_OBJECT_DOCUMENT(box);
131     if (!doc) {
132         g_print ("No document for the box!!!!\n");
133         return;
134     }
135     /**
136     if (!box->persp3d) {
137         g_print ("Box seems to be newly created since no perspective is referenced yet. We reference the current perspective.\n");
138         box->persp3d = doc->current_persp3d;
139     }
140     **/
142     box->persp_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(box3d_ref_changed), box));
144     sp_object_read_attr(object, "inkscape:perspectiveID");
145     sp_object_read_attr(object, "inkscape:corner0");
146     sp_object_read_attr(object, "inkscape:corner7");
149 /**
150  * Virtual release of SPBox3D members before destruction.
151  */
152 static void
153 box3d_release(SPObject *object)
155     SPBox3D *box = (SPBox3D *) object;
157     if (box->persp_href) {
158         g_free(box->persp_href);
159     }
160     if (box->persp_ref) {
161         box->persp_ref->detach();
162         delete box->persp_ref;
163         box->persp_ref = NULL;
164     }
166     box->modified_connection.disconnect();
167     box->modified_connection.~connection();
169     //persp3d_remove_box (box3d_get_perspective(box), box);
171     if (((SPObjectClass *) parent_class)->release)
172         ((SPObjectClass *) parent_class)->release(object);
175 static void
176 box3d_set(SPObject *object, unsigned int key, const gchar *value)
178     SPBox3D *box = SP_BOX3D(object);
180     switch (key) {
181         case SP_ATTR_INKSCAPE_BOX3D_PERSPECTIVE_ID:
182             if ( value && box->persp_href && ( strcmp(value, box->persp_href) == 0 ) ) {
183                 /* No change, do nothing. */
184             } else {
185                 if (box->persp_href) {
186                     g_free(box->persp_href);
187                     box->persp_href = NULL;
188                 }
189                 if (value) {
190                     box->persp_href = g_strdup(value);
192                     // Now do the attaching, which emits the changed signal.
193                     try {
194                         box->persp_ref->attach(Inkscape::URI(value));
195                     } catch (Inkscape::BadURIException &e) {
196                         g_warning("%s", e.what());
197                         box->persp_ref->detach();
198                     }
199                 } else {
200                     // Detach, which emits the changed signal.
201                     box->persp_ref->detach();
202                         // TODO: Clean this up (also w.r.t the surrounding if construct)
203                         /***
204                         g_print ("No perspective given. Attaching to current perspective instead.\n");
205                         g_free(box->persp_href);
206                         Inkscape::XML::Node *repr = SP_OBJECT_REPR(inkscape_active_document()->current_persp3d);
207                         box->persp_href = g_strdup(repr->attribute("id"));
208                         box->persp_ref->attach(Inkscape::URI(box->persp_href));
209                         ***/
210                 }
211             }
213             // FIXME: Is the following update doubled by some call in either persp3d.cpp or vanishing_point_new.cpp?
214             box3d_position_set(box);
215             break;
216         case SP_ATTR_INKSCAPE_BOX3D_CORNER0:
217             if (value && strcmp(value, "0 : 0 : 0 : 0")) {
218                 box->orig_corner0 = Proj::Pt3(value);
219                 box->save_corner0 = box->orig_corner0;
220                 box3d_position_set(box);
221             }
222             break;
223         case SP_ATTR_INKSCAPE_BOX3D_CORNER7:
224             if (value && strcmp(value, "0 : 0 : 0 : 0")) {
225                 box->orig_corner7 = Proj::Pt3(value);
226                 box->save_corner7 = box->orig_corner7;
227                 box3d_position_set(box);
228             }
229             break;
230         default:
231             if (((SPObjectClass *) (parent_class))->set) {
232                 ((SPObjectClass *) (parent_class))->set(object, key, value);
233             }
234             break;
235     }
236     //object->updateRepr(); // This ensures correct update of the box after undo/redo. FIXME: Why is this not present in sp-rect.cpp and similar files?
239 /**
240  * Gets called when (re)attached to another perspective.
241  */
242 static void
243 box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box)
245     if (old_ref) {
246         sp_signal_disconnect_by_data(old_ref, box);
247         persp3d_remove_box (SP_PERSP3D(old_ref), box);
248         /* Note: This sometimes leads to attempts to remove boxes twice from the list of selected/transformed
249            boxes in a perspectives, but this should be uncritical. */
250         persp3d_remove_box_transform (SP_PERSP3D(old_ref), box);
251     }
252     if ( SP_IS_PERSP3D(ref) && ref != box ) // FIXME: Comparisons sane?
253     {
254         box->modified_connection.disconnect();
255         box->modified_connection = ref->connectModified(sigc::bind(sigc::ptr_fun(&box3d_ref_modified), box));
256         box3d_ref_modified(ref, 0, box);
257         persp3d_add_box (SP_PERSP3D(ref), box);
258         /* Note: This sometimes leads to attempts to add boxes twice to the list of selected/transformed
259            boxes in a perspectives, but this should be uncritical. */
260         persp3d_add_box_transform (SP_PERSP3D(ref), box);
261     }
264 static void
265 box3d_update(SPObject *object, SPCtx *ctx, guint flags)
267     if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) {
269         /* FIXME?: Perhaps the display updates of box sides should be instantiated from here, but this
270            causes evil update loops so it's all done from box3d_position_set, which is called from
271            various other places (like the handlers in object-edit.cpp, vanishing-point.cpp, etc. */
273     }
275     // Invoke parent method
276     if (((SPObjectClass *) (parent_class))->update)
277         ((SPObjectClass *) (parent_class))->update(object, ctx, flags);
281 static Inkscape::XML::Node *box3d_write(SPObject *object, Inkscape::XML::Node *repr, guint flags)
283     SPBox3D *box = SP_BOX3D(object);
285     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
286         // this is where we end up when saving as plain SVG (also in other circumstances?)
287         // thus we don' set "sodipodi:type" so that the box is only saved as an ordinary svg:g
288         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(object));
289         repr = xml_doc->createElement("svg:g");
290     }
292     if (flags & SP_OBJECT_WRITE_EXT) {
294         if (box->persp_href) {
295             repr->setAttribute("inkscape:perspectiveID", box->persp_href);
296         } else {
297             /* box is not yet linked to a perspective; use the document's current perspective */
298             SPDocument *doc = inkscape_active_document();
299             if (box->persp_ref->getURI()) {
300                 gchar *uri_string = box->persp_ref->getURI()->toString();
301                 repr->setAttribute("inkscape:perspectiveID", uri_string);
302                 g_free(uri_string);
303             } else if (doc) {
304                 //persp3d_add_box (doc->current_persp3d, box);
305                 Inkscape::XML::Node *persp_repr = SP_OBJECT_REPR(doc->current_persp3d);
306                 const gchar *persp_id = persp_repr->attribute("id");
307                 gchar *href = g_strdup_printf("#%s", persp_id);
308                 repr->setAttribute("inkscape:perspectiveID", href);
309                 g_free(href);
310             } else {
311                 g_print ("No active document while creating perspective!!!\n");
312             }
313         }
315         gchar *coordstr0 = box->orig_corner0.coord_string();
316         gchar *coordstr7 = box->orig_corner7.coord_string();
317         repr->setAttribute("inkscape:corner0", coordstr0);
318         repr->setAttribute("inkscape:corner7", coordstr7);
319         g_free(coordstr0);
320         g_free(coordstr7);
322         box->orig_corner0.normalize();
323         box->orig_corner7.normalize();
325         box->save_corner0 = box->orig_corner0;
326         box->save_corner7 = box->orig_corner7;
327     }
329     if (((SPObjectClass *) (parent_class))->write) {
330         ((SPObjectClass *) (parent_class))->write(object, repr, flags);
331     }
333     return repr;
336 static gchar *
337 box3d_description(SPItem *item)
339     g_return_val_if_fail(SP_IS_BOX3D(item), NULL);
341     return g_strdup(_("<b>3D Box</b>"));
344 void
345 box3d_position_set (SPBox3D *box)
347     /* This draws the curve and calls requestDisplayUpdate() for each side (the latter is done in
348        box3d_side_position_set() to avoid update conflicts with the parent box) */
349     for (SPObject *child = sp_object_first_child(SP_OBJECT (box)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
350         box3d_side_position_set (SP_BOX3D_SIDE (child));
351     }
354 static NR::Matrix
355 box3d_set_transform(SPItem *item, NR::Matrix const &xform)
357     SPBox3D *box = SP_BOX3D(item);
359     /* check whether we need to unlink any boxes from their perspectives */
360     Persp3D *persp = box3d_get_perspective(box);
361     Persp3D *transf_persp;
363     if (!persp3d_has_all_boxes_in_selection (persp)) {
364         std::list<SPBox3D *> sel = persp3d_selected_boxes (persp);
366         /* create a new perspective as a copy of the current one and link the selected boxes to it */
367         transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp);
369         for (std::list<SPBox3D *>::iterator b = sel.begin(); b != sel.end(); ++b) {
370             box3d_switch_perspectives(*b, persp, transf_persp);
371         }
372     } else {
373         transf_persp = persp;
374     }
376     /* only transform the perspective once, even if it has several selected boxes */
377     if(!persp3d_was_transformed (transf_persp)) {
378         /* concatenate the affine transformation with the perspective mapping; this
379            function also triggers repr updates of boxes and the perspective itself */
380         persp3d_apply_affine_transformation(transf_persp, xform);
381     }
383     box3d_mark_transformed(box);
385     if (persp3d_all_transformed(transf_persp)) {
386         /* all boxes were transformed; make perspective sensitive for further transformations */
387         persp3d_unset_transforms(transf_persp);
388     }
390     NR::Matrix ret(NR::transform(xform));
391     gdouble const sw = hypot(ret[0], ret[1]);
392     gdouble const sh = hypot(ret[2], ret[3]);
394     SPItem *sideitem = NULL;
395     for (SPObject *side = sp_object_first_child(box); side != NULL; side = SP_OBJECT_NEXT(side)) {
396         sideitem = SP_ITEM(side);
398         // Adjust stroke width
399         sp_item_adjust_stroke(sideitem, sqrt(fabs(sw * sh)));
401         // Adjust pattern fill
402         sp_item_adjust_pattern(sideitem, xform);
404         // Adjust gradient fill
405         sp_item_adjust_gradient(sideitem, xform);
407         // Adjust LPE
408         sp_item_adjust_livepatheffect(item, xform);
409     }
411     return NR::identity();
415 /**
416  * Gets called when persp(?) repr contents change: i.e. parameter change.
417  */
418 static void
419 box3d_ref_modified(SPObject */*href*/, guint /*flags*/, SPBox3D */*box*/)
421     /***
422     g_print ("FIXME: box3d_ref_modified was called. What should we do?\n");
423     g_print ("Here is at least the the href's id: %s\n", SP_OBJECT_REPR(href)->attribute("id"));
424     g_print ("             ... and the box's, too: %s\n", SP_OBJECT_REPR(box)->attribute("id"));
425     ***/
429 Proj::Pt3
430 box3d_get_proj_corner (guint id, Proj::Pt3 const &c0, Proj::Pt3 const &c7) {
431     return Proj::Pt3 ((id & Box3D::X) ? c7[Proj::X] : c0[Proj::X],
432                       (id & Box3D::Y) ? c7[Proj::Y] : c0[Proj::Y],
433                       (id & Box3D::Z) ? c7[Proj::Z] : c0[Proj::Z],
434                       1.0);
437 Proj::Pt3
438 box3d_get_proj_corner (SPBox3D const *box, guint id) {
439     return Proj::Pt3 ((id & Box3D::X) ? box->orig_corner7[Proj::X] : box->orig_corner0[Proj::X],
440                       (id & Box3D::Y) ? box->orig_corner7[Proj::Y] : box->orig_corner0[Proj::Y],
441                       (id & Box3D::Z) ? box->orig_corner7[Proj::Z] : box->orig_corner0[Proj::Z],
442                       1.0);
445 NR::Point
446 box3d_get_corner_screen (SPBox3D const *box, guint id) {
447     Proj::Pt3 proj_corner (box3d_get_proj_corner (box, id));
448     if (!box3d_get_perspective(box)) {
449         //g_print ("No perspective present in box!! Should we simply use the currently active perspective?\n");
450         return NR::Point (NR_HUGE, NR_HUGE);
451     }
452     return box3d_get_perspective(box)->tmat.image(proj_corner).affine();
455 Proj::Pt3
456 box3d_get_proj_center (SPBox3D *box) {
457     box->orig_corner0.normalize();
458     box->orig_corner7.normalize();
459     return Proj::Pt3 ((box->orig_corner0[Proj::X] + box->orig_corner7[Proj::X]) / 2,
460                       (box->orig_corner0[Proj::Y] + box->orig_corner7[Proj::Y]) / 2,
461                       (box->orig_corner0[Proj::Z] + box->orig_corner7[Proj::Z]) / 2,
462                       1.0);
465 NR::Point
466 box3d_get_center_screen (SPBox3D *box) {
467     Proj::Pt3 proj_center (box3d_get_proj_center (box));
468     if (!box3d_get_perspective(box)) {
469         //g_print ("No perspective present in box!! Should we simply use the currently active perspective?\n");
470         return NR::Point (NR_HUGE, NR_HUGE);
471     }
472     return box3d_get_perspective(box)->tmat.image(proj_center).affine();
475 /*
476  * To keep the snappoint from jumping randomly between the two lines when the mouse pointer is close to
477  * their intersection, we remember the last snapped line and keep snapping to this specific line as long
478  * as the distance from the intersection to the mouse pointer is less than remember_snap_threshold.
479  */
481 // Should we make the threshold settable in the preferences?
482 static double remember_snap_threshold = 30;
483 //static guint remember_snap_index = 0;
484 static guint remember_snap_index_center = 0;
486 static Proj::Pt3
487 box3d_snap (SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &start_pt) {
488     double z_coord = start_pt[Proj::Z];
489     double diff_x = box->save_corner7[Proj::X] - box->save_corner0[Proj::X];
490     double diff_y = box->save_corner7[Proj::Y] - box->save_corner0[Proj::Y];
491     double x_coord = start_pt[Proj::X];
492     double y_coord = start_pt[Proj::Y];
493     Proj::Pt3 A_proj (x_coord,          y_coord,          z_coord, 1.0);
494     Proj::Pt3 B_proj (x_coord + diff_x, y_coord,          z_coord, 1.0);
495     Proj::Pt3 C_proj (x_coord + diff_x, y_coord + diff_y, z_coord, 1.0);
496     Proj::Pt3 D_proj (x_coord,          y_coord + diff_y, z_coord, 1.0);
497     Proj::Pt3 E_proj (x_coord - diff_x, y_coord + diff_y, z_coord, 1.0);
499     Persp3D *persp = box3d_get_perspective(box);
500     NR::Point A = persp->tmat.image(A_proj).affine();
501     NR::Point B = persp->tmat.image(B_proj).affine();
502     NR::Point C = persp->tmat.image(C_proj).affine();
503     NR::Point D = persp->tmat.image(D_proj).affine();
504     NR::Point E = persp->tmat.image(E_proj).affine();
505     NR::Point pt = persp->tmat.image(pt_proj).affine();
507     // TODO: Replace these lines between corners with lines from a corner to a vanishing point
508     //       (this might help to prevent rounding errors if the box is small)
509     Box3D::Line pl1(A, B);
510     Box3D::Line pl2(A, D);
511     Box3D::Line diag1(A, (id == -1 || (!(id & Box3D::X) == !(id & Box3D::Y))) ? C : E);
512     Box3D::Line diag2(A, E); // diag2 is only taken into account if id equals -1, i.e., if we are snapping the center
514     int num_snap_lines = (id != -1) ? 3 : 4;
515     NR::Point snap_pts[num_snap_lines];
517     snap_pts[0] = pl1.closest_to (pt);
518     snap_pts[1] = pl2.closest_to (pt);
519     snap_pts[2] = diag1.closest_to (pt);
520     if (id == -1) {
521         snap_pts[3] = diag2.closest_to (pt);
522     }
524     gdouble const zoom = inkscape_active_desktop()->current_zoom();
526     // determine the distances to all potential snapping points
527     double snap_dists[num_snap_lines];
528     for (int i = 0; i < num_snap_lines; ++i) {
529         snap_dists[i] = NR::L2 (snap_pts[i] - pt) * zoom;
530     }
532     // while we are within a given tolerance of the starting point,
533     // keep snapping to the same point to avoid jumping
534     bool within_tolerance = true;
535     for (int i = 0; i < num_snap_lines; ++i) {
536         if (snap_dists[i] > remember_snap_threshold) {
537             within_tolerance = false;
538             break;
539         }
540     }
542     // find the closest snapping point
543     int snap_index = -1;
544     double snap_dist = NR_HUGE;
545     for (int i = 0; i < num_snap_lines; ++i) {
546         if (snap_dists[i] < snap_dist) {
547             snap_index = i;
548             snap_dist = snap_dists[i];
549         }
550     }
552     // snap to the closest point (or the previously remembered one
553     // if we are within tolerance of the starting point)
554     NR::Point result;
555     if (within_tolerance) {
556         result = snap_pts[remember_snap_index_center];
557     } else {
558         remember_snap_index_center = snap_index;
559         result = snap_pts[snap_index];
560     }
561     return box3d_get_perspective(box)->tmat.preimage (result, z_coord, Proj::Z);
564 void
565 box3d_set_corner (SPBox3D *box, const guint id, NR::Point const &new_pos, const Box3D::Axis movement, bool constrained) {
566     g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ));
568     box->orig_corner0.normalize();
569     box->orig_corner7.normalize();
571     /* update corners 0 and 7 according to which handle was moved and to the axes of movement */
572     if (!(movement & Box3D::Z)) {
573         Proj::Pt3 pt_proj (box3d_get_perspective(box)->tmat.preimage (new_pos, (id < 4) ? box->orig_corner0[Proj::Z] :
574                                                                       box->orig_corner7[Proj::Z], Proj::Z));
575         if (constrained) {
576             pt_proj = box3d_snap (box, id, pt_proj, box3d_get_proj_corner (id, box->save_corner0, box->save_corner7));
577         }
579         // normalizing pt_proj is essential because we want to mingle affine coordinates
580         pt_proj.normalize();
581         box->orig_corner0 = Proj::Pt3 ((id & Box3D::X) ? box->save_corner0[Proj::X] : pt_proj[Proj::X],
582                                        (id & Box3D::Y) ? box->save_corner0[Proj::Y] : pt_proj[Proj::Y],
583                                        box->save_corner0[Proj::Z],
584                                        1.0);
585         box->orig_corner7 = Proj::Pt3 ((id & Box3D::X) ? pt_proj[Proj::X] : box->save_corner7[Proj::X],
586                                        (id & Box3D::Y) ? pt_proj[Proj::Y] : box->save_corner7[Proj::Y],
587                                        box->save_corner7[Proj::Z],
588                                        1.0);
589     } else {
590         Persp3D *persp = box3d_get_perspective(box);
591         Box3D::PerspectiveLine pl(persp->tmat.image(
592                                       box3d_get_proj_corner (id, box->save_corner0, box->save_corner7)).affine(),
593                                   Proj::Z, persp);
594         NR::Point new_pos_snapped(pl.closest_to(new_pos));
595         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos_snapped,
596                                           box3d_get_proj_corner (box, id)[(movement & Box3D::Y) ? Proj::X : Proj::Y],
597                                           (movement & Box3D::Y) ? Proj::X : Proj::Y));
598         bool corner0_move_x = !(id & Box3D::X) && (movement & Box3D::X);
599         bool corner0_move_y = !(id & Box3D::Y) && (movement & Box3D::Y);
600         bool corner7_move_x =  (id & Box3D::X) && (movement & Box3D::X);
601         bool corner7_move_y =  (id & Box3D::Y) && (movement & Box3D::Y);
602         // normalizing pt_proj is essential because we want to mingle affine coordinates
603         pt_proj.normalize();
604         box->orig_corner0 = Proj::Pt3 (corner0_move_x ? pt_proj[Proj::X] : box->orig_corner0[Proj::X],
605                                        corner0_move_y ? pt_proj[Proj::Y] : box->orig_corner0[Proj::Y],
606                                        (id & Box3D::Z) ? box->orig_corner0[Proj::Z] : pt_proj[Proj::Z],
607                                        1.0);
608         box->orig_corner7 = Proj::Pt3 (corner7_move_x ? pt_proj[Proj::X] : box->orig_corner7[Proj::X],
609                                        corner7_move_y ? pt_proj[Proj::Y] : box->orig_corner7[Proj::Y],
610                                        (id & Box3D::Z) ? pt_proj[Proj::Z] : box->orig_corner7[Proj::Z],
611                                        1.0);
612     }
613     // FIXME: Should we update the box here? If so, how?
616 void box3d_set_center (SPBox3D *box, NR::Point const &new_pos, NR::Point const &old_pos, const Box3D::Axis movement, bool constrained) {
617     g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ));
619     Persp3D *persp = box3d_get_perspective(box);
620     if (!(movement & Box3D::Z)) {
621         double coord = (box->orig_corner0[Proj::Z] + box->orig_corner7[Proj::Z]) / 2;
622         double radx = (box->orig_corner7[Proj::X] - box->orig_corner0[Proj::X]) / 2;
623         double rady = (box->orig_corner7[Proj::Y] - box->orig_corner0[Proj::Y]) / 2;
625         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos, coord, Proj::Z));
626         if (constrained) {
627             Proj::Pt3 old_pos_proj (persp->tmat.preimage (old_pos, coord, Proj::Z));
628             pt_proj = box3d_snap (box, -1, pt_proj, old_pos_proj);
629         }
630         // normalizing pt_proj is essential because we want to mingle affine coordinates
631         pt_proj.normalize();
632         box->orig_corner0 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] - radx : box->orig_corner0[Proj::X],
633                                        (movement & Box3D::Y) ? pt_proj[Proj::Y] - rady : box->orig_corner0[Proj::Y],
634                                        box->orig_corner0[Proj::Z],
635                                        1.0);
636         box->orig_corner7 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] + radx : box->orig_corner7[Proj::X],
637                                        (movement & Box3D::Y) ? pt_proj[Proj::Y] + rady : box->orig_corner7[Proj::Y],
638                                        box->orig_corner7[Proj::Z],
639                                        1.0);
640     } else {
641         double coord = (box->orig_corner0[Proj::X] + box->orig_corner7[Proj::X]) / 2;
642         double radz = (box->orig_corner7[Proj::Z] - box->orig_corner0[Proj::Z]) / 2;
644         Box3D::PerspectiveLine pl(old_pos, Proj::Z, persp);
645         NR::Point new_pos_snapped(pl.closest_to(new_pos));
646         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos_snapped, coord, Proj::X));
648         /* normalizing pt_proj is essential because we want to mingle affine coordinates */
649         pt_proj.normalize();
650         box->orig_corner0 = Proj::Pt3 (box->orig_corner0[Proj::X],
651                                        box->orig_corner0[Proj::Y],
652                                        pt_proj[Proj::Z] - radz,
653                                        1.0);
654         box->orig_corner7 = Proj::Pt3 (box->orig_corner7[Proj::X],
655                                        box->orig_corner7[Proj::Y],
656                                        pt_proj[Proj::Z] + radz,
657                                        1.0);
658     }
661 /*
662  * Manipulates corner1 through corner4 to contain the indices of the corners
663  * from which the perspective lines in the direction of 'axis' emerge
664  */
665 void box3d_corners_for_PLs (const SPBox3D * box, Proj::Axis axis,
666                             NR::Point &corner1, NR::Point &corner2, NR::Point &corner3, NR::Point &corner4)
668     Persp3D *persp = box3d_get_perspective(box);
669     g_return_if_fail (persp);
670     //box->orig_corner0.normalize();
671     //box->orig_corner7.normalize();
672     double coord = (box->orig_corner0[axis] > box->orig_corner7[axis]) ?
673         box->orig_corner0[axis] :
674         box->orig_corner7[axis];
676     Proj::Pt3 c1, c2, c3, c4;
677     // FIXME: This can certainly be done more elegantly/efficiently than by a case-by-case analysis.
678     switch (axis) {
679         case Proj::X:
680             c1 = Proj::Pt3 (coord, box->orig_corner0[Proj::Y], box->orig_corner0[Proj::Z], 1.0);
681             c2 = Proj::Pt3 (coord, box->orig_corner7[Proj::Y], box->orig_corner0[Proj::Z], 1.0);
682             c3 = Proj::Pt3 (coord, box->orig_corner7[Proj::Y], box->orig_corner7[Proj::Z], 1.0);
683             c4 = Proj::Pt3 (coord, box->orig_corner0[Proj::Y], box->orig_corner7[Proj::Z], 1.0);
684             break;
685         case Proj::Y:
686             c1 = Proj::Pt3 (box->orig_corner0[Proj::X], coord, box->orig_corner0[Proj::Z], 1.0);
687             c2 = Proj::Pt3 (box->orig_corner7[Proj::X], coord, box->orig_corner0[Proj::Z], 1.0);
688             c3 = Proj::Pt3 (box->orig_corner7[Proj::X], coord, box->orig_corner7[Proj::Z], 1.0);
689             c4 = Proj::Pt3 (box->orig_corner0[Proj::X], coord, box->orig_corner7[Proj::Z], 1.0);
690             break;
691         case Proj::Z:
692             c1 = Proj::Pt3 (box->orig_corner7[Proj::X], box->orig_corner7[Proj::Y], coord, 1.0);
693             c2 = Proj::Pt3 (box->orig_corner7[Proj::X], box->orig_corner0[Proj::Y], coord, 1.0);
694             c3 = Proj::Pt3 (box->orig_corner0[Proj::X], box->orig_corner0[Proj::Y], coord, 1.0);
695             c4 = Proj::Pt3 (box->orig_corner0[Proj::X], box->orig_corner7[Proj::Y], coord, 1.0);
696             break;
697         default:
698             return;
699     }
700     corner1 = persp->tmat.image(c1).affine();
701     corner2 = persp->tmat.image(c2).affine();
702     corner3 = persp->tmat.image(c3).affine();
703     corner4 = persp->tmat.image(c4).affine();
706 /* Auxiliary function: Checks whether the half-line from A to B crosses the line segment joining C and D */
707 static bool
708 box3d_half_line_crosses_joining_line (Geom::Point const &A, Geom::Point const &B,
709                                       Geom::Point const &C, Geom::Point const &D) {
710     Geom::Point E; // the point of intersection
711     Geom::Point n0 = (B - A).ccw();
712     double d0 = dot(n0,A);
714     Geom::Point n1 = (D - C).ccw();
715     double d1 = dot(n1,C);
716     Geom::IntersectorKind intersects = Geom::line_intersection(n0, d0, n1, d1, E);
717     if (intersects == Geom::coincident || intersects == Geom::parallel) {
718         return false;
719     }
721     if ((dot(C,n0) < d0) == (dot(D,n0) < d0)) {
722         // C and D lie on the same side of the line AB
723         return false;
724     }
725     if ((dot(A,n1) < d1) != (dot(B,n1) < d1)) {
726         // A and B lie on different sides of the line CD
727         return true;
728     } else if (Geom::distance(E,A) < Geom::distance(E,B)) {
729         // The line CD passes on the "wrong" side of A
730         return false;
731     }
733     // The line CD passes on the "correct" side of A
734     return true;
737 static bool
738 box3d_XY_axes_are_swapped (SPBox3D *box) {
739     Persp3D *persp = box3d_get_perspective(box);
740     g_return_val_if_fail(persp, false);
741     Box3D::PerspectiveLine l1(box3d_get_corner_screen(box, 3), Proj::X, persp);
742     Box3D::PerspectiveLine l2(box3d_get_corner_screen(box, 3), Proj::Y, persp);
743     NR::Point v1(l1.direction());
744     NR::Point v2(l2.direction());
745     v1.normalize();
746     v2.normalize();
748     return (v1[NR::X]*v2[NR::Y] - v1[NR::Y]*v2[NR::X] > 0);
751 static inline void
752 box3d_aux_set_z_orders (int z_orders[6], int a, int b, int c, int d, int e, int f) {
753     z_orders[0] = a;
754     z_orders[1] = b;
755     z_orders[2] = c;
756     z_orders[3] = d;
757     z_orders[4] = e;
758     z_orders[5] = f;
761 static inline void
762 box3d_swap_z_orders (int z_orders[6]) {
763     int tmp;
764     for (int i = 0; i < 3; ++i) {
765         tmp = z_orders[i];
766         z_orders[i] = z_orders[5-i];
767         z_orders[5-i] = tmp;
768     }
771 /*
772  * In standard perspective we have:
773  * 2 = front face
774  * 1 = top face
775  * 0 = left face
776  * 3 = right face
777  * 4 = bottom face
778  * 5 = rear face
779  */
781 /* All VPs infinite */
782 static void
783 box3d_set_new_z_orders_case0 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis) {
784     Persp3D *persp = box3d_get_perspective(box);
785     NR::Point xdir(persp3d_get_infinite_dir(persp, Proj::X));
786     NR::Point ydir(persp3d_get_infinite_dir(persp, Proj::Y));
787     NR::Point zdir(persp3d_get_infinite_dir(persp, Proj::Z));
789     bool swapped = box3d_XY_axes_are_swapped(box);
791     //g_print ("3 infinite VPs; ");
792     switch(central_axis) {
793         case Box3D::X:
794             if (!swapped) {
795                 //g_print ("central axis X (case a)");
796                 box3d_aux_set_z_orders (z_orders, 2, 0, 4, 1, 3, 5);
797             } else {
798                 //g_print ("central axis X (case b)");
799                 box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0);
800             }
801             break;
802         case Box3D::Y:
803             if (!swapped) {
804                 //g_print ("central axis Y (case a)");
805                 box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5);
806             } else {
807                 //g_print ("central axis Y (case b)");
808                 box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
809             }
810             break;
811         case Box3D::Z:
812             if (!swapped) {
813                 //g_print ("central axis Z (case a)");
814                 box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
815             } else {
816                 //g_print ("central axis Z (case b)");
817                 box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2);
818             }
819             break;
820         case Box3D::NONE:
821             if (!swapped) {
822                 //g_print ("central axis NONE (case a)");
823                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
824             } else {
825                 //g_print ("central axis NONE (case b)");
826                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2);
827             }
828             break;
829         default:
830             g_assert_not_reached();
831             break;
832     }
833     /**
834     if (swapped) {
835         g_print ("; swapped");
836     }
837     g_print ("\n");
838     **/
841 /* Precisely one finite VP */
842 static void
843 box3d_set_new_z_orders_case1 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis fin_axis) {
844     Persp3D *persp = box3d_get_perspective(box);
845     NR::Point vp(persp3d_get_VP(persp, Box3D::toProj(fin_axis)).affine());
847     // note: in some of the case distinctions below we rely upon the fact that oaxis1 and oaxis2 are ordered
848     Box3D::Axis oaxis1 = Box3D::get_remaining_axes(fin_axis).first;
849     Box3D::Axis oaxis2 = Box3D::get_remaining_axes(fin_axis).second;
850     //g_print ("oaxis1  = %s, oaxis2  = %s\n", Box3D::string_from_axes(oaxis1), Box3D::string_from_axes(oaxis2));
851     int inside1 = 0;
852     int inside2 = 0;
853     inside1 = box3d_pt_lies_in_PL_sector (box, vp, 3, 3 ^ oaxis2, oaxis1);
854     inside2 = box3d_pt_lies_in_PL_sector (box, vp, 3, 3 ^ oaxis1, oaxis2);
855     //g_print ("inside1 = %d, inside2 = %d\n", inside1, inside2);
857     bool swapped = box3d_XY_axes_are_swapped(box);
859     //g_print ("2 infinite VPs; ");
860     //g_print ("finite axis: %s; ", Box3D::string_from_axes(fin_axis));
861     switch(central_axis) {
862         case Box3D::X:
863             if (!swapped) {
864                 //g_print ("central axis X (case a)");
865                 box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
866             } else {
867                 //if (inside2) {
868                     //g_print ("central axis X (case b)");
869                     box3d_aux_set_z_orders (z_orders, 5, 3, 1, 0, 2, 4);
870                 //} else {
871                     //g_print ("central axis X (case c)");
872                     //box3d_aux_set_z_orders (z_orders, 5, 3, 1, 2, 0, 4);
873                 //}
874             }
875             break;
876         case Box3D::Y:
877             if (inside2 > 0) {
878                 //g_print ("central axis Y (case a)");
879                 box3d_aux_set_z_orders (z_orders, 1, 2, 3, 0, 5, 4);
880             } else if (inside2 < 0) {
881                 //g_print ("central axis Y (case b)");
882                 box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5);
883             } else {
884                 if (!swapped) {
885                     //g_print ("central axis Y (case c1)");
886                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
887                 } else {
888                     //g_print ("central axis Y (case c2)");
889                     box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
890                 }
891             }
892             break;
893         case Box3D::Z:
894             if (inside2) {
895                 if (!swapped) {
896                     //g_print ("central axis Z (case a1)");
897                     box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 4, 5);
898                 } else {
899                     //g_print ("central axis Z (case a2)");
900                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 1, 2);
901                 }
902             } else if (inside1) {
903                 if (!swapped) {
904                     //g_print ("central axis Z (case b1)");
905                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
906                 } else {
907                     //g_print ("central axis Z (case b2)");
908                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2);
909                     //box3d_aux_set_z_orders (z_orders, 5, 3, 0, 1, 2, 4);
910                 }
911             } else {
912                 // "regular" case
913                 if (!swapped) {
914                     //g_print ("central axis Z (case c1)");
915                     box3d_aux_set_z_orders (z_orders, 0, 1, 2, 5, 4, 3);
916                 } else {
917                     //g_print ("central axis Z (case c2)");
918                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 2, 1);
919                     //box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 2, 1);
920                 }
921             }
922             break;
923         case Box3D::NONE:
924             if (!swapped) {
925                 //g_print ("central axis NONE (case a)");
926                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 5, 0, 1);
927             } else {
928                 //g_print ("central axis NONE (case b)");
929                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 3, 2, 4);
930                 //box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
931             }
932             break;
933         default:
934             g_assert_not_reached();
935     }
936     /**
937     if (swapped) {
938         g_print ("; swapped");
939     }
940     g_print ("\n");
941     **/
944 /* Precisely 2 finite VPs */
945 static void
946 box3d_set_new_z_orders_case2 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis /*infinite_axis*/) {
947     Persp3D *persp = box3d_get_perspective(box);
949     NR::Point c3(box3d_get_corner_screen(box, 3));
950     NR::Point xdir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::X));
951     NR::Point ydir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::Y));
952     NR::Point zdir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::Z));
954     bool swapped = box3d_XY_axes_are_swapped(box);
956     int insidexy = box3d_VP_lies_in_PL_sector (box, Proj::X, 3, 3 ^ Box3D::Z, Box3D::Y);
957     int insidexz = box3d_VP_lies_in_PL_sector (box, Proj::X, 3, 3 ^ Box3D::Y, Box3D::Z);
959     int insideyx = box3d_VP_lies_in_PL_sector (box, Proj::Y, 3, 3 ^ Box3D::Z, Box3D::X);
960     int insideyz = box3d_VP_lies_in_PL_sector (box, Proj::Y, 3, 3 ^ Box3D::X, Box3D::Z);
962     int insidezx = box3d_VP_lies_in_PL_sector (box, Proj::Z, 3, 3 ^ Box3D::Y, Box3D::X);
963     int insidezy = box3d_VP_lies_in_PL_sector (box, Proj::Z, 3, 3 ^ Box3D::X, Box3D::Y);
965     //g_print ("Insides: xy = %d, xz = %d, yx = %d, yz = %d, zx = %d, zy = %d\n",
966     //         insidexy, insidexz, insideyx, insideyz, insidezx, insidezy);
967     (void)insidexz;
968     (void)insideyx;
969     (void)insidezx;
971     //g_print ("1 infinite VP; ");
972     switch(central_axis) {
973         case Box3D::X:
974             if (!swapped) {
975                 if (insidezy == -1) {
976                     //g_print ("central axis X (case a1)");
977                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
978                 } else if (insidexy == 1) {
979                     //g_print ("central axis X (case a2)");
980                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3);
981                 } else {
982                     //g_print ("central axis X (case a3)");
983                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
984                 }
985             } else {
986                 if (insideyz == -1) {
987                     //g_print ("central axis X (case b1)");
988                     box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4);
989                 } else {
990                     if (!swapped) {
991                         //g_print ("central axis X (case b2)");
992                         box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0);
993                     } else {
994                         //g_print ("central axis X (case b3)");
995                         box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4);
996                     }
997                 }
998             }
999             break;
1000         case Box3D::Y:
1001             if (!swapped) {
1002                 if (insideyz == 1) {
1003                     //g_print ("central axis Y (case a1)");
1004                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 0, 5, 4);
1005                 } else {
1006                     //g_print ("central axis Y (case a2)");
1007                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
1008                 }
1009             } else {
1010                 //g_print ("central axis Y (case b)");
1011                 box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
1012             }
1013             break;
1014         case Box3D::Z:
1015             if (!swapped) {
1016                 if (insidezy == 1) {
1017                     //g_print ("central axis Z (case a1)");
1018                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 3, 5);
1019                 } else if (insidexy == -1) {
1020                     //g_print ("central axis Z (case a2)");
1021                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 4, 3);
1022                 } else {
1023                     //g_print ("central axis Z (case a3)");
1024                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 5, 3, 4);
1025                 }
1026             } else {
1027                 //g_print ("central axis Z (case b)");
1028                 box3d_aux_set_z_orders (z_orders, 3, 4, 5, 1, 0, 2);
1029             }
1030             break;
1031         case Box3D::NONE:
1032             if (!swapped) {
1033                 //g_print ("central axis NONE (case a)");
1034                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
1035             } else {
1036                 //g_print ("central axis NONE (case b)");
1037                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2);
1038             }
1039             break;
1040         default:
1041             g_assert_not_reached();
1042             break;
1043     }
1044     /**
1045     if (swapped) {
1046         g_print ("; swapped");
1047     }
1048     g_print ("\n");
1049     **/
1052 /*
1053  * It can happen that during dragging the box is everted.
1054  * In this case the opposite sides in this direction need to be swapped
1055  */
1056 static Box3D::Axis
1057 box3d_everted_directions (SPBox3D *box) {
1058     Box3D::Axis ev = Box3D::NONE;
1060     box->orig_corner0.normalize();
1061     box->orig_corner7.normalize();
1063     if (box->orig_corner0[Proj::X] < box->orig_corner7[Proj::X])
1064         ev = (Box3D::Axis) (ev ^ Box3D::X);
1065     if (box->orig_corner0[Proj::Y] < box->orig_corner7[Proj::Y])
1066         ev = (Box3D::Axis) (ev ^ Box3D::Y);
1067     if (box->orig_corner0[Proj::Z] > box->orig_corner7[Proj::Z]) // FIXME: Remove the need to distinguish signs among the cases
1068         ev = (Box3D::Axis) (ev ^ Box3D::Z);
1070     return ev;
1073 static void
1074 box3d_swap_sides(int z_orders[6], Box3D::Axis axis) {
1075     int pos1 = -1;
1076     int pos2 = -1;
1078     for (int i = 0; i < 6; ++i) {
1079         if (!(Box3D::int_to_face(z_orders[i]) & axis)) {
1080             if (pos1 == -1) {
1081                 pos1 = i;
1082             } else {
1083                 pos2 = i;
1084                 break;
1085             }
1086         }
1087     }
1089     int tmp = z_orders[pos1];
1090     z_orders[pos1] = z_orders[pos2];
1091     z_orders[pos2] = tmp;
1095 bool
1096 box3d_recompute_z_orders (SPBox3D *box) {
1097     Persp3D *persp = box3d_get_perspective(box);
1099     //g_return_val_if_fail(persp, false);
1100     if (!persp)
1101         return false;
1103     int z_orders[6];
1105     NR::Point c3(box3d_get_corner_screen(box, 3));
1107     // determine directions from corner3 to the VPs
1108     int num_finite = 0;
1109     Box3D::Axis axis_finite = Box3D::NONE;
1110     Box3D::Axis axis_infinite = Box3D::NONE;
1111     NR::Point dirs[3];
1112     for (int i = 0; i < 3; ++i) {
1113         dirs[i] = persp3d_get_PL_dir_from_pt(persp, c3, Box3D::toProj(Box3D::axes[i]));
1114         if (persp3d_VP_is_finite(persp, Proj::axes[i])) {
1115             num_finite++;
1116             axis_finite = Box3D::axes[i];
1117         } else {
1118             axis_infinite = Box3D::axes[i];
1119         }
1120     }
1122     // determine the "central" axis (if there is one)
1123     Box3D::Axis central_axis = Box3D::NONE;
1124     if(Box3D::lies_in_sector(dirs[0], dirs[1], dirs[2])) {
1125         central_axis = Box3D::Z;
1126     } else if(Box3D::lies_in_sector(dirs[1], dirs[2], dirs[0])) {
1127         central_axis = Box3D::X;
1128     } else if(Box3D::lies_in_sector(dirs[2], dirs[0], dirs[1])) {
1129         central_axis = Box3D::Y;
1130     }
1132     switch (num_finite) {
1133         case 0:
1134             // TODO: Remark: In this case (and maybe one of the others, too) the z-orders for all boxes
1135             //               coincide, hence only need to be computed once in a more central location.
1136             box3d_set_new_z_orders_case0(box, z_orders, central_axis);
1137             break;
1138         case 1:
1139             box3d_set_new_z_orders_case1(box, z_orders, central_axis, axis_finite);
1140             break;
1141         case 2:
1142         case 3:
1143             box3d_set_new_z_orders_case2(box, z_orders, central_axis, axis_infinite);
1144             break;
1145         default:
1146         /*
1147          * For each VP F, check wether the half-line from the corner3 to F crosses the line segment
1148          * joining the other two VPs. If this is the case, it determines the "central" corner from
1149          * which the visible sides can be deduced. Otherwise, corner3 is the central corner.
1150          */
1151         // FIXME: We should eliminate the use of NR::Point altogether
1152         Box3D::Axis central_axis = Box3D::NONE;
1153         NR::Point vp_x = persp3d_get_VP(persp, Proj::X).affine();
1154         NR::Point vp_y = persp3d_get_VP(persp, Proj::Y).affine();
1155         NR::Point vp_z = persp3d_get_VP(persp, Proj::Z).affine();
1156         Geom::Point vpx(vp_x[NR::X], vp_x[NR::Y]);
1157         Geom::Point vpy(vp_y[NR::X], vp_y[NR::Y]);
1158         Geom::Point vpz(vp_z[NR::X], vp_z[NR::Y]);
1160         NR::Point c3 = box3d_get_corner_screen(box, 3);
1161         Geom::Point corner3(c3[NR::X], c3[NR::Y]);
1163         if (box3d_half_line_crosses_joining_line (corner3, vpx, vpy, vpz)) {
1164             central_axis = Box3D::X;
1165         } else if (box3d_half_line_crosses_joining_line (corner3, vpy, vpz, vpx)) {
1166             central_axis = Box3D::Y;
1167         } else if (box3d_half_line_crosses_joining_line (corner3, vpz, vpx, vpy)) {
1168             central_axis = Box3D::Z;
1169         }
1170         //g_print ("Crossing: %s\n", Box3D::string_from_axes(central_axis));
1172         unsigned int central_corner = 3 ^ central_axis;
1173         if (central_axis == Box3D::Z) {
1174             central_corner = central_corner ^ Box3D::XYZ;
1175         }
1176         if (box3d_XY_axes_are_swapped(box)) {
1177             //g_print ("Axes X and Y are swapped\n");
1178             central_corner = central_corner ^ Box3D::XYZ;
1179         }
1181         NR::Point c1(box3d_get_corner_screen(box, 1));
1182         NR::Point c2(box3d_get_corner_screen(box, 2));
1183         NR::Point c7(box3d_get_corner_screen(box, 7));
1185         Geom::Point corner1(c1[NR::X], c1[NR::Y]);
1186         Geom::Point corner2(c2[NR::X], c2[NR::Y]);
1187         Geom::Point corner7(c7[NR::X], c7[NR::Y]);
1188         // FIXME: At present we don't use the information about central_corner computed above.
1189         switch (central_axis) {
1190             case Box3D::Y:
1191                 if (!box3d_half_line_crosses_joining_line(vpz, vpy, corner3, corner2)) {
1192                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
1193                 } else {
1194                     // degenerate case
1195                     //g_print ("Degenerate case #1\n");
1196                     box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 5, 4);
1197                 }
1198                 break;
1200             case Box3D::Z:
1201                 if (box3d_half_line_crosses_joining_line(vpx, vpz, corner3, corner1)) {
1202                     // degenerate case
1203                     //g_print ("Degenerate case #2\n");
1204                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
1205                 } else if (box3d_half_line_crosses_joining_line(vpx, vpy, corner3, corner7)) {
1206                     // degenerate case
1207                     //g_print ("Degenerate case #3\n");
1208                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 3, 4);
1209                 } else {
1210                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 3, 4, 5);
1211                 }
1212                 break;
1214             case Box3D::X:
1215                 if (box3d_half_line_crosses_joining_line(vpz, vpx, corner3, corner1)) {
1216                     // degenerate case
1217                     //g_print ("Degenerate case #4\n");
1218                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 5, 3);
1219                 } else {
1220                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3);
1221                 }
1222                 break;
1224             case Box3D::NONE:
1225                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
1226                 break;
1228             default:
1229                 g_assert_not_reached();
1230                 break;
1231         } // end default case
1232     }
1234     // TODO: If there are still errors in z-orders of everted boxes, we need to choose a variable corner
1235     //       instead of the hard-coded corner #3 in the computations above
1236     Box3D::Axis ev = box3d_everted_directions(box);
1237     for (int i = 0; i < 3; ++i) {
1238         if (ev & Box3D::axes[i]) {
1239             box3d_swap_sides(z_orders, Box3D::axes[i]);
1240         }
1241     }
1243     // Check whether anything actually changed
1244     for (int i = 0; i < 6; ++i) {
1245         if (box->z_orders[i] != z_orders[i]) {
1246             for (int j = i; j < 6; ++j) {
1247                 box->z_orders[j] = z_orders[j];
1248             }
1249             return true;
1250         }
1251     }
1252     return false;
1255 static std::map<int, Box3DSide *>
1256 box3d_get_sides (SPBox3D *box) {
1257     std::map<int, Box3DSide *> sides;
1258     for (SPObject *side = sp_object_first_child(box); side != NULL; side = SP_OBJECT_NEXT(side)) {
1259         sides[Box3D::face_to_int(sp_repr_get_int_attribute(SP_OBJECT_REPR(side),
1260                                                            "inkscape:box3dsidetype", -1))] = SP_BOX3D_SIDE(side);
1261     }
1262     sides.erase(-1);
1263     return sides;
1267 // TODO: Check whether the box is everted in any direction and swap the sides opposite to this direction
1268 void
1269 box3d_set_z_orders (SPBox3D *box) {
1270     // For efficiency reasons, we only set the new z-orders if something really changed
1271     if (box3d_recompute_z_orders (box)) {
1272         std::map<int, Box3DSide *> sides = box3d_get_sides(box);
1273         std::map<int, Box3DSide *>::iterator side;
1274         for (unsigned int i = 0; i < 6; ++i) {
1275             side = sides.find(box->z_orders[i]);
1276             if (side != sides.end()) {
1277                 SP_ITEM((*side).second)->lowerToBottom();
1278             }
1279         }
1280         /**
1281         g_print ("Resetting z-orders: ");
1282         for (int i = 0; i < 6; ++i) {
1283             g_print ("%d ", box->z_orders[i]);
1284         }
1285         g_print ("\n");
1286         **/
1287     }
1290 /*
1291  * Auxiliary function for z-order recomputing:
1292  * Determines whether \a pt lies in the sector formed by the two PLs from the corners with IDs
1293  * \a i21 and \a id2 to the VP in direction \a axis. If the VP is infinite, we say that \a pt
1294  * lies in the sector if it lies between the two (parallel) PLs.
1295  * \ret *  0 if \a pt doesn't lie in the sector
1296  *      *  1 if \a pt lies in the sector and either VP is finite of VP is infinite and the direction
1297  *           from the edge between the two corners to \a pt points towards the VP
1298  *      * -1 otherwise
1299  */
1300 // TODO: Maybe it would be useful to have a similar method for projective points pt because then we
1301 //       can use it for VPs and perhaps merge the case distinctions during z-order recomputation.
1302 int
1303 box3d_pt_lies_in_PL_sector (SPBox3D const *box, NR::Point const &pt, int id1, int id2, Box3D::Axis axis) {
1304     Persp3D *persp = box3d_get_perspective(box);
1306     // the two corners
1307     NR::Point c1(box3d_get_corner_screen(box, id1));
1308     NR::Point c2(box3d_get_corner_screen(box, id2));
1310     int ret = 0;
1311     if (persp3d_VP_is_finite(persp, Box3D::toProj(axis))) {
1312         NR::Point vp(persp3d_get_VP(persp, Box3D::toProj(axis)).affine());
1313         NR::Point v1(c1 - vp);
1314         NR::Point v2(c2 - vp);
1315         NR::Point w(pt - vp);
1316         ret = static_cast<int>(Box3D::lies_in_sector(v1, v2, w));
1317         //g_print ("Case 0 - returning %d\n", ret);
1318     } else {
1319         Box3D::PerspectiveLine pl1(c1, Box3D::toProj(axis), persp);
1320         Box3D::PerspectiveLine pl2(c2, Box3D::toProj(axis), persp);
1321         if (pl1.lie_on_same_side(pt, c2) && pl2.lie_on_same_side(pt, c1)) {
1322             // test whether pt lies "towards" or "away from" the VP
1323             Box3D::Line edge(c1,c2);
1324             NR::Point c3(box3d_get_corner_screen(box, id1 ^ axis));
1325             if (edge.lie_on_same_side(pt, c3)) {
1326                 ret = 1;
1327             } else {
1328                 ret = -1;
1329             }
1330         }
1331         //g_print ("Case 1 - returning %d\n", ret);
1332     }
1333     return ret;
1336 int
1337 box3d_VP_lies_in_PL_sector (SPBox3D const *box, Proj::Axis vpdir, int id1, int id2, Box3D::Axis axis) {
1338     Persp3D *persp = box3d_get_perspective(box);
1340     if (!persp3d_VP_is_finite(persp, vpdir)) {
1341         return 0;
1342     } else {
1343         return box3d_pt_lies_in_PL_sector(box, persp3d_get_VP(persp, vpdir).affine(), id1, id2, axis);
1344     }
1347 /* swap the coordinates of corner0 and corner7 along the specified axis */
1348 static void
1349 box3d_swap_coords(SPBox3D *box, Proj::Axis axis, bool smaller = true) {
1350     box->orig_corner0.normalize();
1351     box->orig_corner7.normalize();
1352     if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) {
1353         double tmp = box->orig_corner0[axis];
1354         box->orig_corner0[axis] = box->orig_corner7[axis];
1355         box->orig_corner7[axis] = tmp;
1356     }
1357     // FIXME: Should we also swap the coordinates of save_corner0 and save_corner7?
1360 /* ensure that the coordinates of corner0 and corner7 are in the correct order (to prevent everted boxes) */
1361 void
1362 box3d_relabel_corners(SPBox3D *box) {
1363     box3d_swap_coords(box, Proj::X, false);
1364     box3d_swap_coords(box, Proj::Y, false);
1365     box3d_swap_coords(box, Proj::Z, true);
1368 static void
1369 box3d_check_for_swapped_coords(SPBox3D *box, Proj::Axis axis, bool smaller) {
1370     box->orig_corner0.normalize();
1371     box->orig_corner7.normalize();
1373     if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) {
1374         box->swapped = (Box3D::Axis) (box->swapped | Proj::toAffine(axis));
1375     } else {
1376         box->swapped = (Box3D::Axis) (box->swapped & ~Proj::toAffine(axis));
1377     }
1380 static void
1381 box3d_exchange_coords(SPBox3D *box) {
1382     box->orig_corner0.normalize();
1383     box->orig_corner7.normalize();
1385     for (int i = 0; i < 3; ++i) {
1386         if (box->swapped & Box3D::axes[i]) {
1387             double tmp = box->orig_corner0[i];
1388             box->orig_corner0[i] = box->orig_corner7[i];
1389             box->orig_corner7[i] = tmp;
1390         }
1391     }
1394 void
1395 box3d_check_for_swapped_coords(SPBox3D *box) {
1396     box3d_check_for_swapped_coords(box, Proj::X, false);
1397     box3d_check_for_swapped_coords(box, Proj::Y, false);
1398     box3d_check_for_swapped_coords(box, Proj::Z, true);
1400     box3d_exchange_coords(box);
1403 void
1404 box3d_add_to_selection(SPBox3D *box) {
1405     Persp3D *persp = box3d_get_perspective(box);
1406     g_return_if_fail(persp);
1407     persp3d_add_box_transform(persp, box);
1410 void
1411 box3d_remove_from_selection(SPBox3D *box) {
1412     Persp3D *persp = box3d_get_perspective(box);
1413     if (!persp) {
1414         /* this can happen if a box is deleted through undo and the persp_ref is already detached;
1415            should we rebuild the boxes of each perspective in this case or is it safe to leave it alone? */
1416         return;
1417     }
1418     persp3d_remove_box_transform(persp, box);
1421 void
1422 box3d_mark_transformed(SPBox3D *box) {
1423     Persp3D *persp = box3d_get_perspective(box);
1424     g_return_if_fail(persp);
1425     persp3d_set_box_transformed(persp, box, true);
1428 Persp3D *
1429 box3d_get_perspective(SPBox3D const *box) {
1430     return box->persp_ref->getObject();
1433 void
1434 box3d_switch_perspectives(SPBox3D *box, Persp3D *old_persp, Persp3D *new_persp, bool recompute_corners) {
1435     if (recompute_corners) {
1436         box->orig_corner0.normalize();
1437         box->orig_corner7.normalize();
1438         double z0 = box->orig_corner0[Proj::Z];
1439         double z7 = box->orig_corner7[Proj::Z];
1440         NR::Point corner0_screen = box3d_get_corner_screen(box, 0);
1441         NR::Point corner7_screen = box3d_get_corner_screen(box, 7);
1443         box->orig_corner0 = new_persp->tmat.preimage(corner0_screen, z0, Proj::Z);
1444         box->orig_corner7 = new_persp->tmat.preimage(corner7_screen, z7, Proj::Z);
1445     }
1447     persp3d_remove_box (old_persp, box);
1448     persp3d_add_box (new_persp, box);
1450     persp3d_remove_box_transform (old_persp, box);
1451     persp3d_add_box_transform (new_persp, box);
1453     gchar *href = g_strdup_printf("#%s", SP_OBJECT_REPR(new_persp)->attribute("id"));
1454     SP_OBJECT_REPR(box)->setAttribute("inkscape:perspectiveID", href);
1455     g_free(href);
1458 /* Converts the 3D box to an ordinary SPGroup, adds it to the XML tree at the same position as
1459    the original box and deletes the latter */
1460 // TODO: Copy over all important attributes (see sp_selected_item_to_curved_repr() for an example)
1461 SPGroup *
1462 box3d_convert_to_group(SPBox3D *box) {
1463     SPDocument *doc = SP_OBJECT_DOCUMENT(box);
1464     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
1466     // remember position of the box
1467     int pos = SP_OBJECT_REPR(box)->position();
1469     // create a new group and add the sides (converted to ordinary paths) as its children
1470     Inkscape::XML::Node *grepr = xml_doc->createElement("svg:g");
1472     Inkscape::XML::Node *repr;
1473     for (SPObject *child = sp_object_first_child(SP_OBJECT(box)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
1474         if (SP_IS_BOX3D_SIDE(child)) {
1475             repr = box3d_side_convert_to_path(SP_BOX3D_SIDE(child));
1476             grepr->appendChild(repr);
1477         } else {
1478             g_warning("Non-side object encountered as child of a 3D box.\n");
1479         }
1480     }
1482     // add the new group to the box's parent and set remembered position
1483     SPObject *parent = SP_OBJECT_PARENT(box);
1484     SP_OBJECT_REPR(parent)->appendChild(grepr);
1485     grepr->setPosition(pos);
1487     SP_OBJECT(box)->deleteObject(true);
1489     return SP_GROUP(doc->getObjectByRepr(grepr));
1492 static void
1493 box3d_push_back_corner_pair(SPBox3D *box, std::list<std::pair<Geom::Point, Geom::Point> > &pts, int c1, int c2) {
1494     pts.push_back(std::make_pair(box3d_get_corner_screen(box, c1).to_2geom(),
1495                                  box3d_get_corner_screen(box, c2).to_2geom()));
1498 void
1499 box3d_convert_to_guides(SPBox3D *box, bool write_undo) {
1500     if (prefs_get_int_attribute("tools.shapes.3dbox", "convertguides", 1) == 0) {
1501         sp_item_convert_to_guides(SP_ITEM(box));
1502         return;
1503     }
1505     SPDocument *doc = SP_OBJECT_DOCUMENT(box);
1506     //SPDesktop *desktop = inkscape_active_desktop();
1507     //Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
1509     std::list<std::pair<Geom::Point, Geom::Point> > pts;
1511     /* perspective lines in X direction */
1512     box3d_push_back_corner_pair(box, pts, 0, 1);
1513     box3d_push_back_corner_pair(box, pts, 2, 3);
1514     box3d_push_back_corner_pair(box, pts, 4, 5);
1515     box3d_push_back_corner_pair(box, pts, 6, 7);
1517     /* perspective lines in Y direction */
1518     box3d_push_back_corner_pair(box, pts, 0, 2);
1519     box3d_push_back_corner_pair(box, pts, 1, 3);
1520     box3d_push_back_corner_pair(box, pts, 4, 6);
1521     box3d_push_back_corner_pair(box, pts, 5, 7);
1523     /* perspective lines in Z direction */
1524     box3d_push_back_corner_pair(box, pts, 0, 4);
1525     box3d_push_back_corner_pair(box, pts, 1, 5);
1526     box3d_push_back_corner_pair(box, pts, 2, 6);
1527     box3d_push_back_corner_pair(box, pts, 3, 7);
1529     sp_guide_pt_pairs_to_guides(doc, pts);
1531     SP_OBJECT(box)->deleteObject(true);
1533     if (write_undo) {
1534         sp_document_done(doc, SP_VERB_CONTEXT_3DBOX, _("Convert to guides"));
1535     }
1538 /*
1539   Local Variables:
1540   mode:c++
1541   c-file-style:"stroustrup"
1542   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1543   indent-tabs-mode:nil
1544   fill-column:99
1545   End:
1546 */
1547 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :