Code

fix bug where changing units changed angles of axonometric grid
[inkscape.git] / src / display / canvas-axonomgrid.cpp
1 #define CANVAS_AXONOMGRID_C
3 /*
4  * Copyright (C) 2006-2007 Johan Engelen <johan@shouraizou.nl>
5  */
7  /*
8   * Current limits are: one axis (y-axis) is always vertical. The other two
9   * axes are bound to a certain range of angles. The z-axis always has an angle
10   * smaller than 90 degrees (measured from horizontal, 0 degrees being a line extending
11   * to the right). The x-axis will always have an angle between 0 and 90 degrees.
12   * When I quickly think about it: all possibilities are probably covered this way. Eg.
13   * a z-axis with negative angle can be replaced with an x-axis, etc.
14   */
16  /*
17   * TODO:
18   * THIS FILE AND THE HEADER FILE NEED CLEANING UP. PLEASE DO NOT HESISTATE TO DO SO.
19   * For example: the line drawing code should not be here. There _must_ be a function somewhere else that can provide this functionality...
20   */
22 #include "sp-canvas-util.h"
23 #include "canvas-axonomgrid.h"
24 #include "util/mathfns.h" 
25 #include "2geom/geom.h"
26 #include "display-forward.h"
27 #include <libnr/nr-pixops.h>
29 #include "canvas-grid.h"
30 #include "desktop-handles.h"
31 #include "helper/units.h"
32 #include "svg/svg-color.h"
33 #include "xml/node-event-vector.h"
34 #include "sp-object.h"
36 #include "sp-namedview.h"
37 #include "inkscape.h"
38 #include "desktop.h"
40 #include "document.h"
41 #include "prefs-utils.h"
43 #define SAFE_SETPIXEL   //undefine this when it is certain that setpixel is never called with invalid params
45 enum Dim3 { X=0, Y, Z };
47 #ifndef M_PI
48 # define M_PI 3.14159265358979323846
49 #endif
51 static double deg_to_rad(double deg) { return deg*M_PI/180.0;}
54 /**
55     \brief  This function renders a pixel on a particular buffer.
57     The topleft of the buffer equals
58                         ( rect.x0 , rect.y0 )  in screen coordinates
59                         ( 0 , 0 )  in setpixel coordinates
60     The bottomright of the buffer equals
61                         ( rect.x1 , rect,y1 )  in screen coordinates
62                         ( rect.x1 - rect.x0 , rect.y1 - rect.y0 )  in setpixel coordinates
63 */
64 static void
65 sp_caxonomgrid_setpixel (SPCanvasBuf *buf, gint x, gint y, guint32 rgba)
66 {
67 #ifdef SAFE_SETPIXEL
68     if ( (x >= buf->rect.x0) && (x < buf->rect.x1) && (y >= buf->rect.y0) && (y < buf->rect.y1) ) {
69 #endif
70         guint r, g, b, a;
71         r = NR_RGBA32_R (rgba);
72         g = NR_RGBA32_G (rgba);
73         b = NR_RGBA32_B (rgba);
74         a = NR_RGBA32_A (rgba);
75         guchar * p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 3;
76         p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
77         p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
78         p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
79 #ifdef SAFE_SETPIXEL
80     }
81 #endif
82 }
84 /**
85     \brief  This function renders a line on a particular canvas buffer,
86             using Bresenham's line drawing function.
87             http://www.cs.unc.edu/~mcmillan/comp136/Lecture6/Lines.html
88             Coordinates are interpreted as SCREENcoordinates
89 */
90 static void
91 sp_caxonomgrid_drawline (SPCanvasBuf *buf, gint x0, gint y0, gint x1, gint y1, guint32 rgba)
92 {
93     int dy = y1 - y0;
94     int dx = x1 - x0;
95     int stepx, stepy;
97     if (dy < 0) { dy = -dy;  stepy = -1; } else { stepy = 1; }
98     if (dx < 0) { dx = -dx;  stepx = -1; } else { stepx = 1; }
99     dy <<= 1;                                                  // dy is now 2*dy
100     dx <<= 1;                                                  // dx is now 2*dx
102     sp_caxonomgrid_setpixel(buf, x0, y0, rgba);
103     if (dx > dy) {
104         int fraction = dy - (dx >> 1);                         // same as 2*dy - dx
105         while (x0 != x1) {
106             if (fraction >= 0) {
107                 y0 += stepy;
108                 fraction -= dx;                                // same as fraction -= 2*dx
109             }
110             x0 += stepx;
111             fraction += dy;                                    // same as fraction -= 2*dy
112             sp_caxonomgrid_setpixel(buf, x0, y0, rgba);
113         }
114     } else {
115         int fraction = dx - (dy >> 1);
116         while (y0 != y1) {
117             if (fraction >= 0) {
118                 x0 += stepx;
119                 fraction -= dy;
120             }
121             y0 += stepy;
122             fraction += dx;
123             sp_caxonomgrid_setpixel(buf, x0, y0, rgba);
124         }
125     }
129 static void
130 sp_grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba)
132     if ((x >= buf->rect.x0) && (x < buf->rect.x1)) {
133         guint r, g, b, a;
134         gint y0, y1, y;
135         guchar *p;
136         r = NR_RGBA32_R(rgba);
137         g = NR_RGBA32_G (rgba);
138         b = NR_RGBA32_B (rgba);
139         a = NR_RGBA32_A (rgba);
140         y0 = MAX (buf->rect.y0, ys);
141         y1 = MIN (buf->rect.y1, ye + 1);
142         p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 3;
143         for (y = y0; y < y1; y++) {
144             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
145             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
146             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
147             p += buf->buf_rowstride;
148         }
149     }
152 namespace Inkscape {
155 /**
156 * A DIRECT COPY-PASTE FROM DOCUMENT-PROPERTIES.CPP  TO QUICKLY GET RESULTS
158  * Helper function that attachs widgets in a 3xn table. The widgets come in an
159  * array that has two entries per table row. The two entries code for four
160  * possible cases: (0,0) means insert space in first column; (0, non-0) means
161  * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and
162  * (non-0, non-0) means two widgets in columns 2 and 3.
163 **/
164 #define SPACE_SIZE_X 15
165 #define SPACE_SIZE_Y 10
166 static inline void
167 attach_all(Gtk::Table &table, Gtk::Widget const *const arr[], unsigned size, int start = 0)
169     for (unsigned i=0, r=start; i<size/sizeof(Gtk::Widget*); i+=2) {
170         if (arr[i] && arr[i+1]) {
171             table.attach (const_cast<Gtk::Widget&>(*arr[i]),   1, 2, r, r+1,
172                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
173             table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 2, 3, r, r+1,
174                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
175         } else {
176             if (arr[i+1]) {
177                 table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 1, 3, r, r+1,
178                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
179             } else if (arr[i]) {
180                 Gtk::Label& label = reinterpret_cast<Gtk::Label&> (const_cast<Gtk::Widget&>(*arr[i]));
181                 label.set_alignment (0.0);
182                 table.attach (label, 0, 3, r, r+1,
183                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
184             } else {
185                 Gtk::HBox *space = manage (new Gtk::HBox);
186                 space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y);
187                 table.attach (*space, 0, 1, r, r+1,
188                               (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0);
189             }
190         }
191         ++r;
192     }
195 CanvasAxonomGrid::CanvasAxonomGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc)
196     : CanvasGrid(nv, in_repr, in_doc, GRID_AXONOMETRIC), table(1, 1)
198     gridunit = sp_unit_get_by_abbreviation( prefs_get_string_attribute("options.grids.axonom", "units") );
199     if (!gridunit)
200         gridunit = &sp_unit_get_by_id(SP_UNIT_PX);
201     origin[NR::X] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.axonom", "origin_x", 0.0), *(gridunit) );
202     origin[NR::Y] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.axonom", "origin_y", 0.0), *(gridunit) );
203     color = prefs_get_int_attribute("options.grids.axonom", "color", 0x0000ff20);
204     empcolor = prefs_get_int_attribute("options.grids.axonom", "empcolor", 0x0000ff40);
205     empspacing = prefs_get_int_attribute("options.grids.axonom", "empspacing", 5);
206     lengthy = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.axonom", "spacing_y", 1.0), *(gridunit) );
207     angle_deg[X] = prefs_get_double_attribute ("options.grids.axonom", "angle_x", 30.0);
208     angle_deg[Z] = prefs_get_double_attribute ("options.grids.axonom", "angle_z", 30.0);
209     angle_deg[Y] = 0;
211     angle_rad[X] = deg_to_rad(angle_deg[X]);
212     tan_angle[X] = tan(angle_rad[X]);
213     angle_rad[Z] = deg_to_rad(angle_deg[Z]);
214     tan_angle[Z] = tan(angle_rad[Z]);
216     snapper = new CanvasAxonomGridSnapper(this, namedview, 0);
218     // initialize widgets:
219     vbox.set_border_width(2);
220     table.set_spacings(2);
221     vbox.pack_start(table, false, false, 0);
223 _wr.setUpdating (true);
224     Inkscape::UI::Widget::ScalarUnit * sutemp;
225     _rumg.init (_("Grid _units:"), "units", _wr, repr, doc);
226     _rsu_ox.init (_("_Origin X:"), _("X coordinate of grid origin"),
227                   "originx", _rumg, _wr, repr, doc);
228         sutemp = _rsu_ox.getSU();
229         sutemp->setDigits(4);
230         sutemp->setIncrements(0.1, 1.0);
231     _rsu_oy.init (_("O_rigin Y:"), _("Y coordinate of grid origin"),
232                   "originy", _rumg, _wr, repr, doc);
233         sutemp = _rsu_oy.getSU();
234         sutemp->setDigits(4);
235         sutemp->setIncrements(0.1, 1.0);
236     _rsu_sy.init (_("Spacing _Y:"), _("Base length of z-axis"),
237                   "spacingy", _rumg, _wr, repr, doc);
238         sutemp = _rsu_sy.getSU();
239         sutemp->setDigits(4);
240         sutemp->setIncrements(0.1, 1.0);
241     _rsu_ax.init (_("Angle X:"), _("Angle of x-axis"),
242                   "gridanglex", _wr, repr, doc);
243     _rsu_az.init (_("Angle Z:"), _("Angle of z-axis"),
244                   "gridanglez", _wr, repr, doc);
245     _rcp_gcol.init (_("Grid line _color:"), _("Grid line color"),
246                     _("Color of grid lines"), "color", "opacity", _wr, repr, doc);
247     _rcp_gmcol.init (_("Ma_jor grid line color:"), _("Major grid line color"),
248                      _("Color of the major (highlighted) grid lines"),
249                      "empcolor", "empopacity", _wr, repr, doc);
250     _rsi.init (_("_Major grid line every:"), _("lines"), "empspacing", _wr, repr, doc);
251 _wr.setUpdating (false);
253     Gtk::Widget const *const widget_array[] = {
254         0,                  _rcbgrid._button,
255         _rumg._label,       _rumg._sel,
256         0,                  _rsu_ox.getSU(),
257         0,                  _rsu_oy.getSU(),
258         0,                  _rsu_sy.getSU(),
259         0,                  _rsu_ax.getS(),
260         0,                  _rsu_az.getS(),
261         _rcp_gcol._label,   _rcp_gcol._cp,
262         0,                  0,
263         _rcp_gmcol._label,  _rcp_gmcol._cp,
264         _rsi._label,        &_rsi._hbox,
265     };
267     attach_all (table, widget_array, sizeof(widget_array));
269     vbox.show();
271     if (repr) readRepr();
272     updateWidgets();
275 CanvasAxonomGrid::~CanvasAxonomGrid ()
277     if (snapper) delete snapper;
281 /* fixme: Collect all these length parsing methods and think common sane API */
283 static gboolean sp_nv_read_length(gchar const *str, guint base, gdouble *val, SPUnit const **unit)
285     if (!str) {
286         return FALSE;
287     }
289     gchar *u;
290     gdouble v = g_ascii_strtod(str, &u);
291     if (!u) {
292         return FALSE;
293     }
294     while (isspace(*u)) {
295         u += 1;
296     }
298     if (!*u) {
299         /* No unit specified - keep default */
300         *val = v;
301         return TRUE;
302     }
304     if (base & SP_UNIT_DEVICE) {
305         if (u[0] && u[1] && !isalnum(u[2]) && !strncmp(u, "px", 2)) {
306             *unit = &sp_unit_get_by_id(SP_UNIT_PX);
307             *val = v;
308             return TRUE;
309         }
310     }
312     if (base & SP_UNIT_ABSOLUTE) {
313         if (!strncmp(u, "pt", 2)) {
314             *unit = &sp_unit_get_by_id(SP_UNIT_PT);
315         } else if (!strncmp(u, "mm", 2)) {
316             *unit = &sp_unit_get_by_id(SP_UNIT_MM);
317         } else if (!strncmp(u, "cm", 2)) {
318             *unit = &sp_unit_get_by_id(SP_UNIT_CM);
319         } else if (!strncmp(u, "m", 1)) {
320             *unit = &sp_unit_get_by_id(SP_UNIT_M);
321         } else if (!strncmp(u, "in", 2)) {
322             *unit = &sp_unit_get_by_id(SP_UNIT_IN);
323         } else {
324             return FALSE;
325         }
326         *val = v;
327         return TRUE;
328     }
330     return FALSE;
333 static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color)
335     if (!str) {
336         return FALSE;
337     }
339     gchar *u;
340     gdouble v = g_ascii_strtod(str, &u);
341     if (!u) {
342         return FALSE;
343     }
344     v = CLAMP(v, 0.0, 1.0);
346     *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999);
348     return TRUE;
353 void
354 CanvasAxonomGrid::readRepr()
356     gchar const *value;
357     if ( (value = repr->attribute("originx")) ) {
358         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::X], &gridunit);
359         origin[NR::X] = sp_units_get_pixels(origin[NR::X], *(gridunit));
360     }
361     if ( (value = repr->attribute("originy")) ) {
362         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::Y], &gridunit);
363         origin[NR::Y] = sp_units_get_pixels(origin[NR::Y], *(gridunit));
364     }
366     if ( (value = repr->attribute("spacingy")) ) {
367         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &lengthy, &gridunit);
368         lengthy = sp_units_get_pixels(lengthy, *(gridunit));
369         if (lengthy < 1.0) lengthy = 1.0;
370     }
372     if ( (value = repr->attribute("gridanglex")) ) {
373         angle_deg[X] = g_ascii_strtod(value, NULL);
374         if (angle_deg[X] < 1.0) angle_deg[X] = 1.0;
375         if (angle_deg[X] > 89.0) angle_deg[X] = 89.0;
376         angle_rad[X] = deg_to_rad(angle_deg[X]);
377         tan_angle[X] = tan(angle_rad[X]);
378     }
380     if ( (value = repr->attribute("gridanglez")) ) {
381         angle_deg[Z] = g_ascii_strtod(value, NULL);
382         if (angle_deg[Z] < 1.0) angle_deg[Z] = 1.0;
383         if (angle_deg[Z] > 89.0) angle_deg[Z] = 89.0;
384         angle_rad[Z] = deg_to_rad(angle_deg[Z]);
385         tan_angle[Z] = tan(angle_rad[Z]);
386     }
388     if ( (value = repr->attribute("color")) ) {
389         color = (color & 0xff) | sp_svg_read_color(value, color);
390     }
392     if ( (value = repr->attribute("empcolor")) ) {
393         empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor);
394     }
396     if ( (value = repr->attribute("opacity")) ) {
397         sp_nv_read_opacity(value, &color);
398     }
399     if ( (value = repr->attribute("empopacity")) ) {
400         sp_nv_read_opacity(value, &empcolor);
401     }
403     if ( (value = repr->attribute("empspacing")) ) {
404         empspacing = atoi(value);
405     }
407     if ( (value = repr->attribute("visible")) ) {
408         visible = (strcmp(value,"true") == 0);
409     }
411     if ( (value = repr->attribute("snap_enabled")) ) {
412         g_assert(snapper != NULL);
413         snapper->setEnabled(strcmp(value,"true") == 0);
414     }
416     for (GSList *l = canvasitems; l != NULL; l = l->next) {
417         sp_canvas_item_request_update ( SP_CANVAS_ITEM(l->data) );
418     }
419     return;
422 /**
423  * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves.
424  */
425 void
426 CanvasAxonomGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/)
428     readRepr();
430     if ( ! (_wr.isUpdating()) )
431         updateWidgets();
437 Gtk::Widget &
438 CanvasAxonomGrid::getWidget()
440     return vbox;
444 /**
445  * Update dialog widgets from object's values.
446  */
447 void
448 CanvasAxonomGrid::updateWidgets()
450     if (_wr.isUpdating()) return;
452     _wr.setUpdating (true);
454     _rcb_visible.setActive(visible);
455     if (snapper != NULL) {
456         _rcb_snap_enabled.setActive(snapper->getEnabled());
457     }
459     _rumg.setUnit (gridunit);
461     gdouble val;
462     val = origin[NR::X];
463     val = sp_pixels_get_units (val, *(gridunit));
464     _rsu_ox.setValue (val);
465     val = origin[NR::Y];
466     val = sp_pixels_get_units (val, *(gridunit));
467     _rsu_oy.setValue (val);
468     val = lengthy;
469     double gridy = sp_pixels_get_units (val, *(gridunit));
470     _rsu_sy.setValue (gridy);
472     _rsu_ax.setValue(angle_deg[X]);
473     _rsu_az.setValue(angle_deg[Z]);
475     _rcp_gcol.setRgba32 (color);
476     _rcp_gmcol.setRgba32 (empcolor);
477     _rsi.setValue (empspacing);
479     _wr.setUpdating (false);
481     return;
486 void
487 CanvasAxonomGrid::Update (NR::Matrix const &affine, unsigned int /*flags*/)
489     ow = origin * affine;
490     sw = NR::Point(fabs(affine[0]),fabs(affine[3]));
492     for(int dim = 0; dim < 2; dim++) {
493         gint scaling_factor = empspacing;
495         if (scaling_factor <= 1)
496             scaling_factor = 5;
498         scaled = FALSE;
499         int watchdog = 0;
500         while (  (sw[dim] < 8.0) & (watchdog < 100) ) {
501             scaled = TRUE;
502             sw[dim] *= scaling_factor;
503             // First pass, go up to the major line spacing, then
504             // keep increasing by two.
505             scaling_factor = 2;
506             watchdog++;
507         }
509     }
511     spacing_ylines = sw[NR::X] * lengthy  /(tan_angle[X] + tan_angle[Z]);
512     lyw            = sw[NR::Y] * lengthy;
513     lxw_x          = (lengthy / tan_angle[X]) * sw[NR::X];
514     lxw_z          = (lengthy / tan_angle[Z]) * sw[NR::X];
516     if (empspacing == 0) {
517         scaled = TRUE;
518     }
522 void
523 CanvasAxonomGrid::Render (SPCanvasBuf *buf)
525     // gc = gridcoordinates (the coordinates calculated from the grids origin 'grid->ow'.
526     // sc = screencoordinates ( for example "buf->rect.x0" is in screencoordinates )
527     // bc = buffer patch coordinates
529     // tl = topleft ; br = bottomright
530     NR::Point buf_tl_gc;
531     NR::Point buf_br_gc;
532     buf_tl_gc[NR::X] = buf->rect.x0 - ow[NR::X];
533     buf_tl_gc[NR::Y] = buf->rect.y0 - ow[NR::Y];
534     buf_br_gc[NR::X] = buf->rect.x1 - ow[NR::X];
535     buf_br_gc[NR::Y] = buf->rect.y1 - ow[NR::Y];
537     gdouble x;
538     gdouble y;
540     // render the three separate line groups representing the main-axes
542     // x-axis always goes from topleft to bottomright. (0,0) - (1,1)
543     gdouble const xintercept_y_bc = (buf_tl_gc[NR::X] * tan_angle[X]) - buf_tl_gc[NR::Y] ;
544     gdouble const xstart_y_sc = ( xintercept_y_bc - floor(xintercept_y_bc/lyw)*lyw ) + buf->rect.y0;
545     gint const xlinestart = (gint) Inkscape::round( (xstart_y_sc - buf->rect.x0*tan_angle[X] -ow[NR::Y]) / lyw );
546     gint xlinenum = xlinestart;
547     // lines starting on left side.
548     for (y = xstart_y_sc; y < buf->rect.y1; y += lyw, xlinenum++) {
549         gint const x0 = buf->rect.x0;
550         gint const y0 = (gint) Inkscape::round(y);
551         gint const x1 = x0 + (gint) Inkscape::round( (buf->rect.y1 - y) / tan_angle[X] );
552         gint const y1 = buf->rect.y1;
554         if (!scaled && (xlinenum % empspacing) == 0) {
555             sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, empcolor);
556         } else {
557             sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, color);
558         }
559     }
560     // lines starting from top side
561     gdouble const xstart_x_sc = buf->rect.x0 + (lxw_x - (xstart_y_sc - buf->rect.y0) / tan_angle[X]) ;
562     xlinenum = xlinestart-1;
563     for (x = xstart_x_sc; x < buf->rect.x1; x += lxw_x, xlinenum--) {
564         gint const y0 = buf->rect.y0;
565         gint const y1 = buf->rect.y1;
566         gint const x0 = (gint) Inkscape::round(x);
567         gint const x1 = x0 + (gint) Inkscape::round( (y1 - y0) / tan_angle[X] );
569         if (!scaled && (xlinenum % empspacing) == 0) {
570             sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, empcolor);
571         } else {
572             sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, color);
573         }
574     }
576     // y-axis lines (vertical)
577     gdouble const ystart_x_sc = floor (buf_tl_gc[NR::X] / spacing_ylines) * spacing_ylines + ow[NR::X];
578     gint const  ylinestart = (gint) Inkscape::round((ystart_x_sc - ow[NR::X]) / spacing_ylines);
579     gint ylinenum = ylinestart;
580     for (x = ystart_x_sc; x < buf->rect.x1; x += spacing_ylines, ylinenum++) {
581         gint const x0 = (gint) Inkscape::round(x);
583         if (!scaled && (ylinenum % empspacing) == 0) {
584             sp_grid_vline (buf, x0, buf->rect.y0, buf->rect.y1 - 1, empcolor);
585         } else {
586             sp_grid_vline (buf, x0, buf->rect.y0, buf->rect.y1 - 1, color);
587         }
588     }
590     // z-axis always goes from bottomleft to topright. (0,1) - (1,0)
591     gdouble const zintercept_y_bc = (buf_tl_gc[NR::X] * -tan_angle[Z]) - buf_tl_gc[NR::Y] ;
592     gdouble const zstart_y_sc = ( zintercept_y_bc - floor(zintercept_y_bc/lyw)*lyw ) + buf->rect.y0;
593     gint const  zlinestart = (gint) Inkscape::round( (zstart_y_sc + buf->rect.x0*tan_angle[X] - ow[NR::Y]) / lyw );
594     gint zlinenum = zlinestart;
595     // lines starting from left side
596     for (y = zstart_y_sc; y < buf->rect.y1; y += lyw, zlinenum++) {
597         gint const x0 = buf->rect.x0;
598         gint const y0 = (gint) Inkscape::round(y);
599         gint const x1 = x0 + (gint) Inkscape::round( (y - buf->rect.y0 ) / tan_angle[Z] );
600         gint const y1 = buf->rect.y0;
602         if (!scaled && (zlinenum % empspacing) == 0) {
603             sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, empcolor);
604         } else {
605             sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, color);
606         }
607     }
608     // draw lines from bottom-up
609     gdouble const zstart_x_sc = buf->rect.x0 + (y - buf->rect.y1) / tan_angle[Z] ;
610     for (x = zstart_x_sc; x < buf->rect.x1; x += lxw_z, zlinenum++) {
611         gint const y0 = buf->rect.y1;
612         gint const y1 = buf->rect.y0;
613         gint const x0 = (gint) Inkscape::round(x);
614         gint const x1 = x0 + (gint) Inkscape::round( (buf->rect.y1 - buf->rect.y0) / tan_angle[Z] );
616         if (!scaled && (zlinenum % empspacing) == 0) {
617             sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, empcolor);
618         } else {
619             sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, color);
620         }
621     }
624 CanvasAxonomGridSnapper::CanvasAxonomGridSnapper(CanvasAxonomGrid *grid, SPNamedView const *nv, NR::Coord const d) : LineSnapper(nv, d)
626     this->grid = grid;
629 LineSnapper::LineList
630 CanvasAxonomGridSnapper::_getSnapLines(NR::Point const &p) const
632     LineList s;
634     if ( grid == NULL ) {
635         return s;
636     }
638     /* This is to make sure we snap to only visible grid lines */
639     double scaled_spacing_h = grid->spacing_ylines; // this is spacing of visible lines if screen pixels
640     double scaled_spacing_v = grid->lyw; // vertical
642     // convert screen pixels to px
643     // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary
644     if (SP_ACTIVE_DESKTOP) {
645         scaled_spacing_h /= SP_ACTIVE_DESKTOP->current_zoom();
646         scaled_spacing_v /= SP_ACTIVE_DESKTOP->current_zoom();
647     }
649     // In an axonometric grid, any point will be surrounded by 6 grid lines:
650     // - 2 vertical grid lines, one left and one right from the point
651     // - 2 angled z grid lines, one above and one below the point
652     // - 2 angled x grid lines, one above and one below the point
653     
654     // Calculate the x coordinate of the vertical grid lines
655     NR::Coord x_max = Inkscape::Util::round_to_upper_multiple_plus(p[NR::X], scaled_spacing_h, grid->origin[NR::X]);
656     NR::Coord x_min = Inkscape::Util::round_to_lower_multiple_plus(p[NR::X], scaled_spacing_h, grid->origin[NR::X]);
657     
658     // Calculate the y coordinate of the intersection of the angled grid lines with the y-axis
659     double y_proj_along_z = p[NR::Y] - grid->tan_angle[Z]*(p[NR::X] - grid->origin[NR::X]);  
660     double y_proj_along_x = p[NR::Y] + grid->tan_angle[X]*(p[NR::X] - grid->origin[NR::X]);    
661     double y_proj_along_z_max = Inkscape::Util::round_to_upper_multiple_plus(y_proj_along_z, scaled_spacing_v, grid->origin[NR::Y]);
662     double y_proj_along_z_min = Inkscape::Util::round_to_lower_multiple_plus(y_proj_along_z, scaled_spacing_v, grid->origin[NR::Y]);    
663     double y_proj_along_x_max = Inkscape::Util::round_to_upper_multiple_plus(y_proj_along_x, scaled_spacing_v, grid->origin[NR::Y]);
664     double y_proj_along_x_min = Inkscape::Util::round_to_lower_multiple_plus(y_proj_along_x, scaled_spacing_v, grid->origin[NR::Y]);
665     
666     // Calculate the normal for the angled grid lines
667     NR::Point norm_x = NR::rot90(NR::Point(1, -grid->tan_angle[X]));
668     NR::Point norm_z = NR::rot90(NR::Point(1, grid->tan_angle[Z]));
669     
670     // The four angled grid lines form a parallellogram, enclosing the point
671     // One of the two vertical grid lines divides this parallellogram in two triangles
672     // We will now try to find out in which half (i.e. triangle) our point is, and return 
673     // only the three grid lines defining that triangle 
674     
675     // The vertical grid line is at the intersection of two angled grid lines. 
676     // Now go find that intersection!
677     Geom::Point result;
678     Geom::IntersectorKind is = line_intersection(norm_x.to_2geom(), norm_x[NR::Y]*y_proj_along_x_max,
679                                            norm_z.to_2geom(), norm_z[NR::Y]*y_proj_along_z_max,
680                                            result);
681                          
682     // Determine which half of the parallellogram to use 
683     bool use_left_half = true;
684     bool use_right_half = true;
685     
686     if (is == Geom::intersects) {
687         use_left_half = (p[NR::X] - grid->origin[NR::X]) < result[Geom::X];
688         use_right_half = !use_left_half; 
689     }
690     
691     //std::cout << "intersection at " << result << " leads to use_left_half = " << use_left_half << " and use_right_half = " << use_right_half << std::endl;
692        
693     // Return the three grid lines which define the triangle that encloses our point
694     // If we didn't find an intersection above, all 6 grid lines will be returned
695     if (use_left_half) {
696         s.push_back(std::make_pair(norm_z, NR::Point(grid->origin[NR::X], y_proj_along_z_max)));
697         s.push_back(std::make_pair(norm_x, NR::Point(grid->origin[NR::X], y_proj_along_x_min)));
698         s.push_back(std::make_pair(component_vectors[NR::X], NR::Point(x_max, 0)));            
699     }
700     
701     if (use_right_half) {
702         s.push_back(std::make_pair(norm_z, NR::Point(grid->origin[NR::X], y_proj_along_z_min)));
703         s.push_back(std::make_pair(norm_x, NR::Point(grid->origin[NR::X], y_proj_along_x_max)));
704         s.push_back(std::make_pair(component_vectors[NR::X], NR::Point(x_min, 0)));        
705     } 
706     
707     return s;
710 void CanvasAxonomGridSnapper::_addSnappedLine(SnappedConstraints &sc, NR::Point const snapped_point, NR::Coord const snapped_distance, NR::Point const normal_to_line, NR::Point const point_on_line) const 
712     SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, normal_to_line, point_on_line);
713     sc.grid_lines.push_back(dummy);
718 }; // namespace Inkscape
721 /*
722   Local Variables:
723   mode:c++
724   c-file-style:"stroustrup"
725   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
726   indent-tabs-mode:nil
727   fill-column:99
728   End:
729 */
730 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :