Code

Use the line intersection routines in 2geom/line.h instead of the deprecated ones...
[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/line.h>
35 #include "sp-guide.h"
36 #include "sp-namedview.h"
37 #include "preferences.h"
39 #include "desktop.h"
40 #include "desktop-handles.h"
41 #include "macros.h"
43 static void box3d_class_init(SPBox3DClass *klass);
44 static void box3d_init(SPBox3D *box3d);
46 static void box3d_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
47 static void box3d_release(SPObject *object);
48 static void box3d_set(SPObject *object, unsigned int key, const gchar *value);
49 static void box3d_update(SPObject *object, SPCtx *ctx, guint flags);
50 static Inkscape::XML::Node *box3d_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags);
52 static gchar *box3d_description(SPItem *item);
53 static Geom::Matrix box3d_set_transform(SPItem *item, Geom::Matrix const &xform);
54 static void box3d_convert_to_guides(SPItem *item);
56 static void box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box);
58 static SPGroupClass *parent_class;
60 static gint counter = 0;
62 GType
63 box3d_get_type(void)
64 {
65     static GType type = 0;
67     if (!type) {
68         GTypeInfo info = {
69             sizeof(SPBox3DClass),
70             NULL,   /* base_init */
71             NULL,   /* base_finalize */
72             (GClassInitFunc) box3d_class_init,
73             NULL,   /* class_finalize */
74             NULL,   /* class_data */
75             sizeof(SPBox3D),
76             16,     /* n_preallocs */
77             (GInstanceInitFunc) box3d_init,
78             NULL,   /* value_table */
79         };
80         type = g_type_register_static(SP_TYPE_GROUP, "SPBox3D", &info, (GTypeFlags) 0);
81     }
83     return type;
84 }
86 static void
87 box3d_class_init(SPBox3DClass *klass)
88 {
89     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
90     SPItemClass *item_class = (SPItemClass *) klass;
92     parent_class = (SPGroupClass *) g_type_class_ref(SP_TYPE_GROUP);
94     sp_object_class->build = box3d_build;
95     sp_object_class->release = box3d_release;
96     sp_object_class->set = box3d_set;
97     sp_object_class->write = box3d_write;
98     sp_object_class->update = box3d_update;
100     item_class->description = box3d_description;
101     item_class->set_transform = box3d_set_transform;
102     item_class->convert_to_guides = box3d_convert_to_guides;
105 static void
106 box3d_init(SPBox3D *box)
108     box->persp_href = NULL;
109     box->persp_ref = new Persp3DReference(SP_OBJECT(box));
112 static void
113 box3d_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
115     if (((SPObjectClass *) (parent_class))->build) {
116         ((SPObjectClass *) (parent_class))->build(object, document, repr);
117     }
119     SPBox3D *box = SP_BOX3D (object);
120     box->my_counter = counter++;
122     /* we initialize the z-orders to zero so that they are updated during dragging */
123     for (int i = 0; i < 6; ++i) {
124         box->z_orders[i] = 0;
125     }
127     // TODO: Create/link to the correct perspective
129     SPDocument *doc = SP_OBJECT_DOCUMENT(box);
130     if (!doc) {
131         g_print ("No document for the box!!!!\n");
132         return;
133     }
135     box->persp_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(box3d_ref_changed), box));
137     sp_object_read_attr(object, "inkscape:perspectiveID");
138     sp_object_read_attr(object, "inkscape:corner0");
139     sp_object_read_attr(object, "inkscape:corner7");
142 /**
143  * Virtual release of SPBox3D members before destruction.
144  */
145 static void
146 box3d_release(SPObject *object)
148     SPBox3D *box = (SPBox3D *) object;
150     if (box->persp_href) {
151         g_free(box->persp_href);
152     }
153     if (box->persp_ref) {
154         box->persp_ref->detach();
155         delete box->persp_ref;
156         box->persp_ref = NULL;
157     }
159     //persp3d_remove_box (box3d_get_perspective(box), box);
161     if (((SPObjectClass *) parent_class)->release)
162         ((SPObjectClass *) parent_class)->release(object);
165 static void
166 box3d_set(SPObject *object, unsigned int key, const gchar *value)
168     SPBox3D *box = SP_BOX3D(object);
170     switch (key) {
171         case SP_ATTR_INKSCAPE_BOX3D_PERSPECTIVE_ID:
172             if ( value && box->persp_href && ( strcmp(value, box->persp_href) == 0 ) ) {
173                 /* No change, do nothing. */
174             } else {
175                 if (box->persp_href) {
176                     g_free(box->persp_href);
177                     box->persp_href = NULL;
178                 }
179                 if (value) {
180                     box->persp_href = g_strdup(value);
182                     // Now do the attaching, which emits the changed signal.
183                     try {
184                         box->persp_ref->attach(Inkscape::URI(value));
185                     } catch (Inkscape::BadURIException &e) {
186                         g_warning("%s", e.what());
187                         box->persp_ref->detach();
188                     }
189                 } else {
190                     // Detach, which emits the changed signal.
191                     box->persp_ref->detach();
192                 }
193             }
195             // FIXME: Is the following update doubled by some call in either persp3d.cpp or vanishing_point_new.cpp?
196             box3d_position_set(box);
197             break;
198         case SP_ATTR_INKSCAPE_BOX3D_CORNER0:
199             if (value && strcmp(value, "0 : 0 : 0 : 0")) {
200                 box->orig_corner0 = Proj::Pt3(value);
201                 box->save_corner0 = box->orig_corner0;
202                 box3d_position_set(box);
203             }
204             break;
205         case SP_ATTR_INKSCAPE_BOX3D_CORNER7:
206             if (value && strcmp(value, "0 : 0 : 0 : 0")) {
207                 box->orig_corner7 = Proj::Pt3(value);
208                 box->save_corner7 = box->orig_corner7;
209                 box3d_position_set(box);
210             }
211             break;
212         default:
213             if (((SPObjectClass *) (parent_class))->set) {
214                 ((SPObjectClass *) (parent_class))->set(object, key, value);
215             }
216             break;
217     }
220 /**
221  * Gets called when (re)attached to another perspective.
222  */
223 static void
224 box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box)
226     if (old_ref) {
227         sp_signal_disconnect_by_data(old_ref, box);
228         persp3d_remove_box (SP_PERSP3D(old_ref), box);
229         /* Note: This sometimes leads to attempts to remove boxes twice from the list of selected/transformed
230            boxes in a perspectives, but this should be uncritical. */
231         persp3d_remove_box_transform (SP_PERSP3D(old_ref), box);
232     }
233     if ( SP_IS_PERSP3D(ref) && ref != box ) // FIXME: Comparisons sane?
234     {
235         persp3d_add_box (SP_PERSP3D(ref), box);
236         /* Note: This sometimes leads to attempts to add boxes twice to the list of selected/transformed
237            boxes in a perspectives, but this should be uncritical. */
238         persp3d_add_box_transform (SP_PERSP3D(ref), box);
239     }
242 static void
243 box3d_update(SPObject *object, SPCtx *ctx, guint flags)
245     if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) {
247         /* FIXME?: Perhaps the display updates of box sides should be instantiated from here, but this
248            causes evil update loops so it's all done from box3d_position_set, which is called from
249            various other places (like the handlers in object-edit.cpp, vanishing-point.cpp, etc. */
251     }
253     // Invoke parent method
254     if (((SPObjectClass *) (parent_class))->update)
255         ((SPObjectClass *) (parent_class))->update(object, ctx, flags);
259 static Inkscape::XML::Node *box3d_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
261     SPBox3D *box = SP_BOX3D(object);
263     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
264         // this is where we end up when saving as plain SVG (also in other circumstances?)
265         // thus we don' set "sodipodi:type" so that the box is only saved as an ordinary svg:g
266         repr = xml_doc->createElement("svg:g");
267     }
269     if (flags & SP_OBJECT_WRITE_EXT) {
271         if (box->persp_href) {
272             repr->setAttribute("inkscape:perspectiveID", box->persp_href);
273         } else {
274             /* box is not yet linked to a perspective; use the document's current perspective */
275             SPDocument *doc = SP_OBJECT_DOCUMENT(object);
276             if (box->persp_ref->getURI()) {
277                 gchar *uri_string = box->persp_ref->getURI()->toString();
278                 repr->setAttribute("inkscape:perspectiveID", uri_string);
279                 g_free(uri_string);
280             } else {
281                 Inkscape::XML::Node *persp_repr = SP_OBJECT_REPR(doc->current_persp3d);
282                 const gchar *persp_id = persp_repr->attribute("id");
283                 gchar *href = g_strdup_printf("#%s", persp_id);
284                 repr->setAttribute("inkscape:perspectiveID", href);
285                 g_free(href);
286             }
287         }
289         gchar *coordstr0 = box->orig_corner0.coord_string();
290         gchar *coordstr7 = box->orig_corner7.coord_string();
291         repr->setAttribute("inkscape:corner0", coordstr0);
292         repr->setAttribute("inkscape:corner7", coordstr7);
293         g_free(coordstr0);
294         g_free(coordstr7);
296         box->orig_corner0.normalize();
297         box->orig_corner7.normalize();
299         box->save_corner0 = box->orig_corner0;
300         box->save_corner7 = box->orig_corner7;
301     }
303     if (((SPObjectClass *) (parent_class))->write) {
304         ((SPObjectClass *) (parent_class))->write(object, xml_doc, repr, flags);
305     }
307     return repr;
310 static gchar *
311 box3d_description(SPItem *item)
313     g_return_val_if_fail(SP_IS_BOX3D(item), NULL);
315     return g_strdup(_("<b>3D Box</b>"));
318 void
319 box3d_position_set (SPBox3D *box)
321     /* This draws the curve and calls requestDisplayUpdate() for each side (the latter is done in
322        box3d_side_position_set() to avoid update conflicts with the parent box) */
323     for (SPObject *child = sp_object_first_child(SP_OBJECT (box)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
324         if (SP_IS_BOX3D_SIDE(child))
325             box3d_side_position_set(SP_BOX3D_SIDE(child));
326     }
329 static Geom::Matrix
330 box3d_set_transform(SPItem *item, Geom::Matrix const &xform)
332     SPBox3D *box = SP_BOX3D(item);
334     /* check whether we need to unlink any boxes from their perspectives */
335     Persp3D *persp = box3d_get_perspective(box);
336     Persp3D *transf_persp;
338     if (!persp3d_has_all_boxes_in_selection (persp)) {
339         std::list<SPBox3D *> selboxes = sp_desktop_selection(inkscape_active_desktop())->box3DList();
341         /* create a new perspective as a copy of the current one and link the selected boxes to it */
342         transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp);
344         for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b) {
345             box3d_switch_perspectives(*b, persp, transf_persp);
346         }
347     } else {
348         transf_persp = persp;
349     }
351     /* only transform the perspective once, even if it has several selected boxes */
352     if(!persp3d_was_transformed (transf_persp)) {
353         /* concatenate the affine transformation with the perspective mapping; this
354            function also triggers repr updates of boxes and the perspective itself */
355         persp3d_apply_affine_transformation(transf_persp, xform);
356     }
358     box3d_mark_transformed(box);
360     if (persp3d_all_transformed(transf_persp)) {
361         /* all boxes were transformed; make perspective sensitive for further transformations */
362         persp3d_unset_transforms(transf_persp);
363     }
365     Geom::Matrix ret(Geom::Matrix(xform).without_translation());
366     gdouble const sw = hypot(ret[0], ret[1]);
367     gdouble const sh = hypot(ret[2], ret[3]);
369     for (SPObject *child = sp_object_first_child(box); child != NULL; child = SP_OBJECT_NEXT(child)) {
370         if (SP_IS_ITEM(child)) {
371             SPItem *childitem = SP_ITEM(child);
373             // Adjust stroke width
374             sp_item_adjust_stroke(childitem, sqrt(fabs(sw * sh)));
376             // Adjust pattern fill
377             sp_item_adjust_pattern(childitem, xform);
379             // Adjust gradient fill
380             sp_item_adjust_gradient(childitem, xform);
382             // Adjust LPE
383             sp_item_adjust_livepatheffect(childitem, xform);
384         }
385     }
387     return Geom::identity();
390 Proj::Pt3
391 box3d_get_proj_corner (guint id, Proj::Pt3 const &c0, Proj::Pt3 const &c7) {
392     return Proj::Pt3 ((id & Box3D::X) ? c7[Proj::X] : c0[Proj::X],
393                       (id & Box3D::Y) ? c7[Proj::Y] : c0[Proj::Y],
394                       (id & Box3D::Z) ? c7[Proj::Z] : c0[Proj::Z],
395                       1.0);
398 Proj::Pt3
399 box3d_get_proj_corner (SPBox3D const *box, guint id) {
400     return Proj::Pt3 ((id & Box3D::X) ? box->orig_corner7[Proj::X] : box->orig_corner0[Proj::X],
401                       (id & Box3D::Y) ? box->orig_corner7[Proj::Y] : box->orig_corner0[Proj::Y],
402                       (id & Box3D::Z) ? box->orig_corner7[Proj::Z] : box->orig_corner0[Proj::Z],
403                       1.0);
406 Geom::Point
407 box3d_get_corner_screen (SPBox3D const *box, guint id, bool item_coords) {
408     Proj::Pt3 proj_corner (box3d_get_proj_corner (box, id));
409     if (!box3d_get_perspective(box)) {
410         return Geom::Point (NR_HUGE, NR_HUGE);
411     }
412     Geom::Matrix const i2d (sp_item_i2d_affine (SP_ITEM(box)));
413     if (item_coords) {
414         return box3d_get_perspective(box)->tmat.image(proj_corner).affine() * i2d.inverse();
415     } else {
416         return box3d_get_perspective(box)->tmat.image(proj_corner).affine();
417     }
420 Proj::Pt3
421 box3d_get_proj_center (SPBox3D *box) {
422     box->orig_corner0.normalize();
423     box->orig_corner7.normalize();
424     return Proj::Pt3 ((box->orig_corner0[Proj::X] + box->orig_corner7[Proj::X]) / 2,
425                       (box->orig_corner0[Proj::Y] + box->orig_corner7[Proj::Y]) / 2,
426                       (box->orig_corner0[Proj::Z] + box->orig_corner7[Proj::Z]) / 2,
427                       1.0);
430 Geom::Point
431 box3d_get_center_screen (SPBox3D *box) {
432     Proj::Pt3 proj_center (box3d_get_proj_center (box));
433     if (!box3d_get_perspective(box)) {
434         return Geom::Point (NR_HUGE, NR_HUGE);
435     }
436     Geom::Matrix const i2d (sp_item_i2d_affine (SP_ITEM(box)));
437     return box3d_get_perspective(box)->tmat.image(proj_center).affine() * i2d.inverse();
440 /*
441  * To keep the snappoint from jumping randomly between the two lines when the mouse pointer is close to
442  * their intersection, we remember the last snapped line and keep snapping to this specific line as long
443  * as the distance from the intersection to the mouse pointer is less than remember_snap_threshold.
444  */
446 // Should we make the threshold settable in the preferences?
447 static double remember_snap_threshold = 30;
448 static guint remember_snap_index = 0;
450 static Proj::Pt3
451 box3d_snap (SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &start_pt) {
452     double z_coord = start_pt[Proj::Z];
453     double diff_x = box->save_corner7[Proj::X] - box->save_corner0[Proj::X];
454     double diff_y = box->save_corner7[Proj::Y] - box->save_corner0[Proj::Y];
455     double x_coord = start_pt[Proj::X];
456     double y_coord = start_pt[Proj::Y];
457     Proj::Pt3 A_proj (x_coord,          y_coord,          z_coord, 1.0);
458     Proj::Pt3 B_proj (x_coord + diff_x, y_coord,          z_coord, 1.0);
459     Proj::Pt3 C_proj (x_coord + diff_x, y_coord + diff_y, z_coord, 1.0);
460     Proj::Pt3 D_proj (x_coord,          y_coord + diff_y, z_coord, 1.0);
461     Proj::Pt3 E_proj (x_coord - diff_x, y_coord + diff_y, z_coord, 1.0);
463     Persp3D *persp = box3d_get_perspective(box);
464     Geom::Point A = persp->tmat.image(A_proj).affine();
465     Geom::Point B = persp->tmat.image(B_proj).affine();
466     Geom::Point C = persp->tmat.image(C_proj).affine();
467     Geom::Point D = persp->tmat.image(D_proj).affine();
468     Geom::Point E = persp->tmat.image(E_proj).affine();
469     Geom::Point pt = persp->tmat.image(pt_proj).affine();
471     // TODO: Replace these lines between corners with lines from a corner to a vanishing point
472     //       (this might help to prevent rounding errors if the box is small)
473     Box3D::Line pl1(A, B);
474     Box3D::Line pl2(A, D);
475     Box3D::Line diag1(A, (id == -1 || (!(id & Box3D::X) == !(id & Box3D::Y))) ? C : E);
476     Box3D::Line diag2(A, E); // diag2 is only taken into account if id equals -1, i.e., if we are snapping the center
478     int num_snap_lines = (id != -1) ? 3 : 4;
479     Geom::Point snap_pts[num_snap_lines];
481     snap_pts[0] = pl1.closest_to (pt);
482     snap_pts[1] = pl2.closest_to (pt);
483     snap_pts[2] = diag1.closest_to (pt);
484     if (id == -1) {
485         snap_pts[3] = diag2.closest_to (pt);
486     }
488     gdouble const zoom = inkscape_active_desktop()->current_zoom();
490     // determine the distances to all potential snapping points
491     double snap_dists[num_snap_lines];
492     for (int i = 0; i < num_snap_lines; ++i) {
493         snap_dists[i] = Geom::L2 (snap_pts[i] - pt) * zoom;
494     }
496     // while we are within a given tolerance of the starting point,
497     // keep snapping to the same point to avoid jumping
498     bool within_tolerance = true;
499     for (int i = 0; i < num_snap_lines; ++i) {
500         if (snap_dists[i] > remember_snap_threshold) {
501             within_tolerance = false;
502             break;
503         }
504     }
506     // find the closest snapping point
507     int snap_index = -1;
508     double snap_dist = NR_HUGE;
509     for (int i = 0; i < num_snap_lines; ++i) {
510         if (snap_dists[i] < snap_dist) {
511             snap_index = i;
512             snap_dist = snap_dists[i];
513         }
514     }
516     // snap to the closest point (or the previously remembered one
517     // if we are within tolerance of the starting point)
518     Geom::Point result;
519     if (within_tolerance) {
520         result = snap_pts[remember_snap_index];
521     } else {
522         remember_snap_index = snap_index;
523         result = snap_pts[snap_index];
524     }
525     return box3d_get_perspective(box)->tmat.preimage (result, z_coord, Proj::Z);
528 void
529 box3d_set_corner (SPBox3D *box, const guint id, Geom::Point const &new_pos, const Box3D::Axis movement, bool constrained) {
530     g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ));
532     box->orig_corner0.normalize();
533     box->orig_corner7.normalize();
535     /* update corners 0 and 7 according to which handle was moved and to the axes of movement */
536     if (!(movement & Box3D::Z)) {
537         Proj::Pt3 pt_proj (box3d_get_perspective(box)->tmat.preimage (new_pos, (id < 4) ? box->orig_corner0[Proj::Z] :
538                                                                       box->orig_corner7[Proj::Z], Proj::Z));
539         if (constrained) {
540             pt_proj = box3d_snap (box, id, pt_proj, box3d_get_proj_corner (id, box->save_corner0, box->save_corner7));
541         }
543         // normalizing pt_proj is essential because we want to mingle affine coordinates
544         pt_proj.normalize();
545         box->orig_corner0 = Proj::Pt3 ((id & Box3D::X) ? box->save_corner0[Proj::X] : pt_proj[Proj::X],
546                                        (id & Box3D::Y) ? box->save_corner0[Proj::Y] : pt_proj[Proj::Y],
547                                        box->save_corner0[Proj::Z],
548                                        1.0);
549         box->orig_corner7 = Proj::Pt3 ((id & Box3D::X) ? pt_proj[Proj::X] : box->save_corner7[Proj::X],
550                                        (id & Box3D::Y) ? pt_proj[Proj::Y] : box->save_corner7[Proj::Y],
551                                        box->save_corner7[Proj::Z],
552                                        1.0);
553     } else {
554         Persp3D *persp = box3d_get_perspective(box);
555         Box3D::PerspectiveLine pl(persp->tmat.image(
556                                       box3d_get_proj_corner (id, box->save_corner0, box->save_corner7)).affine(),
557                                   Proj::Z, persp);
558         Geom::Point new_pos_snapped(pl.closest_to(new_pos));
559         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos_snapped,
560                                           box3d_get_proj_corner (box, id)[(movement & Box3D::Y) ? Proj::X : Proj::Y],
561                                           (movement & Box3D::Y) ? Proj::X : Proj::Y));
562         bool corner0_move_x = !(id & Box3D::X) && (movement & Box3D::X);
563         bool corner0_move_y = !(id & Box3D::Y) && (movement & Box3D::Y);
564         bool corner7_move_x =  (id & Box3D::X) && (movement & Box3D::X);
565         bool corner7_move_y =  (id & Box3D::Y) && (movement & Box3D::Y);
566         // normalizing pt_proj is essential because we want to mingle affine coordinates
567         pt_proj.normalize();
568         box->orig_corner0 = Proj::Pt3 (corner0_move_x ? pt_proj[Proj::X] : box->orig_corner0[Proj::X],
569                                        corner0_move_y ? pt_proj[Proj::Y] : box->orig_corner0[Proj::Y],
570                                        (id & Box3D::Z) ? box->orig_corner0[Proj::Z] : pt_proj[Proj::Z],
571                                        1.0);
572         box->orig_corner7 = Proj::Pt3 (corner7_move_x ? pt_proj[Proj::X] : box->orig_corner7[Proj::X],
573                                        corner7_move_y ? pt_proj[Proj::Y] : box->orig_corner7[Proj::Y],
574                                        (id & Box3D::Z) ? pt_proj[Proj::Z] : box->orig_corner7[Proj::Z],
575                                        1.0);
576     }
577     // FIXME: Should we update the box here? If so, how?
580 void box3d_set_center (SPBox3D *box, Geom::Point const &new_pos, Geom::Point const &old_pos, const Box3D::Axis movement, bool constrained) {
581     g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ));
583     box->orig_corner0.normalize();
584     box->orig_corner7.normalize();
586     Persp3D *persp = box3d_get_perspective(box);
587     if (!(movement & Box3D::Z)) {
588         double coord = (box->orig_corner0[Proj::Z] + box->orig_corner7[Proj::Z]) / 2;
589         double radx = (box->orig_corner7[Proj::X] - box->orig_corner0[Proj::X]) / 2;
590         double rady = (box->orig_corner7[Proj::Y] - box->orig_corner0[Proj::Y]) / 2;
592         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos, coord, Proj::Z));
593         if (constrained) {
594             Proj::Pt3 old_pos_proj (persp->tmat.preimage (old_pos, coord, Proj::Z));
595             old_pos_proj.normalize();
596             pt_proj = box3d_snap (box, -1, pt_proj, old_pos_proj);
597         }
598         // normalizing pt_proj is essential because we want to mingle affine coordinates
599         pt_proj.normalize();
600         box->orig_corner0 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] - radx : box->orig_corner0[Proj::X],
601                                        (movement & Box3D::Y) ? pt_proj[Proj::Y] - rady : box->orig_corner0[Proj::Y],
602                                        box->orig_corner0[Proj::Z],
603                                        1.0);
604         box->orig_corner7 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] + radx : box->orig_corner7[Proj::X],
605                                        (movement & Box3D::Y) ? pt_proj[Proj::Y] + rady : box->orig_corner7[Proj::Y],
606                                        box->orig_corner7[Proj::Z],
607                                        1.0);
608     } else {
609         double coord = (box->orig_corner0[Proj::X] + box->orig_corner7[Proj::X]) / 2;
610         double radz = (box->orig_corner7[Proj::Z] - box->orig_corner0[Proj::Z]) / 2;
612         Box3D::PerspectiveLine pl(old_pos, Proj::Z, persp);
613         Geom::Point new_pos_snapped(pl.closest_to(new_pos));
614         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos_snapped, coord, Proj::X));
616         /* normalizing pt_proj is essential because we want to mingle affine coordinates */
617         pt_proj.normalize();
618         box->orig_corner0 = Proj::Pt3 (box->orig_corner0[Proj::X],
619                                        box->orig_corner0[Proj::Y],
620                                        pt_proj[Proj::Z] - radz,
621                                        1.0);
622         box->orig_corner7 = Proj::Pt3 (box->orig_corner7[Proj::X],
623                                        box->orig_corner7[Proj::Y],
624                                        pt_proj[Proj::Z] + radz,
625                                        1.0);
626     }
629 /*
630  * Manipulates corner1 through corner4 to contain the indices of the corners
631  * from which the perspective lines in the direction of 'axis' emerge
632  */
633 void box3d_corners_for_PLs (const SPBox3D * box, Proj::Axis axis,
634                             Geom::Point &corner1, Geom::Point &corner2, Geom::Point &corner3, Geom::Point &corner4)
636     Persp3D *persp = box3d_get_perspective(box);
637     g_return_if_fail (persp);
638     //box->orig_corner0.normalize();
639     //box->orig_corner7.normalize();
640     double coord = (box->orig_corner0[axis] > box->orig_corner7[axis]) ?
641         box->orig_corner0[axis] :
642         box->orig_corner7[axis];
644     Proj::Pt3 c1, c2, c3, c4;
645     // FIXME: This can certainly be done more elegantly/efficiently than by a case-by-case analysis.
646     switch (axis) {
647         case Proj::X:
648             c1 = Proj::Pt3 (coord, box->orig_corner0[Proj::Y], box->orig_corner0[Proj::Z], 1.0);
649             c2 = Proj::Pt3 (coord, box->orig_corner7[Proj::Y], box->orig_corner0[Proj::Z], 1.0);
650             c3 = Proj::Pt3 (coord, box->orig_corner7[Proj::Y], box->orig_corner7[Proj::Z], 1.0);
651             c4 = Proj::Pt3 (coord, box->orig_corner0[Proj::Y], box->orig_corner7[Proj::Z], 1.0);
652             break;
653         case Proj::Y:
654             c1 = Proj::Pt3 (box->orig_corner0[Proj::X], coord, box->orig_corner0[Proj::Z], 1.0);
655             c2 = Proj::Pt3 (box->orig_corner7[Proj::X], coord, box->orig_corner0[Proj::Z], 1.0);
656             c3 = Proj::Pt3 (box->orig_corner7[Proj::X], coord, box->orig_corner7[Proj::Z], 1.0);
657             c4 = Proj::Pt3 (box->orig_corner0[Proj::X], coord, box->orig_corner7[Proj::Z], 1.0);
658             break;
659         case Proj::Z:
660             c1 = Proj::Pt3 (box->orig_corner7[Proj::X], box->orig_corner7[Proj::Y], coord, 1.0);
661             c2 = Proj::Pt3 (box->orig_corner7[Proj::X], box->orig_corner0[Proj::Y], coord, 1.0);
662             c3 = Proj::Pt3 (box->orig_corner0[Proj::X], box->orig_corner0[Proj::Y], coord, 1.0);
663             c4 = Proj::Pt3 (box->orig_corner0[Proj::X], box->orig_corner7[Proj::Y], coord, 1.0);
664             break;
665         default:
666             return;
667     }
668     corner1 = persp->tmat.image(c1).affine();
669     corner2 = persp->tmat.image(c2).affine();
670     corner3 = persp->tmat.image(c3).affine();
671     corner4 = persp->tmat.image(c4).affine();
674 /* Auxiliary function: Checks whether the half-line from A to B crosses the line segment joining C and D */
675 static bool
676 box3d_half_line_crosses_joining_line (Geom::Point const &A, Geom::Point const &B,
677                                       Geom::Point const &C, Geom::Point const &D) {
678     Geom::Point n0 = (B - A).ccw();
679     double d0 = dot(n0,A);
681     Geom::Point n1 = (D - C).ccw();
682     double d1 = dot(n1,C);
684     Geom::Line lineAB(A,B);
685     Geom::Line lineCD(C,D);
687     Geom::OptCrossing inters = Geom::OptCrossing(); // empty by default
688         try
689         {
690                 inters = Geom::intersection(lineAB, lineCD);
691         }
692         catch (Geom::InfiniteSolutions e)
693         {
694                 // We're probably dealing with parallel lines, so they don't really cross
695                 return false;
696         }
698     if (!inters) {
699         return false;
700     }
702     Geom::Point E = lineAB.pointAt((*inters).ta); // the point of intersection
704     if ((dot(C,n0) < d0) == (dot(D,n0) < d0)) {
705         // C and D lie on the same side of the line AB
706         return false;
707     }
708     if ((dot(A,n1) < d1) != (dot(B,n1) < d1)) {
709         // A and B lie on different sides of the line CD
710         return true;
711     } else if (Geom::distance(E,A) < Geom::distance(E,B)) {
712         // The line CD passes on the "wrong" side of A
713         return false;
714     }
716     // The line CD passes on the "correct" side of A
717     return true;
720 static bool
721 box3d_XY_axes_are_swapped (SPBox3D *box) {
722     Persp3D *persp = box3d_get_perspective(box);
723     g_return_val_if_fail(persp, false);
724     Box3D::PerspectiveLine l1(box3d_get_corner_screen(box, 3, false), Proj::X, persp);
725     Box3D::PerspectiveLine l2(box3d_get_corner_screen(box, 3, false), Proj::Y, persp);
726     Geom::Point v1(l1.direction());
727     Geom::Point v2(l2.direction());
728     v1.normalize();
729     v2.normalize();
731     return (v1[Geom::X]*v2[Geom::Y] - v1[Geom::Y]*v2[Geom::X] > 0);
734 static inline void
735 box3d_aux_set_z_orders (int z_orders[6], int a, int b, int c, int d, int e, int f) {
736     z_orders[0] = a;
737     z_orders[1] = b;
738     z_orders[2] = c;
739     z_orders[3] = d;
740     z_orders[4] = e;
741     z_orders[5] = f;
744 static inline void
745 box3d_swap_z_orders (int z_orders[6]) {
746     int tmp;
747     for (int i = 0; i < 3; ++i) {
748         tmp = z_orders[i];
749         z_orders[i] = z_orders[5-i];
750         z_orders[5-i] = tmp;
751     }
754 /*
755  * In standard perspective we have:
756  * 2 = front face
757  * 1 = top face
758  * 0 = left face
759  * 3 = right face
760  * 4 = bottom face
761  * 5 = rear face
762  */
764 /* All VPs infinite */
765 static void
766 box3d_set_new_z_orders_case0 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis) {
767     Persp3D *persp = box3d_get_perspective(box);
768     Geom::Point xdir(persp3d_get_infinite_dir(persp, Proj::X));
769     Geom::Point ydir(persp3d_get_infinite_dir(persp, Proj::Y));
770     Geom::Point zdir(persp3d_get_infinite_dir(persp, Proj::Z));
772     bool swapped = box3d_XY_axes_are_swapped(box);
774     switch(central_axis) {
775         case Box3D::X:
776             if (!swapped) {
777                 box3d_aux_set_z_orders (z_orders, 2, 0, 4, 1, 3, 5);
778             } else {
779                 box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0);
780             }
781             break;
782         case Box3D::Y:
783             if (!swapped) {
784                 box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5);
785             } else {
786                 box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
787             }
788             break;
789         case Box3D::Z:
790             if (!swapped) {
791                 box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
792             } else {
793                 box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2);
794             }
795             break;
796         case Box3D::NONE:
797             if (!swapped) {
798                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
799             } else {
800                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2);
801             }
802             break;
803         default:
804             g_assert_not_reached();
805             break;
806     }
809 /* Precisely one finite VP */
810 static void
811 box3d_set_new_z_orders_case1 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis fin_axis) {
812     Persp3D *persp = box3d_get_perspective(box);
813     Geom::Point vp(persp3d_get_VP(persp, Box3D::toProj(fin_axis)).affine());
815     // note: in some of the case distinctions below we rely upon the fact that oaxis1 and oaxis2 are ordered
816     Box3D::Axis oaxis1 = Box3D::get_remaining_axes(fin_axis).first;
817     Box3D::Axis oaxis2 = Box3D::get_remaining_axes(fin_axis).second;
818     int inside1 = 0;
819     int inside2 = 0;
820     inside1 = box3d_pt_lies_in_PL_sector (box, vp, 3, 3 ^ oaxis2, oaxis1);
821     inside2 = box3d_pt_lies_in_PL_sector (box, vp, 3, 3 ^ oaxis1, oaxis2);
823     bool swapped = box3d_XY_axes_are_swapped(box);
825     switch(central_axis) {
826         case Box3D::X:
827             if (!swapped) {
828                 box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
829             } else {
830                 box3d_aux_set_z_orders (z_orders, 5, 3, 1, 0, 2, 4);
831             }
832             break;
833         case Box3D::Y:
834             if (inside2 > 0) {
835                 box3d_aux_set_z_orders (z_orders, 1, 2, 3, 0, 5, 4);
836             } else if (inside2 < 0) {
837                 box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5);
838             } else {
839                 if (!swapped) {
840                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
841                 } else {
842                     box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
843                 }
844             }
845             break;
846         case Box3D::Z:
847             if (inside2) {
848                 if (!swapped) {
849                     box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 4, 5);
850                 } else {
851                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 1, 2);
852                 }
853             } else if (inside1) {
854                 if (!swapped) {
855                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
856                 } else {
857                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2);
858                 }
859             } else {
860                 // "regular" case
861                 if (!swapped) {
862                     box3d_aux_set_z_orders (z_orders, 0, 1, 2, 5, 4, 3);
863                 } else {
864                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 2, 1);
865                 }
866             }
867             break;
868         case Box3D::NONE:
869             if (!swapped) {
870                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 5, 0, 1);
871             } else {
872                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 3, 2, 4);
873             }
874             break;
875         default:
876             g_assert_not_reached();
877     }
880 /* Precisely 2 finite VPs */
881 static void
882 box3d_set_new_z_orders_case2 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis /*infinite_axis*/) {
883     Persp3D *persp = box3d_get_perspective(box);
885     Geom::Point c3(box3d_get_corner_screen(box, 3, false));
886     Geom::Point xdir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::X));
887     Geom::Point ydir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::Y));
888     Geom::Point zdir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::Z));
890     bool swapped = box3d_XY_axes_are_swapped(box);
892     int insidexy = box3d_VP_lies_in_PL_sector (box, Proj::X, 3, 3 ^ Box3D::Z, Box3D::Y);
893     //int insidexz = box3d_VP_lies_in_PL_sector (box, Proj::X, 3, 3 ^ Box3D::Y, Box3D::Z);
895     int insideyx = box3d_VP_lies_in_PL_sector (box, Proj::Y, 3, 3 ^ Box3D::Z, Box3D::X);
896     int insideyz = box3d_VP_lies_in_PL_sector (box, Proj::Y, 3, 3 ^ Box3D::X, Box3D::Z);
898     //int insidezx = box3d_VP_lies_in_PL_sector (box, Proj::Z, 3, 3 ^ Box3D::Y, Box3D::X);
899     int insidezy = box3d_VP_lies_in_PL_sector (box, Proj::Z, 3, 3 ^ Box3D::X, Box3D::Y);
901     switch(central_axis) {
902         case Box3D::X:
903             if (!swapped) {
904                 if (insidezy == -1) {
905                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
906                 } else if (insidexy == 1) {
907                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3);
908                 } else {
909                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
910                 }
911             } else {
912                 if (insideyz == -1) {
913                     box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4);
914                 } else {
915                     if (!swapped) {
916                         box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0);
917                     } else {
918                         if (insidexy == 0) {
919                             box3d_aux_set_z_orders (z_orders, 3, 5, 1, 0, 2, 4);
920                         } else {
921                             box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4);
922                         }
923                     }
924                 }
925             }
926             break;
927         case Box3D::Y:
928             if (!swapped) {
929                 if (insideyz == 1) {
930                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 0, 5, 4);
931                 } else {
932                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
933                 }
934             } else {
935                 if (insideyx == 1) {
936                     box3d_aux_set_z_orders (z_orders, 4, 0, 5, 1, 3, 2);
937                 } else {
938                     box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
939                 }
940             }
941             break;
942         case Box3D::Z:
943             if (!swapped) {
944                 if (insidezy == 1) {
945                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 3, 5);
946                 } else if (insidexy == -1) {
947                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 4, 3);
948                 } else {
949                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 5, 3, 4);
950                 }
951             } else {
952                 box3d_aux_set_z_orders (z_orders, 3, 4, 5, 1, 0, 2);
953             }
954             break;
955         case Box3D::NONE:
956             if (!swapped) {
957                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
958             } else {
959                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2);
960             }
961             break;
962         default:
963             g_assert_not_reached();
964             break;
965     }
968 /*
969  * It can happen that during dragging the box is everted.
970  * In this case the opposite sides in this direction need to be swapped
971  */
972 static Box3D::Axis
973 box3d_everted_directions (SPBox3D *box) {
974     Box3D::Axis ev = Box3D::NONE;
976     box->orig_corner0.normalize();
977     box->orig_corner7.normalize();
979     if (box->orig_corner0[Proj::X] < box->orig_corner7[Proj::X])
980         ev = (Box3D::Axis) (ev ^ Box3D::X);
981     if (box->orig_corner0[Proj::Y] < box->orig_corner7[Proj::Y])
982         ev = (Box3D::Axis) (ev ^ Box3D::Y);
983     if (box->orig_corner0[Proj::Z] > box->orig_corner7[Proj::Z]) // FIXME: Remove the need to distinguish signs among the cases
984         ev = (Box3D::Axis) (ev ^ Box3D::Z);
986     return ev;
989 static void
990 box3d_swap_sides(int z_orders[6], Box3D::Axis axis) {
991     int pos1 = -1;
992     int pos2 = -1;
994     for (int i = 0; i < 6; ++i) {
995         if (!(Box3D::int_to_face(z_orders[i]) & axis)) {
996             if (pos1 == -1) {
997                 pos1 = i;
998             } else {
999                 pos2 = i;
1000                 break;
1001             }
1002         }
1003     }
1005     int tmp = z_orders[pos1];
1006     z_orders[pos1] = z_orders[pos2];
1007     z_orders[pos2] = tmp;
1011 bool
1012 box3d_recompute_z_orders (SPBox3D *box) {
1013     Persp3D *persp = box3d_get_perspective(box);
1015     if (!persp)
1016         return false;
1018     int z_orders[6];
1020     Geom::Point c3(box3d_get_corner_screen(box, 3, false));
1022     // determine directions from corner3 to the VPs
1023     int num_finite = 0;
1024     Box3D::Axis axis_finite = Box3D::NONE;
1025     Box3D::Axis axis_infinite = Box3D::NONE;
1026     Geom::Point dirs[3];
1027     for (int i = 0; i < 3; ++i) {
1028         dirs[i] = persp3d_get_PL_dir_from_pt(persp, c3, Box3D::toProj(Box3D::axes[i]));
1029         if (persp3d_VP_is_finite(persp, Proj::axes[i])) {
1030             num_finite++;
1031             axis_finite = Box3D::axes[i];
1032         } else {
1033             axis_infinite = Box3D::axes[i];
1034         }
1035     }
1037     // determine the "central" axis (if there is one)
1038     Box3D::Axis central_axis = Box3D::NONE;
1039     if(Box3D::lies_in_sector(dirs[0], dirs[1], dirs[2])) {
1040         central_axis = Box3D::Z;
1041     } else if(Box3D::lies_in_sector(dirs[1], dirs[2], dirs[0])) {
1042         central_axis = Box3D::X;
1043     } else if(Box3D::lies_in_sector(dirs[2], dirs[0], dirs[1])) {
1044         central_axis = Box3D::Y;
1045     }
1047     switch (num_finite) {
1048         case 0:
1049             // TODO: Remark: In this case (and maybe one of the others, too) the z-orders for all boxes
1050             //               coincide, hence only need to be computed once in a more central location.
1051             box3d_set_new_z_orders_case0(box, z_orders, central_axis);
1052             break;
1053         case 1:
1054             box3d_set_new_z_orders_case1(box, z_orders, central_axis, axis_finite);
1055             break;
1056         case 2:
1057         case 3:
1058             box3d_set_new_z_orders_case2(box, z_orders, central_axis, axis_infinite);
1059             break;
1060         default:
1061         /*
1062          * For each VP F, check wether the half-line from the corner3 to F crosses the line segment
1063          * joining the other two VPs. If this is the case, it determines the "central" corner from
1064          * which the visible sides can be deduced. Otherwise, corner3 is the central corner.
1065          */
1066         // FIXME: We should eliminate the use of Geom::Point altogether
1067         Box3D::Axis central_axis = Box3D::NONE;
1068         Geom::Point vp_x = persp3d_get_VP(persp, Proj::X).affine();
1069         Geom::Point vp_y = persp3d_get_VP(persp, Proj::Y).affine();
1070         Geom::Point vp_z = persp3d_get_VP(persp, Proj::Z).affine();
1071         Geom::Point vpx(vp_x[Geom::X], vp_x[Geom::Y]);
1072         Geom::Point vpy(vp_y[Geom::X], vp_y[Geom::Y]);
1073         Geom::Point vpz(vp_z[Geom::X], vp_z[Geom::Y]);
1075         Geom::Point c3 = box3d_get_corner_screen(box, 3, false);
1076         Geom::Point corner3(c3[Geom::X], c3[Geom::Y]);
1078         if (box3d_half_line_crosses_joining_line (corner3, vpx, vpy, vpz)) {
1079             central_axis = Box3D::X;
1080         } else if (box3d_half_line_crosses_joining_line (corner3, vpy, vpz, vpx)) {
1081             central_axis = Box3D::Y;
1082         } else if (box3d_half_line_crosses_joining_line (corner3, vpz, vpx, vpy)) {
1083             central_axis = Box3D::Z;
1084         }
1086         unsigned int central_corner = 3 ^ central_axis;
1087         if (central_axis == Box3D::Z) {
1088             central_corner = central_corner ^ Box3D::XYZ;
1089         }
1090         if (box3d_XY_axes_are_swapped(box)) {
1091             central_corner = central_corner ^ Box3D::XYZ;
1092         }
1094         Geom::Point c1(box3d_get_corner_screen(box, 1, false));
1095         Geom::Point c2(box3d_get_corner_screen(box, 2, false));
1096         Geom::Point c7(box3d_get_corner_screen(box, 7, false));
1098         Geom::Point corner1(c1[Geom::X], c1[Geom::Y]);
1099         Geom::Point corner2(c2[Geom::X], c2[Geom::Y]);
1100         Geom::Point corner7(c7[Geom::X], c7[Geom::Y]);
1101         // FIXME: At present we don't use the information about central_corner computed above.
1102         switch (central_axis) {
1103             case Box3D::Y:
1104                 if (!box3d_half_line_crosses_joining_line(vpz, vpy, corner3, corner2)) {
1105                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
1106                 } else {
1107                     // degenerate case
1108                     box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 5, 4);
1109                 }
1110                 break;
1112             case Box3D::Z:
1113                 if (box3d_half_line_crosses_joining_line(vpx, vpz, corner3, corner1)) {
1114                     // degenerate case
1115                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
1116                 } else if (box3d_half_line_crosses_joining_line(vpx, vpy, corner3, corner7)) {
1117                     // degenerate case
1118                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 3, 4);
1119                 } else {
1120                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 3, 4, 5);
1121                 }
1122                 break;
1124             case Box3D::X:
1125                 if (box3d_half_line_crosses_joining_line(vpz, vpx, corner3, corner1)) {
1126                     // degenerate case
1127                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 5, 3);
1128                 } else {
1129                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3);
1130                 }
1131                 break;
1133             case Box3D::NONE:
1134                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
1135                 break;
1137             default:
1138                 g_assert_not_reached();
1139                 break;
1140         } // end default case
1141     }
1143     // TODO: If there are still errors in z-orders of everted boxes, we need to choose a variable corner
1144     //       instead of the hard-coded corner #3 in the computations above
1145     Box3D::Axis ev = box3d_everted_directions(box);
1146     for (int i = 0; i < 3; ++i) {
1147         if (ev & Box3D::axes[i]) {
1148             box3d_swap_sides(z_orders, Box3D::axes[i]);
1149         }
1150     }
1152     // Check whether anything actually changed
1153     for (int i = 0; i < 6; ++i) {
1154         if (box->z_orders[i] != z_orders[i]) {
1155             for (int j = i; j < 6; ++j) {
1156                 box->z_orders[j] = z_orders[j];
1157             }
1158             return true;
1159         }
1160     }
1161     return false;
1164 static std::map<int, Box3DSide *>
1165 box3d_get_sides (SPBox3D *box) {
1166     std::map<int, Box3DSide *> sides;
1167     for (SPObject *side = sp_object_first_child(box); side != NULL; side = SP_OBJECT_NEXT(side)) {
1168         if (SP_IS_BOX3D_SIDE(side))
1169             sides[Box3D::face_to_int(sp_repr_get_int_attribute(SP_OBJECT_REPR(side),
1170                                                                "inkscape:box3dsidetype", -1))] = SP_BOX3D_SIDE(side);
1171     }
1172     sides.erase(-1);
1173     return sides;
1177 // TODO: Check whether the box is everted in any direction and swap the sides opposite to this direction
1178 void
1179 box3d_set_z_orders (SPBox3D *box) {
1180     // For efficiency reasons, we only set the new z-orders if something really changed
1181     if (box3d_recompute_z_orders (box)) {
1182         std::map<int, Box3DSide *> sides = box3d_get_sides(box);
1183         std::map<int, Box3DSide *>::iterator side;
1184         for (unsigned int i = 0; i < 6; ++i) {
1185             side = sides.find(box->z_orders[i]);
1186             if (side != sides.end()) {
1187                 SP_ITEM((*side).second)->lowerToBottom();
1188             }
1189         }
1190     }
1193 /*
1194  * Auxiliary function for z-order recomputing:
1195  * Determines whether \a pt lies in the sector formed by the two PLs from the corners with IDs
1196  * \a i21 and \a id2 to the VP in direction \a axis. If the VP is infinite, we say that \a pt
1197  * lies in the sector if it lies between the two (parallel) PLs.
1198  * \ret *  0 if \a pt doesn't lie in the sector
1199  *      *  1 if \a pt lies in the sector and either VP is finite of VP is infinite and the direction
1200  *           from the edge between the two corners to \a pt points towards the VP
1201  *      * -1 otherwise
1202  */
1203 // TODO: Maybe it would be useful to have a similar method for projective points pt because then we
1204 //       can use it for VPs and perhaps merge the case distinctions during z-order recomputation.
1205 int
1206 box3d_pt_lies_in_PL_sector (SPBox3D const *box, Geom::Point const &pt, int id1, int id2, Box3D::Axis axis) {
1207     Persp3D *persp = box3d_get_perspective(box);
1209     // the two corners
1210     Geom::Point c1(box3d_get_corner_screen(box, id1, false));
1211     Geom::Point c2(box3d_get_corner_screen(box, id2, false));
1213     int ret = 0;
1214     if (persp3d_VP_is_finite(persp, Box3D::toProj(axis))) {
1215         Geom::Point vp(persp3d_get_VP(persp, Box3D::toProj(axis)).affine());
1216         Geom::Point v1(c1 - vp);
1217         Geom::Point v2(c2 - vp);
1218         Geom::Point w(pt - vp);
1219         ret = static_cast<int>(Box3D::lies_in_sector(v1, v2, w));
1220     } else {
1221         Box3D::PerspectiveLine pl1(c1, Box3D::toProj(axis), persp);
1222         Box3D::PerspectiveLine pl2(c2, Box3D::toProj(axis), persp);
1223         if (pl1.lie_on_same_side(pt, c2) && pl2.lie_on_same_side(pt, c1)) {
1224             // test whether pt lies "towards" or "away from" the VP
1225             Box3D::Line edge(c1,c2);
1226             Geom::Point c3(box3d_get_corner_screen(box, id1 ^ axis, false));
1227             if (edge.lie_on_same_side(pt, c3)) {
1228                 ret = 1;
1229             } else {
1230                 ret = -1;
1231             }
1232         }
1233     }
1234     return ret;
1237 int
1238 box3d_VP_lies_in_PL_sector (SPBox3D const *box, Proj::Axis vpdir, int id1, int id2, Box3D::Axis axis) {
1239     Persp3D *persp = box3d_get_perspective(box);
1241     if (!persp3d_VP_is_finite(persp, vpdir)) {
1242         return 0;
1243     } else {
1244         return box3d_pt_lies_in_PL_sector(box, persp3d_get_VP(persp, vpdir).affine(), id1, id2, axis);
1245     }
1248 /* swap the coordinates of corner0 and corner7 along the specified axis */
1249 static void
1250 box3d_swap_coords(SPBox3D *box, Proj::Axis axis, bool smaller = true) {
1251     box->orig_corner0.normalize();
1252     box->orig_corner7.normalize();
1253     if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) {
1254         double tmp = box->orig_corner0[axis];
1255         box->orig_corner0[axis] = box->orig_corner7[axis];
1256         box->orig_corner7[axis] = tmp;
1257     }
1258     // Should we also swap the coordinates of save_corner0 and save_corner7?
1261 /* ensure that the coordinates of corner0 and corner7 are in the correct order (to prevent everted boxes) */
1262 void
1263 box3d_relabel_corners(SPBox3D *box) {
1264     box3d_swap_coords(box, Proj::X, false);
1265     box3d_swap_coords(box, Proj::Y, false);
1266     box3d_swap_coords(box, Proj::Z, true);
1269 static void
1270 box3d_check_for_swapped_coords(SPBox3D *box, Proj::Axis axis, bool smaller) {
1271     box->orig_corner0.normalize();
1272     box->orig_corner7.normalize();
1274     if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) {
1275         box->swapped = (Box3D::Axis) (box->swapped | Proj::toAffine(axis));
1276     } else {
1277         box->swapped = (Box3D::Axis) (box->swapped & ~Proj::toAffine(axis));
1278     }
1281 static void
1282 box3d_exchange_coords(SPBox3D *box) {
1283     box->orig_corner0.normalize();
1284     box->orig_corner7.normalize();
1286     for (int i = 0; i < 3; ++i) {
1287         if (box->swapped & Box3D::axes[i]) {
1288             double tmp = box->orig_corner0[i];
1289             box->orig_corner0[i] = box->orig_corner7[i];
1290             box->orig_corner7[i] = tmp;
1291         }
1292     }
1295 void
1296 box3d_check_for_swapped_coords(SPBox3D *box) {
1297     box3d_check_for_swapped_coords(box, Proj::X, false);
1298     box3d_check_for_swapped_coords(box, Proj::Y, false);
1299     box3d_check_for_swapped_coords(box, Proj::Z, true);
1301     box3d_exchange_coords(box);
1304 void
1305 box3d_add_to_selection(SPBox3D *box) {
1306     Persp3D *persp = box3d_get_perspective(box);
1307     g_return_if_fail(persp);
1308     persp3d_add_box_transform(persp, box);
1311 void
1312 box3d_remove_from_selection(SPBox3D *box) {
1313     Persp3D *persp = box3d_get_perspective(box);
1314     if (!persp) {
1315         /* this can happen if a box is deleted through undo and the persp_ref is already detached;
1316            should we rebuild the boxes of each perspective in this case or is it safe to leave it alone? */
1317         return;
1318     }
1319     persp3d_remove_box_transform(persp, box);
1322 void
1323 box3d_mark_transformed(SPBox3D *box) {
1324     Persp3D *persp = box3d_get_perspective(box);
1325     g_return_if_fail(persp);
1326     persp3d_set_box_transformed(persp, box, true);
1329 static void
1330 box3d_extract_boxes_rec(SPObject *obj, std::list<SPBox3D *> &boxes) {
1331     if (SP_IS_BOX3D(obj)) {
1332         boxes.push_back(SP_BOX3D(obj));
1333     } else if (SP_IS_GROUP(obj)) {
1334         for (SPObject *child = sp_object_first_child(obj); child != NULL; child = SP_OBJECT_NEXT(child) ) {
1335             box3d_extract_boxes_rec(child, boxes);
1336         }
1337     }
1340 std::list<SPBox3D *>
1341 box3d_extract_boxes(SPObject *obj) {
1342     std::list<SPBox3D *> boxes;
1343     box3d_extract_boxes_rec(obj, boxes);
1344     return boxes;
1347 Persp3D *
1348 box3d_get_perspective(SPBox3D const *box) {
1349     return box->persp_ref->getObject();
1352 void
1353 box3d_switch_perspectives(SPBox3D *box, Persp3D *old_persp, Persp3D *new_persp, bool recompute_corners) {
1354     if (recompute_corners) {
1355         box->orig_corner0.normalize();
1356         box->orig_corner7.normalize();
1357         double z0 = box->orig_corner0[Proj::Z];
1358         double z7 = box->orig_corner7[Proj::Z];
1359         Geom::Point corner0_screen = box3d_get_corner_screen(box, 0, false);
1360         Geom::Point corner7_screen = box3d_get_corner_screen(box, 7, false);
1362         box->orig_corner0 = new_persp->tmat.preimage(corner0_screen, z0, Proj::Z);
1363         box->orig_corner7 = new_persp->tmat.preimage(corner7_screen, z7, Proj::Z);
1364     }
1366     persp3d_remove_box (old_persp, box);
1367     persp3d_add_box (new_persp, box);
1369     persp3d_remove_box_transform (old_persp, box);
1370     persp3d_add_box_transform (new_persp, box);
1372     gchar *href = g_strdup_printf("#%s", SP_OBJECT_REPR(new_persp)->attribute("id"));
1373     SP_OBJECT_REPR(box)->setAttribute("inkscape:perspectiveID", href);
1374     g_free(href);
1377 /* Converts the 3D box to an ordinary SPGroup, adds it to the XML tree at the same position as
1378    the original box and deletes the latter */
1379 SPGroup *
1380 box3d_convert_to_group(SPBox3D *box) {
1381     SPDocument *doc = SP_OBJECT_DOCUMENT(box);
1382     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
1384     // remember position of the box
1385     int pos = SP_OBJECT_REPR(box)->position();
1387     // remember important attributes
1388     Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(box);
1389     gchar const *id = repr_source->attribute("id");
1390     gchar const *style = repr_source->attribute("style");
1391     gchar const *mask = repr_source->attribute("mask");
1392     gchar const *clip_path = repr_source->attribute("clip-path");
1394     // create a new group and add the sides (converted to ordinary paths) as its children
1395     Inkscape::XML::Node *grepr = xml_doc->createElement("svg:g");
1397     Inkscape::XML::Node *repr;
1398     for (SPObject *child = sp_object_first_child(SP_OBJECT(box)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
1399         if (SP_IS_BOX3D_SIDE(child)) {
1400             repr = box3d_side_convert_to_path(SP_BOX3D_SIDE(child));
1401             grepr->appendChild(repr);
1402         } else {
1403             g_warning("Non-side item encountered as child of a 3D box.");
1404         }
1405     }
1407     // add the new group to the box's parent and set remembered position
1408     SPObject *parent = SP_OBJECT_PARENT(box);
1409     SP_OBJECT_REPR(parent)->appendChild(grepr);
1410     grepr->setPosition(pos);
1411     grepr->setAttribute("style", style);
1412     if (mask)
1413        grepr->setAttribute("mask", mask);
1414     if (clip_path)
1415        grepr->setAttribute("clip-path", clip_path);
1417     SP_OBJECT(box)->deleteObject(true);
1419     grepr->setAttribute("id", id);
1421     return SP_GROUP(doc->getObjectByRepr(grepr));
1424 static inline void
1425 box3d_push_back_corner_pair(SPBox3D *box, std::list<std::pair<Geom::Point, Geom::Point> > &pts, int c1, int c2) {
1426     pts.push_back(std::make_pair(box3d_get_corner_screen(box, c1, false),
1427                                  box3d_get_corner_screen(box, c2, false)));
1430 void
1431 box3d_convert_to_guides(SPItem *item) {
1432     SPBox3D *box = SP_BOX3D(item);
1433     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1435     if (!prefs->getBool("/tools/shapes/3dbox/convertguides", true)) {
1436         sp_item_convert_to_guides(SP_ITEM(box));
1437         return;
1438     }
1440     std::list<std::pair<Geom::Point, Geom::Point> > pts;
1442     /* perspective lines in X direction */
1443     box3d_push_back_corner_pair(box, pts, 0, 1);
1444     box3d_push_back_corner_pair(box, pts, 2, 3);
1445     box3d_push_back_corner_pair(box, pts, 4, 5);
1446     box3d_push_back_corner_pair(box, pts, 6, 7);
1448     /* perspective lines in Y direction */
1449     box3d_push_back_corner_pair(box, pts, 0, 2);
1450     box3d_push_back_corner_pair(box, pts, 1, 3);
1451     box3d_push_back_corner_pair(box, pts, 4, 6);
1452     box3d_push_back_corner_pair(box, pts, 5, 7);
1454     /* perspective lines in Z direction */
1455     box3d_push_back_corner_pair(box, pts, 0, 4);
1456     box3d_push_back_corner_pair(box, pts, 1, 5);
1457     box3d_push_back_corner_pair(box, pts, 2, 6);
1458     box3d_push_back_corner_pair(box, pts, 3, 7);
1460     sp_guide_pt_pairs_to_guides(inkscape_active_desktop(), pts);
1463 /*
1464   Local Variables:
1465   mode:c++
1466   c-file-style:"stroustrup"
1467   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1468   indent-tabs-mode:nil
1469   fill-column:99
1470   End:
1471 */
1472 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :