1 //-----------------------------------------------------------------------------
2 // Top-level implementation of the program's main window, in which a graphical
3 // representation of the model is drawn and edited by the user.
4 //
5 // Copyright 2008-2013 Jonathan Westhues.
6 //-----------------------------------------------------------------------------
7 #include "solvespace.h"
8 #include "config.h"
9
10 #define mView (&GraphicsWindow::MenuView)
11 #define mEdit (&GraphicsWindow::MenuEdit)
12 #define mClip (&GraphicsWindow::MenuClipboard)
13 #define mReq (&GraphicsWindow::MenuRequest)
14 #define mCon (&Constraint::MenuConstrain)
15 #define mFile (&SolveSpaceUI::MenuFile)
16 #define mGrp (&Group::MenuGroup)
17 #define mAna (&SolveSpaceUI::MenuAnalyze)
18 #define mHelp (&SolveSpaceUI::MenuHelp)
19 #define DEL DELETE_KEY
20 #define ESC ESCAPE_KEY
21 #define S SHIFT_MASK
22 #define C CTRL_MASK
23 #define F(k) (FUNCTION_KEY_BASE+(k))
24 #define TN MENU_ITEM_NORMAL
25 #define TC MENU_ITEM_CHECK
26 #define TR MENU_ITEM_RADIO
27 const GraphicsWindow::MenuEntry GraphicsWindow::menu[] = {
28 //level
29 // label id accel ty fn
30 { 0, "&File", 0, 0, TN, NULL },
31 { 1, "&New", MNU_NEW, C|'N', TN, mFile },
32 { 1, "&Open...", MNU_OPEN, C|'O', TN, mFile },
33 { 1, "Open &Recent", MNU_OPEN_RECENT, 0, TN, mFile },
34 { 1, "&Save", MNU_SAVE, C|'S', TN, mFile },
35 { 1, "Save &As...", MNU_SAVE_AS, 0, TN, mFile },
36 { 1, NULL, 0, 0, TN, NULL },
37 { 1, "Export &Image...", MNU_EXPORT_PNG, 0, TN, mFile },
38 { 1, "Export 2d &View...", MNU_EXPORT_VIEW, 0, TN, mFile },
39 { 1, "Export 2d &Section...", MNU_EXPORT_SECTION, 0, TN, mFile },
40 { 1, "Export 3d &Wireframe...", MNU_EXPORT_WIREFRAME, 0, TN, mFile },
41 { 1, "Export Triangle &Mesh...", MNU_EXPORT_MESH, 0, TN, mFile },
42 { 1, "Export &Surfaces...", MNU_EXPORT_SURFACES,0, TN, mFile },
43 { 1, "Im&port...", MNU_IMPORT ,0, TN, mFile },
44 #ifndef __APPLE__
45 { 1, NULL, 0, 0, TN, NULL },
46 { 1, "E&xit", MNU_EXIT, C|'Q', TN, mFile },
47 #endif
48
49 { 0, "&Edit", 0, 0, TN, NULL },
50 { 1, "&Undo", MNU_UNDO, C|'Z', TN, mEdit },
51 { 1, "&Redo", MNU_REDO, C|'Y', TN, mEdit },
52 { 1, "Re&generate All", MNU_REGEN_ALL, ' ', TN, mEdit },
53 { 1, NULL, 0, 0, TN, NULL },
54 { 1, "Snap Selection to &Grid", MNU_SNAP_TO_GRID, '.', TN, mEdit },
55 { 1, "Rotate Imported &90°", MNU_ROTATE_90, '9', TN, mEdit },
56 { 1, NULL, 0, 0, TN, NULL },
57 { 1, "Cu&t", MNU_CUT, C|'X', TN, mClip },
58 { 1, "&Copy", MNU_COPY, C|'C', TN, mClip },
59 { 1, "&Paste", MNU_PASTE, C|'V', TN, mClip },
60 { 1, "Paste &Transformed...", MNU_PASTE_TRANSFORM,C|'T', TN, mClip },
61 { 1, "&Delete", MNU_DELETE, DEL, TN, mClip },
62 { 1, NULL, 0, 0, TN, NULL },
63 { 1, "Select &Edge Chain", MNU_SELECT_CHAIN, C|'E', TN, mEdit },
64 { 1, "Select &All", MNU_SELECT_ALL, C|'A', TN, mEdit },
65 { 1, "&Unselect All", MNU_UNSELECT_ALL, ESC, TN, mEdit },
66
67 { 0, "&View", 0, 0, TN, NULL },
68 { 1, "Zoom &In", MNU_ZOOM_IN, '+', TN, mView },
69 { 1, "Zoom &Out", MNU_ZOOM_OUT, '-', TN, mView },
70 { 1, "Zoom To &Fit", MNU_ZOOM_TO_FIT, 'F', TN, mView },
71 { 1, NULL, 0, 0, TN, NULL },
72 { 1, "Align View to &Workplane", MNU_ONTO_WORKPLANE, 'W', TN, mView },
73 { 1, "Nearest &Ortho View", MNU_NEAREST_ORTHO, F(2), TN, mView },
74 { 1, "Nearest &Isometric View", MNU_NEAREST_ISO, F(3), TN, mView },
75 { 1, "&Center View At Point", MNU_CENTER_VIEW, F(4), TN, mView },
76 { 1, NULL, 0, 0, TN, NULL },
77 { 1, "Show Snap &Grid", MNU_SHOW_GRID, '>', TC, mView },
78 { 1, "Use &Perspective Projection", MNU_PERSPECTIVE_PROJ,'`', TC, mView },
79 { 1, NULL, 0, 0, TN, NULL },
80 #if defined(__APPLE__)
81 { 1, "Show Menu &Bar", MNU_SHOW_MENU_BAR, C|F(12), TC, mView },
82 #endif
83 { 1, "Show &Toolbar", MNU_SHOW_TOOLBAR, 0, TC, mView },
84 { 1, "Show Property Bro&wser", MNU_SHOW_TEXT_WND, '\t', TC, mView },
85 { 1, NULL, 0, 0, TN, NULL },
86 { 1, "Dimensions in &Inches", MNU_UNITS_INCHES, 0, TR, mView },
87 { 1, "Dimensions in &Millimeters", MNU_UNITS_MM, 0, TR, mView },
88 #if defined(HAVE_GTK) || defined(__APPLE__)
89 { 1, NULL, 0, 0, TN, NULL },
90 { 1, "&Full Screen", MNU_FULL_SCREEN, C|F(11), TC, mView },
91 #endif
92
93 { 0, "&New Group", 0, 0, TN, NULL },
94 { 1, "Sketch In &3d", MNU_GROUP_3D, S|'3', TN, mGrp },
95 { 1, "Sketch In New &Workplane", MNU_GROUP_WRKPL, S|'W', TN, mGrp },
96 { 1, NULL, 0, 0, TN, NULL },
97 { 1, "Step &Translating", MNU_GROUP_TRANS, S|'T', TN, mGrp },
98 { 1, "Step &Rotating", MNU_GROUP_ROT, S|'R', TN, mGrp },
99 { 1, NULL, 0, 0, TN, NULL },
100 { 1, "E&xtrude", MNU_GROUP_EXTRUDE, S|'X', TN, mGrp },
101 { 1, "&Lathe", MNU_GROUP_LATHE, S|'L', TN, mGrp },
102 { 1, NULL, 0, 0, TN, NULL },
103 { 1, "Link / Assemble...", MNU_GROUP_LINK, S|'I', TN, mGrp },
104 { 1, "Link Recent", MNU_GROUP_RECENT, 0, TN, mGrp },
105
106 { 0, "&Sketch", 0, 0, TN, NULL },
107 { 1, "In &Workplane", MNU_SEL_WORKPLANE, '2', TR, mReq },
108 { 1, "Anywhere In &3d", MNU_FREE_IN_3D, '3', TR, mReq },
109 { 1, NULL, 0, 0, TN, NULL },
110 { 1, "Datum &Point", MNU_DATUM_POINT, 'P', TN, mReq },
111 { 1, "&Workplane", MNU_WORKPLANE, 0, TN, mReq },
112 { 1, NULL, 0, 0, TN, NULL },
113 { 1, "Line &Segment", MNU_LINE_SEGMENT, 'S', TN, mReq },
114 { 1, "C&onstruction Line Segment", MNU_CONSTR_SEGMENT, S|'S', TN, mReq },
115 { 1, "&Rectangle", MNU_RECTANGLE, 'R', TN, mReq },
116 { 1, "&Circle", MNU_CIRCLE, 'C', TN, mReq },
117 { 1, "&Arc of a Circle", MNU_ARC, 'A', TN, mReq },
118 { 1, "&Bezier Cubic Spline", MNU_CUBIC, 'B', TN, mReq },
119 { 1, NULL, 0, 0, TN, NULL },
120 { 1, "&Text in TrueType Font", MNU_TTF_TEXT, 'T', TN, mReq },
121 { 1, NULL, 0, 0, TN, NULL },
122 { 1, "To&ggle Construction", MNU_CONSTRUCTION, 'G', TN, mReq },
123 { 1, "Tangent &Arc at Point", MNU_TANGENT_ARC, S|'A', TN, mReq },
124 { 1, "Split Curves at &Intersection", MNU_SPLIT_CURVES, 'I', TN, mReq },
125
126 { 0, "&Constrain", 0, 0, TN, NULL },
127 { 1, "&Distance / Diameter", MNU_DISTANCE_DIA, 'D', TN, mCon },
128 { 1, "Re&ference Dimension", MNU_REF_DISTANCE, S|'D', TN, mCon },
129 { 1, "A&ngle", MNU_ANGLE, 'N', TN, mCon },
130 { 1, "Reference An&gle", MNU_REF_ANGLE, S|'N', TN, mCon },
131 { 1, "Other S&upplementary Angle", MNU_OTHER_ANGLE, 'U', TN, mCon },
132 { 1, "Toggle R&eference Dim", MNU_REFERENCE, 'E', TN, mCon },
133 { 1, NULL, 0, 0, TN, NULL },
134 { 1, "&Horizontal", MNU_HORIZONTAL, 'H', TN, mCon },
135 { 1, "&Vertical", MNU_VERTICAL, 'V', TN, mCon },
136 { 1, NULL, 0, 0, TN, NULL },
137 { 1, "&On Point / Curve / Plane", MNU_ON_ENTITY, 'O', TN, mCon },
138 { 1, "E&qual Length / Radius / Angle", MNU_EQUAL, 'Q', TN, mCon },
139 { 1, "Length Ra&tio", MNU_RATIO, 'Z', TN, mCon },
140 { 1, "Length Diff&erence", MNU_DIFFERENCE, 'J', TN, mCon },
141 { 1, "At &Midpoint", MNU_AT_MIDPOINT, 'M', TN, mCon },
142 { 1, "S&ymmetric", MNU_SYMMETRIC, 'Y', TN, mCon },
143 { 1, "Para&llel / Tangent", MNU_PARALLEL, 'L', TN, mCon },
144 { 1, "&Perpendicular", MNU_PERPENDICULAR, '[', TN, mCon },
145 { 1, "Same Orient&ation", MNU_ORIENTED_SAME, 'X', TN, mCon },
146 { 1, "Lock Point Where &Dragged", MNU_WHERE_DRAGGED, ']', TN, mCon },
147 { 1, NULL, 0, 0, TN, NULL },
148 { 1, "Comment", MNU_COMMENT, ';', TN, mCon },
149
150 { 0, "&Analyze", 0, 0, TN, NULL },
151 { 1, "Measure &Volume", MNU_VOLUME, C|S|'V', TN, mAna },
152 { 1, "Measure &Area", MNU_AREA, C|S|'A', TN, mAna },
153 { 1, "Show &Interfering Parts", MNU_INTERFERENCE, C|S|'I', TN, mAna },
154 { 1, "Show &Naked Edges", MNU_NAKED_EDGES, C|S|'N', TN, mAna },
155 { 1, NULL, 0, 0, TN, NULL },
156 { 1, "Show Degrees of &Freedom", MNU_SHOW_DOF, C|S|'F', TN, mAna },
157 { 1, NULL, 0, 0, TN, NULL },
158 { 1, "&Trace Point", MNU_TRACE_PT, C|S|'T', TN, mAna },
159 { 1, "&Stop Tracing...", MNU_STOP_TRACING, C|S|'S', TN, mAna },
160 { 1, "Step &Dimension...", MNU_STEP_DIM, C|S|'D', TN, mAna },
161
162 { 0, "&Help", 0, 0, TN, NULL },
163 { 1, "&Website / Manual", MNU_WEBSITE, 0, TN, mHelp },
164 #ifndef __APPLE__
165 { 1, "&About", MNU_ABOUT, 0, TN, mHelp },
166 #endif
167
168 { -1, 0, 0, 0, TN, 0 }
169 };
170
171 #undef DEL
172 #undef ESC
173 #undef S
174 #undef C
175 #undef F
176 #undef TN
177 #undef TC
178 #undef TR
179
MakeAcceleratorLabel(int accel)180 std::string SolveSpace::MakeAcceleratorLabel(int accel) {
181 if(!accel) return "";
182
183 std::string label;
184 if(accel & GraphicsWindow::CTRL_MASK) {
185 label += "Ctrl+";
186 }
187 if(accel & GraphicsWindow::SHIFT_MASK) {
188 label += "Shift+";
189 }
190 if(accel >= GraphicsWindow::FUNCTION_KEY_BASE + 1 &&
191 accel <= GraphicsWindow::FUNCTION_KEY_BASE + 12) {
192 label += ssprintf("F%d", accel - GraphicsWindow::FUNCTION_KEY_BASE);
193 } else if(accel == '\t') {
194 label += "Tab";
195 } else if(accel == ' ') {
196 label += "Space";
197 } else if(accel == GraphicsWindow::ESCAPE_KEY) {
198 label += "Esc";
199 } else if(accel == GraphicsWindow::DELETE_KEY) {
200 label += "Del";
201 } else {
202 label += (char)(accel & 0xff);
203 }
204 return label;
205 }
206
Init(void)207 void GraphicsWindow::Init(void) {
208 scale = 5;
209 offset = Vector::From(0, 0, 0);
210 projRight = Vector::From(1, 0, 0);
211 projUp = Vector::From(0, 1, 0);
212
213 // Make sure those are valid; could get a mouse move without a mouse
214 // down if someone depresses the button, then drags into our window.
215 orig.projRight = projRight;
216 orig.projUp = projUp;
217
218 // And with the last group active
219 activeGroup = SK.groupOrder.elem[SK.groupOrder.n - 1];
220 SK.GetGroup(activeGroup)->Activate();
221
222 showWorkplanes = false;
223 showNormals = true;
224 showPoints = true;
225 showConstraints = true;
226 showHdnLines = false;
227 showShaded = true;
228 showEdges = true;
229 showMesh = false;
230 showOutlines = false;
231
232 showTextWindow = true;
233 ShowTextWindow(showTextWindow);
234
235 showSnapGrid = false;
236 context.active = false;
237
238 // Do this last, so that all the menus get updated correctly.
239 ClearSuper();
240 }
241
AnimateOntoWorkplane(void)242 void GraphicsWindow::AnimateOntoWorkplane(void) {
243 if(!LockedInWorkplane()) return;
244
245 Entity *w = SK.GetEntity(ActiveWorkplane());
246 Quaternion quatf = w->Normal()->NormalGetNum();
247 Vector offsetf = (SK.GetEntity(w->point[0])->PointGetNum()).ScaledBy(-1);
248
249 AnimateOnto(quatf, offsetf);
250 }
251
AnimateOnto(Quaternion quatf,Vector offsetf)252 void GraphicsWindow::AnimateOnto(Quaternion quatf, Vector offsetf) {
253 // Get our initial orientation and translation.
254 Quaternion quat0 = Quaternion::From(projRight, projUp);
255 Vector offset0 = offset;
256
257 // Make sure we take the shorter of the two possible paths.
258 double mp = (quatf.Minus(quat0)).Magnitude();
259 double mm = (quatf.Plus(quat0)).Magnitude();
260 if(mp > mm) {
261 quatf = quatf.ScaledBy(-1);
262 mp = mm;
263 }
264 double mo = (offset0.Minus(offsetf)).Magnitude()*scale;
265
266 // Animate transition, unless it's a tiny move.
267 int32_t dt = (mp < 0.01 && mo < 10) ? (-20) :
268 (int32_t)(100 + 1000*mp + 0.4*mo);
269 // Don't ever animate for longer than 2000 ms; we can get absurdly
270 // long translations (as measured in pixels) if the user zooms out, moves,
271 // and then zooms in again.
272 if(dt > 2000) dt = 2000;
273 int64_t tn, t0 = GetMilliseconds();
274 double s = 0;
275 Quaternion dq = quatf.Times(quat0.Inverse());
276 do {
277 offset = (offset0.ScaledBy(1 - s)).Plus(offsetf.ScaledBy(s));
278 Quaternion quat = (dq.ToThe(s)).Times(quat0);
279 quat = quat.WithMagnitude(1);
280
281 projRight = quat.RotationU();
282 projUp = quat.RotationV();
283 PaintGraphics();
284
285 tn = GetMilliseconds();
286 s = (tn - t0)/((double)dt);
287 } while((tn - t0) < dt);
288
289 projRight = quatf.RotationU();
290 projUp = quatf.RotationV();
291 offset = offsetf;
292 InvalidateGraphics();
293 // If the view screen is open, then we need to refresh it.
294 SS.ScheduleShowTW();
295 }
296
HandlePointForZoomToFit(Vector p,Point2d * pmax,Point2d * pmin,double * wmin,bool usePerspective)297 void GraphicsWindow::HandlePointForZoomToFit(Vector p, Point2d *pmax, Point2d *pmin,
298 double *wmin, bool usePerspective)
299 {
300 double w;
301 Vector pp = ProjectPoint4(p, &w);
302 // If usePerspective is true, then we calculate a perspective projection of the point.
303 // If not, then we do a parallel projection regardless of the current
304 // scale factor.
305 if(usePerspective) {
306 pp = pp.ScaledBy(1.0/w);
307 }
308
309 pmax->x = max(pmax->x, pp.x);
310 pmax->y = max(pmax->y, pp.y);
311 pmin->x = min(pmin->x, pp.x);
312 pmin->y = min(pmin->y, pp.y);
313 *wmin = min(*wmin, w);
314 }
LoopOverPoints(const std::vector<Entity * > & entities,const std::vector<hEntity> & faces,Point2d * pmax,Point2d * pmin,double * wmin,bool usePerspective,bool includeMesh)315 void GraphicsWindow::LoopOverPoints(const std::vector<Entity *> &entities,
316 const std::vector<hEntity> &faces,
317 Point2d *pmax, Point2d *pmin, double *wmin,
318 bool usePerspective, bool includeMesh) {
319
320 int i, j;
321 for(Entity *e : entities) {
322 if(e->IsPoint()) {
323 HandlePointForZoomToFit(e->PointGetNum(), pmax, pmin, wmin, usePerspective);
324 } else if(e->type == Entity::CIRCLE) {
325 // Lots of entities can extend outside the bbox of their points,
326 // but circles are particularly bad. We want to get things halfway
327 // reasonable without the mesh, because a zoom to fit is used to
328 // set the zoom level to set the chord tol.
329 double r = e->CircleGetRadiusNum();
330 Vector c = SK.GetEntity(e->point[0])->PointGetNum();
331 Quaternion q = SK.GetEntity(e->normal)->NormalGetNum();
332 for(j = 0; j < 4; j++) {
333 Vector p = (j == 0) ? (c.Plus(q.RotationU().ScaledBy( r))) :
334 (j == 1) ? (c.Plus(q.RotationU().ScaledBy(-r))) :
335 (j == 2) ? (c.Plus(q.RotationV().ScaledBy( r))) :
336 (c.Plus(q.RotationV().ScaledBy(-r)));
337 HandlePointForZoomToFit(p, pmax, pmin, wmin, usePerspective);
338 }
339 } else {
340 // We have to iterate children points, because we can select entites without points
341 for(int i = 0; i < MAX_POINTS_IN_ENTITY; i++) {
342 if(e->point[i].v == 0) break;
343 Vector p = SK.GetEntity(e->point[i])->PointGetNum();
344 HandlePointForZoomToFit(p, pmax, pmin, wmin, usePerspective);
345 }
346 }
347 }
348
349 if(!includeMesh && faces.empty()) return;
350
351 Group *g = SK.GetGroup(activeGroup);
352 g->GenerateDisplayItems();
353 for(i = 0; i < g->displayMesh.l.n; i++) {
354 STriangle *tr = &(g->displayMesh.l.elem[i]);
355 if(!includeMesh) {
356 bool found = false;
357 for(const hEntity &face : faces) {
358 if(face.v != tr->meta.face) continue;
359 found = true;
360 break;
361 }
362 if(!found) continue;
363 }
364 HandlePointForZoomToFit(tr->a, pmax, pmin, wmin, usePerspective);
365 HandlePointForZoomToFit(tr->b, pmax, pmin, wmin, usePerspective);
366 HandlePointForZoomToFit(tr->c, pmax, pmin, wmin, usePerspective);
367 }
368 if(!includeMesh) return;
369 for(i = 0; i < g->polyLoops.l.n; i++) {
370 SContour *sc = &(g->polyLoops.l.elem[i]);
371 for(j = 0; j < sc->l.n; j++) {
372 HandlePointForZoomToFit(sc->l.elem[j].p, pmax, pmin, wmin, usePerspective);
373 }
374 }
375 }
ZoomToFit(bool includingInvisibles,bool useSelection)376 void GraphicsWindow::ZoomToFit(bool includingInvisibles, bool useSelection) {
377 std::vector<Entity *> entities;
378 std::vector<hEntity> faces;
379
380 if(useSelection) {
381 for(int i = 0; i < selection.n; i++) {
382 Selection *s = &selection.elem[i];
383 if(s->entity.v == 0) continue;
384 Entity *e = SK.entity.FindById(s->entity);
385 if(e->IsFace()) {
386 faces.push_back(e->h);
387 continue;
388 }
389 entities.push_back(e);
390 }
391 }
392
393 bool selectionUsed = !entities.empty() || !faces.empty();
394
395 if(!selectionUsed) {
396 for(int i = 0; i<SK.entity.n; i++) {
397 Entity *e = &(SK.entity.elem[i]);
398 // we don't want to handle separate points, because we will iterate them inside entities.
399 if(e->IsPoint()) continue;
400 if(!includingInvisibles && !e->IsVisible()) continue;
401 entities.push_back(e);
402 }
403 }
404
405 // On the first run, ignore perspective.
406 Point2d pmax = { -1e12, -1e12 }, pmin = { 1e12, 1e12 };
407 double wmin = 1;
408 LoopOverPoints(entities, faces, &pmax, &pmin, &wmin,
409 /*usePerspective=*/false, /*includeMesh=*/!selectionUsed);
410
411 double xm = (pmax.x + pmin.x)/2, ym = (pmax.y + pmin.y)/2;
412 double dx = pmax.x - pmin.x, dy = pmax.y - pmin.y;
413
414 offset = offset.Plus(projRight.ScaledBy(-xm)).Plus(
415 projUp. ScaledBy(-ym));
416
417 // And based on this, we calculate the scale and offset
418 if(EXACT(dx == 0 && dy == 0)) {
419 scale = 5;
420 } else {
421 double scalex = 1e12, scaley = 1e12;
422 if(EXACT(dx != 0)) scalex = 0.9*width /dx;
423 if(EXACT(dy != 0)) scaley = 0.9*height/dy;
424 scale = min(scalex, scaley);
425
426 scale = min(300.0, scale);
427 scale = max(0.003, scale);
428 }
429
430 // Then do another run, considering the perspective.
431 pmax.x = -1e12; pmax.y = -1e12;
432 pmin.x = 1e12; pmin.y = 1e12;
433 wmin = 1;
434 LoopOverPoints(entities, faces, &pmax, &pmin, &wmin,
435 /*usePerspective=*/true, /*includeMesh=*/!selectionUsed);
436
437 // Adjust the scale so that no points are behind the camera
438 if(wmin < 0.1) {
439 double k = SS.CameraTangent();
440 // w = 1+k*scale*z
441 double zmin = (wmin - 1)/(k*scale);
442 // 0.1 = 1 + k*scale*zmin
443 // (0.1 - 1)/(k*zmin) = scale
444 scale = min(scale, (0.1 - 1)/(k*zmin));
445 }
446 }
447
MenuView(int id)448 void GraphicsWindow::MenuView(int id) {
449 switch(id) {
450 case MNU_ZOOM_IN:
451 SS.GW.scale *= 1.2;
452 SS.ScheduleShowTW();
453 break;
454
455 case MNU_ZOOM_OUT:
456 SS.GW.scale /= 1.2;
457 SS.ScheduleShowTW();
458 break;
459
460 case MNU_ZOOM_TO_FIT:
461 SS.GW.ZoomToFit(/*includingInvisibles=*/false, /*useSelection=*/true);
462 SS.ScheduleShowTW();
463 break;
464
465 case MNU_SHOW_GRID:
466 SS.GW.showSnapGrid = !SS.GW.showSnapGrid;
467 if(SS.GW.showSnapGrid && !SS.GW.LockedInWorkplane()) {
468 Message("No workplane is active, so the grid will not "
469 "appear.");
470 }
471 SS.GW.EnsureValidActives();
472 InvalidateGraphics();
473 break;
474
475 case MNU_PERSPECTIVE_PROJ:
476 SS.usePerspectiveProj = !SS.usePerspectiveProj;
477 if(SS.cameraTangent < 1e-6) {
478 Error("The perspective factor is set to zero, so the view will "
479 "always be a parallel projection.\n\n"
480 "For a perspective projection, modify the perspective "
481 "factor in the configuration screen. A value around 0.3 "
482 "is typical.");
483 }
484 SS.GW.EnsureValidActives();
485 InvalidateGraphics();
486 break;
487
488 case MNU_ONTO_WORKPLANE:
489 if(SS.GW.LockedInWorkplane()) {
490 SS.GW.AnimateOntoWorkplane();
491 SS.ScheduleShowTW();
492 break;
493 } // if not in 2d mode fall through and use ORTHO logic
494 case MNU_NEAREST_ORTHO:
495 case MNU_NEAREST_ISO: {
496 static const Vector ortho[3] = {
497 Vector::From(1, 0, 0),
498 Vector::From(0, 1, 0),
499 Vector::From(0, 0, 1)
500 };
501 double sqrt2 = sqrt(2.0), sqrt6 = sqrt(6.0);
502 Quaternion quat0 = Quaternion::From(SS.GW.projRight, SS.GW.projUp);
503 Quaternion quatf = quat0;
504 double dmin = 1e10;
505
506 // There are 24 possible views; 3*2*2*2
507 int i, j, negi, negj;
508 for(i = 0; i < 3; i++) {
509 for(j = 0; j < 3; j++) {
510 if(i == j) continue;
511 for(negi = 0; negi < 2; negi++) {
512 for(negj = 0; negj < 2; negj++) {
513 Vector ou = ortho[i], ov = ortho[j];
514 if(negi) ou = ou.ScaledBy(-1);
515 if(negj) ov = ov.ScaledBy(-1);
516 Vector on = ou.Cross(ov);
517
518 Vector u, v;
519 if(id == MNU_NEAREST_ORTHO || id == MNU_ONTO_WORKPLANE) {
520 u = ou;
521 v = ov;
522 } else {
523 u =
524 ou.ScaledBy(1/sqrt2).Plus(
525 on.ScaledBy(-1/sqrt2));
526 v =
527 ou.ScaledBy(-1/sqrt6).Plus(
528 ov.ScaledBy(2/sqrt6).Plus(
529 on.ScaledBy(-1/sqrt6)));
530 }
531
532 Quaternion quatt = Quaternion::From(u, v);
533 double d = min(
534 (quatt.Minus(quat0)).Magnitude(),
535 (quatt.Plus(quat0)).Magnitude());
536 if(d < dmin) {
537 dmin = d;
538 quatf = quatt;
539 }
540 }
541 }
542 }
543 }
544
545 SS.GW.AnimateOnto(quatf, SS.GW.offset);
546 break;
547 }
548
549 case MNU_CENTER_VIEW:
550 SS.GW.GroupSelection();
551 if(SS.GW.gs.n == 1 && SS.GW.gs.points == 1) {
552 Quaternion quat0;
553 // Offset is the selected point, quaternion is same as before
554 Vector pt = SK.GetEntity(SS.GW.gs.point[0])->PointGetNum();
555 quat0 = Quaternion::From(SS.GW.projRight, SS.GW.projUp);
556 SS.GW.AnimateOnto(quat0, pt.ScaledBy(-1));
557 SS.GW.ClearSelection();
558 } else {
559 Error("Select a point; this point will become the center "
560 "of the view on screen.");
561 }
562 break;
563
564 case MNU_SHOW_MENU_BAR:
565 ToggleMenuBar();
566 SS.GW.EnsureValidActives();
567 InvalidateGraphics();
568 break;
569
570 case MNU_SHOW_TOOLBAR:
571 SS.showToolbar = !SS.showToolbar;
572 SS.GW.EnsureValidActives();
573 InvalidateGraphics();
574 break;
575
576 case MNU_SHOW_TEXT_WND:
577 SS.GW.showTextWindow = !SS.GW.showTextWindow;
578 SS.GW.EnsureValidActives();
579 break;
580
581 case MNU_UNITS_INCHES:
582 SS.viewUnits = SolveSpaceUI::UNIT_INCHES;
583 SS.ScheduleShowTW();
584 SS.GW.EnsureValidActives();
585 break;
586
587 case MNU_UNITS_MM:
588 SS.viewUnits = SolveSpaceUI::UNIT_MM;
589 SS.ScheduleShowTW();
590 SS.GW.EnsureValidActives();
591 break;
592
593 case MNU_FULL_SCREEN:
594 ToggleFullScreen();
595 SS.GW.EnsureValidActives();
596 break;
597
598 default: oops();
599 }
600 InvalidateGraphics();
601 }
602
EnsureValidActives(void)603 void GraphicsWindow::EnsureValidActives(void) {
604 bool change = false;
605 // The active group must exist, and not be the references.
606 Group *g = SK.group.FindByIdNoOops(activeGroup);
607 if((!g) || (g->h.v == Group::HGROUP_REFERENCES.v)) {
608 int i;
609 for(i = 0; i < SK.groupOrder.n; i++) {
610 if(SK.groupOrder.elem[i].v != Group::HGROUP_REFERENCES.v) {
611 break;
612 }
613 }
614 if(i >= SK.groupOrder.n) {
615 // This can happen if the user deletes all the groups in the
616 // sketch. It's difficult to prevent that, because the last
617 // group might have been deleted automatically, because it failed
618 // a dependency. There needs to be something, so create a plane
619 // drawing group and activate that. They should never be able
620 // to delete the references, though.
621 activeGroup = SS.CreateDefaultDrawingGroup();
622 // We've created the default group, but not the workplane entity;
623 // do it now so that drawing mode isn't switched to "Free in 3d".
624 SS.GenerateAll(SolveSpaceUI::GENERATE_ALL);
625 } else {
626 activeGroup = SK.groupOrder.elem[i];
627 }
628 SK.GetGroup(activeGroup)->Activate();
629 change = true;
630 }
631
632 // The active coordinate system must also exist.
633 if(LockedInWorkplane()) {
634 Entity *e = SK.entity.FindByIdNoOops(ActiveWorkplane());
635 if(e) {
636 hGroup hgw = e->group;
637 if(hgw.v != activeGroup.v && SS.GroupsInOrder(activeGroup, hgw)) {
638 // The active workplane is in a group that comes after the
639 // active group; so any request or constraint will fail.
640 SetWorkplaneFreeIn3d();
641 change = true;
642 }
643 } else {
644 SetWorkplaneFreeIn3d();
645 change = true;
646 }
647 }
648
649 // And update the checked state for various menus
650 bool locked = LockedInWorkplane();
651 RadioMenuById(MNU_FREE_IN_3D, !locked);
652 RadioMenuById(MNU_SEL_WORKPLANE, locked);
653
654 SS.UndoEnableMenus();
655
656 switch(SS.viewUnits) {
657 case SolveSpaceUI::UNIT_MM:
658 case SolveSpaceUI::UNIT_INCHES:
659 break;
660 default:
661 SS.viewUnits = SolveSpaceUI::UNIT_MM;
662 break;
663 }
664 RadioMenuById(MNU_UNITS_MM, SS.viewUnits == SolveSpaceUI::UNIT_MM);
665 RadioMenuById(MNU_UNITS_INCHES, SS.viewUnits == SolveSpaceUI::UNIT_INCHES);
666
667 ShowTextWindow(SS.GW.showTextWindow);
668 CheckMenuById(MNU_SHOW_TEXT_WND, SS.GW.showTextWindow);
669
670 #if defined(__APPLE__)
671 CheckMenuById(MNU_SHOW_MENU_BAR, MenuBarIsVisible());
672 #endif
673 CheckMenuById(MNU_SHOW_TOOLBAR, SS.showToolbar);
674 CheckMenuById(MNU_PERSPECTIVE_PROJ, SS.usePerspectiveProj);
675 CheckMenuById(MNU_SHOW_GRID, SS.GW.showSnapGrid);
676 #if defined(HAVE_GTK) || defined(__APPLE__)
677 CheckMenuById(MNU_FULL_SCREEN, FullScreenIsActive());
678 #endif
679
680 if(change) SS.ScheduleShowTW();
681 }
682
SetWorkplaneFreeIn3d(void)683 void GraphicsWindow::SetWorkplaneFreeIn3d(void) {
684 SK.GetGroup(activeGroup)->activeWorkplane = Entity::FREE_IN_3D;
685 }
ActiveWorkplane(void)686 hEntity GraphicsWindow::ActiveWorkplane(void) {
687 Group *g = SK.group.FindByIdNoOops(activeGroup);
688 if(g) {
689 return g->activeWorkplane;
690 } else {
691 return Entity::FREE_IN_3D;
692 }
693 }
LockedInWorkplane(void)694 bool GraphicsWindow::LockedInWorkplane(void) {
695 return (SS.GW.ActiveWorkplane().v != Entity::FREE_IN_3D.v);
696 }
697
ForceTextWindowShown(void)698 void GraphicsWindow::ForceTextWindowShown(void) {
699 if(!showTextWindow) {
700 showTextWindow = true;
701 CheckMenuById(MNU_SHOW_TEXT_WND, true);
702 ShowTextWindow(true);
703 }
704 }
705
DeleteTaggedRequests(void)706 void GraphicsWindow::DeleteTaggedRequests(void) {
707 // Rewrite any point-coincident constraints that were affected by this
708 // deletion.
709 Request *r;
710 for(r = SK.request.First(); r; r = SK.request.NextAfter(r)) {
711 if(!r->tag) continue;
712 FixConstraintsForRequestBeingDeleted(r->h);
713 }
714 // and then delete the tagged requests.
715 SK.request.RemoveTagged();
716
717 // An edit might be in progress for the just-deleted item. So
718 // now it's not.
719 HideGraphicsEditControl();
720 SS.TW.HideEditControl();
721 // And clear out the selection, which could contain that item.
722 ClearSuper();
723 // And regenerate to get rid of what it generates, plus anything
724 // that references it (since the regen code checks for that).
725 SS.GenerateAll(SolveSpaceUI::GENERATE_ALL);
726 EnsureValidActives();
727 SS.ScheduleShowTW();
728 }
729
SnapToGrid(Vector p)730 Vector GraphicsWindow::SnapToGrid(Vector p) {
731 if(!LockedInWorkplane()) return p;
732
733 EntityBase *wrkpl = SK.GetEntity(ActiveWorkplane()),
734 *norm = wrkpl->Normal();
735 Vector wo = SK.GetEntity(wrkpl->point[0])->PointGetNum(),
736 wu = norm->NormalU(),
737 wv = norm->NormalV(),
738 wn = norm->NormalN();
739
740 Vector pp = (p.Minus(wo)).DotInToCsys(wu, wv, wn);
741 pp.x = floor((pp.x / SS.gridSpacing) + 0.5)*SS.gridSpacing;
742 pp.y = floor((pp.y / SS.gridSpacing) + 0.5)*SS.gridSpacing;
743 pp.z = 0;
744
745 return pp.ScaleOutOfCsys(wu, wv, wn).Plus(wo);
746 }
747
MenuEdit(int id)748 void GraphicsWindow::MenuEdit(int id) {
749 switch(id) {
750 case MNU_UNSELECT_ALL:
751 SS.GW.GroupSelection();
752 // If there's nothing selected to de-select, and no operation
753 // to cancel, then perhaps they want to return to the home
754 // screen in the text window.
755 if(SS.GW.gs.n == 0 &&
756 SS.GW.gs.constraints == 0 &&
757 SS.GW.pending.operation == 0)
758 {
759 if(!(TextEditControlIsVisible() ||
760 GraphicsEditControlIsVisible()))
761 {
762 if(SS.TW.shown.screen == TextWindow::SCREEN_STYLE_INFO) {
763 SS.TW.GoToScreen(TextWindow::SCREEN_LIST_OF_STYLES);
764 } else {
765 SS.TW.ClearSuper();
766 }
767 }
768 }
769 SS.GW.ClearSuper();
770 SS.TW.HideEditControl();
771 SS.nakedEdges.Clear();
772 SS.justExportedInfo.draw = false;
773 // This clears the marks drawn to indicate which points are
774 // still free to drag.
775 Param *p;
776 for(p = SK.param.First(); p; p = SK.param.NextAfter(p)) {
777 p->free = false;
778 }
779 if(SS.exportMode) {
780 SS.exportMode = false;
781 SS.GenerateAll(SolveSpaceUI::GENERATE_ALL);
782 }
783 break;
784
785 case MNU_SELECT_ALL: {
786 Entity *e;
787 for(e = SK.entity.First(); e; e = SK.entity.NextAfter(e)) {
788 if(e->group.v != SS.GW.activeGroup.v) continue;
789 if(e->IsFace() || e->IsDistance()) continue;
790 if(!e->IsVisible()) continue;
791
792 SS.GW.MakeSelected(e->h);
793 }
794 InvalidateGraphics();
795 SS.ScheduleShowTW();
796 break;
797 }
798
799 case MNU_SELECT_CHAIN: {
800 Entity *e;
801 int newlySelected = 0;
802 bool didSomething;
803 do {
804 didSomething = false;
805 for(e = SK.entity.First(); e; e = SK.entity.NextAfter(e)) {
806 if(e->group.v != SS.GW.activeGroup.v) continue;
807 if(!e->HasEndpoints()) continue;
808 if(!e->IsVisible()) continue;
809
810 Vector st = e->EndpointStart(),
811 fi = e->EndpointFinish();
812
813 bool onChain = false, alreadySelected = false;
814 List<Selection> *ls = &(SS.GW.selection);
815 for(Selection *s = ls->First(); s; s = ls->NextAfter(s)) {
816 if(!s->entity.v) continue;
817 if(s->entity.v == e->h.v) {
818 alreadySelected = true;
819 continue;
820 }
821 Entity *se = SK.GetEntity(s->entity);
822 if(!se->HasEndpoints()) continue;
823
824 Vector sst = se->EndpointStart(),
825 sfi = se->EndpointFinish();
826
827 if(sst.Equals(st) || sst.Equals(fi) ||
828 sfi.Equals(st) || sfi.Equals(fi))
829 {
830 onChain = true;
831 }
832 }
833 if(onChain && !alreadySelected) {
834 SS.GW.MakeSelected(e->h);
835 newlySelected++;
836 didSomething = true;
837 }
838 }
839 } while(didSomething);
840 if(newlySelected == 0) {
841 Error("No additional entities share endpoints with the "
842 "selected entities.");
843 }
844 InvalidateGraphics();
845 SS.ScheduleShowTW();
846 break;
847 }
848
849 case MNU_ROTATE_90: {
850 SS.GW.GroupSelection();
851 Entity *e = NULL;
852 if(SS.GW.gs.n == 1 && SS.GW.gs.points == 1) {
853 e = SK.GetEntity(SS.GW.gs.point[0]);
854 } else if(SS.GW.gs.n == 1 && SS.GW.gs.entities == 1) {
855 e = SK.GetEntity(SS.GW.gs.entity[0]);
856 }
857 SS.GW.ClearSelection();
858
859 hGroup hg = e ? e->group : SS.GW.activeGroup;
860 Group *g = SK.GetGroup(hg);
861 if(g->type != Group::LINKED) {
862 Error("To use this command, select a point or other "
863 "entity from an linked part, or make a link "
864 "group the active group.");
865 break;
866 }
867
868
869 SS.UndoRemember();
870 // Rotate by ninety degrees about the coordinate axis closest
871 // to the screen normal.
872 Vector norm = SS.GW.projRight.Cross(SS.GW.projUp);
873 norm = norm.ClosestOrtho();
874 norm = norm.WithMagnitude(1);
875 Quaternion qaa = Quaternion::From(norm, PI/2);
876
877 g->TransformImportedBy(Vector::From(0, 0, 0), qaa);
878
879 // and regenerate as necessary.
880 SS.MarkGroupDirty(hg);
881 SS.GenerateAll();
882 break;
883 }
884
885 case MNU_SNAP_TO_GRID: {
886 if(!SS.GW.LockedInWorkplane()) {
887 Error("No workplane is active. Select a workplane to define "
888 "the plane for the snap grid.");
889 break;
890 }
891 SS.GW.GroupSelection();
892 if(SS.GW.gs.points == 0 && SS.GW.gs.constraintLabels == 0) {
893 Error("Can't snap these items to grid; select points, "
894 "text comments, or constraints with a label. "
895 "To snap a line, select its endpoints.");
896 break;
897 }
898 SS.UndoRemember();
899
900 List<Selection> *ls = &(SS.GW.selection);
901 for(Selection *s = ls->First(); s; s = ls->NextAfter(s)) {
902 if(s->entity.v) {
903 hEntity hp = s->entity;
904 Entity *ep = SK.GetEntity(hp);
905 if(!ep->IsPoint()) continue;
906
907 Vector p = ep->PointGetNum();
908 ep->PointForceTo(SS.GW.SnapToGrid(p));
909 SS.GW.pending.points.Add(&hp);
910 SS.MarkGroupDirty(ep->group);
911 } else if(s->constraint.v) {
912 Constraint *c = SK.GetConstraint(s->constraint);
913 Vector refp = c->GetReferencePos();
914 c->disp.offset = c->disp.offset.Plus(SS.GW.SnapToGrid(refp).Minus(refp));
915 }
916 }
917 // Regenerate, with these points marked as dragged so that they
918 // get placed as close as possible to our snap grid.
919 SS.GenerateAll();
920 SS.GW.ClearPending();
921
922 SS.GW.ClearSelection();
923 InvalidateGraphics();
924 break;
925 }
926
927 case MNU_UNDO:
928 SS.UndoUndo();
929 break;
930
931 case MNU_REDO:
932 SS.UndoRedo();
933 break;
934
935 case MNU_REGEN_ALL:
936 SS.ReloadAllImported();
937 SS.GenerateAll(SolveSpaceUI::GENERATE_UNTIL_ACTIVE);
938 SS.ScheduleShowTW();
939 break;
940
941 default: oops();
942 }
943 }
944
MenuRequest(int id)945 void GraphicsWindow::MenuRequest(int id) {
946 const char *s;
947 switch(id) {
948 case MNU_SEL_WORKPLANE: {
949 SS.GW.GroupSelection();
950 Group *g = SK.GetGroup(SS.GW.activeGroup);
951
952 if(SS.GW.gs.n == 1 && SS.GW.gs.workplanes == 1) {
953 // A user-selected workplane
954 g->activeWorkplane = SS.GW.gs.entity[0];
955 } else if(g->type == Group::DRAWING_WORKPLANE) {
956 // The group's default workplane
957 g->activeWorkplane = g->h.entity(0);
958 Message("No workplane selected. Activating default workplane "
959 "for this group.");
960 }
961
962 if(!SS.GW.LockedInWorkplane()) {
963 Error("No workplane is selected, and the active group does "
964 "not have a default workplane. Try selecting a "
965 "workplane, or activating a sketch-in-new-workplane "
966 "group.");
967 break;
968 }
969 // Align the view with the selected workplane
970 SS.GW.AnimateOntoWorkplane();
971 SS.GW.ClearSuper();
972 SS.ScheduleShowTW();
973 break;
974 }
975 case MNU_FREE_IN_3D:
976 SS.GW.SetWorkplaneFreeIn3d();
977 SS.GW.EnsureValidActives();
978 SS.ScheduleShowTW();
979 InvalidateGraphics();
980 break;
981
982 case MNU_TANGENT_ARC:
983 SS.GW.GroupSelection();
984 if(SS.GW.gs.n == 1 && SS.GW.gs.points == 1) {
985 SS.GW.MakeTangentArc();
986 } else if(SS.GW.gs.n != 0) {
987 Error("Bad selection for tangent arc at point. Select a "
988 "single point, or select nothing to set up arc "
989 "parameters.");
990 } else {
991 SS.TW.GoToScreen(TextWindow::SCREEN_TANGENT_ARC);
992 SS.GW.ForceTextWindowShown();
993 SS.ScheduleShowTW();
994 InvalidateGraphics(); // repaint toolbar
995 }
996 break;
997
998 case MNU_ARC: s = "click point on arc (draws anti-clockwise)"; goto c;
999 case MNU_DATUM_POINT: s = "click to place datum point"; goto c;
1000 case MNU_LINE_SEGMENT: s = "click first point of line segment"; goto c;
1001 case MNU_CONSTR_SEGMENT: s = "click first point of construction line segment"; goto c;
1002 case MNU_CUBIC: s = "click first point of cubic segment"; goto c;
1003 case MNU_CIRCLE: s = "click center of circle"; goto c;
1004 case MNU_WORKPLANE: s = "click origin of workplane"; goto c;
1005 case MNU_RECTANGLE: s = "click one corner of rectangle"; goto c;
1006 case MNU_TTF_TEXT: s = "click top left of text"; goto c;
1007 c:
1008 SS.GW.pending.operation = id;
1009 SS.GW.pending.description = s;
1010 SS.ScheduleShowTW();
1011 InvalidateGraphics(); // repaint toolbar
1012 break;
1013
1014 case MNU_CONSTRUCTION: {
1015 SS.UndoRemember();
1016 SS.GW.GroupSelection();
1017 if(SS.GW.gs.entities == 0) {
1018 Error("No entities are selected. Select entities before "
1019 "trying to toggle their construction state.");
1020 }
1021 int i;
1022 for(i = 0; i < SS.GW.gs.entities; i++) {
1023 hEntity he = SS.GW.gs.entity[i];
1024 if(!he.isFromRequest()) continue;
1025 Request *r = SK.GetRequest(he.request());
1026 r->construction = !(r->construction);
1027 SS.MarkGroupDirty(r->group);
1028 }
1029 SS.GW.ClearSelection();
1030 SS.GenerateAll();
1031 break;
1032 }
1033
1034 case MNU_SPLIT_CURVES:
1035 SS.GW.SplitLinesOrCurves();
1036 break;
1037
1038 default: oops();
1039 }
1040 }
1041
ClearSuper(void)1042 void GraphicsWindow::ClearSuper(void) {
1043 HideGraphicsEditControl();
1044 ClearPending();
1045 ClearSelection();
1046 hover.Clear();
1047 EnsureValidActives();
1048 }
1049
ToggleBool(bool * v)1050 void GraphicsWindow::ToggleBool(bool *v) {
1051 *v = !*v;
1052
1053 // The faces are shown as special stippling on the shaded triangle mesh,
1054 // so not meaningful to show them and hide the shaded.
1055 if(!showShaded) showFaces = false;
1056
1057 // We might need to regenerate the mesh and edge list, since the edges
1058 // wouldn't have been generated if they were previously hidden.
1059 if(showEdges) (SK.GetGroup(activeGroup))->displayDirty = true;
1060
1061 SS.GenerateAll();
1062 InvalidateGraphics();
1063 SS.ScheduleShowTW();
1064 }
1065
SuggestLineConstraint(hRequest request)1066 GraphicsWindow::SuggestedConstraint GraphicsWindow::SuggestLineConstraint(hRequest request) {
1067 if(LockedInWorkplane()) {
1068 Entity *ptA = SK.GetEntity(request.entity(1)),
1069 *ptB = SK.GetEntity(request.entity(2));
1070
1071 Expr *au, *av, *bu, *bv;
1072
1073 ptA->PointGetExprsInWorkplane(ActiveWorkplane(), &au, &av);
1074 ptB->PointGetExprsInWorkplane(ActiveWorkplane(), &bu, &bv);
1075
1076 double du = au->Minus(bu)->Eval();
1077 double dv = av->Minus(bv)->Eval();
1078
1079 const double TOLERANCE_RATIO = 0.02;
1080 if(fabs(dv) > LENGTH_EPS && fabs(du / dv) < TOLERANCE_RATIO)
1081 return SUGGESTED_VERTICAL;
1082 else if(fabs(du) > LENGTH_EPS && fabs(dv / du) < TOLERANCE_RATIO)
1083 return SUGGESTED_HORIZONTAL;
1084 else
1085 return SUGGESTED_NONE;
1086 } else {
1087 return SUGGESTED_NONE;
1088 }
1089 }
1090