Curves: save active point to file
[blender.git] / source / blender / editors / space_view3d / view3d_select.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_select.c
28  *  \ingroup spview3d
29  */
30
31
32 #include <string.h>
33 #include <stdio.h>
34 #include <math.h>
35 #include <float.h>
36 #include <assert.h>
37
38 #include "DNA_action_types.h"
39 #include "DNA_armature_types.h"
40 #include "DNA_curve_types.h"
41 #include "DNA_meta_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_tracking_types.h"
47
48 #include "MEM_guardedalloc.h"
49
50 #include "BLI_math.h"
51 #include "BLI_lasso.h"
52 #include "BLI_rect.h"
53 #include "BLI_linklist.h"
54 #include "BLI_listbase.h"
55 #include "BLI_string.h"
56 #include "BLI_utildefines.h"
57
58 /* vertex box select */
59 #include "IMB_imbuf_types.h"
60 #include "IMB_imbuf.h"
61 #include "BKE_global.h"
62
63 #include "BKE_armature.h"
64 #include "BKE_context.h"
65 #include "BKE_curve.h"
66 #include "BKE_depsgraph.h"
67 #include "BKE_mball.h"
68 #include "BKE_mesh.h"
69 #include "BKE_movieclip.h"
70 #include "BKE_object.h"
71 #include "BKE_paint.h"
72 #include "BKE_editmesh.h"
73 #include "BKE_tracking.h"
74 #include "BKE_utildefines.h"
75
76
77 #include "BIF_gl.h"
78 #include "BIF_glutil.h"
79
80 #include "WM_api.h"
81 #include "WM_types.h"
82
83 #include "RNA_access.h"
84 #include "RNA_define.h"
85 #include "RNA_enum_types.h"
86
87 #include "ED_armature.h"
88 #include "ED_curve.h"
89 #include "ED_particle.h"
90 #include "ED_mesh.h"
91 #include "ED_object.h"
92 #include "ED_screen.h"
93 #include "ED_sculpt.h"
94 #include "ED_mball.h"
95
96 #include "UI_interface.h"
97 #include "UI_resources.h"
98
99 #include "view3d_intern.h"  /* own include */
100
101 /* TODO: should return whether there is valid context to continue */
102 void view3d_set_viewcontext(bContext *C, ViewContext *vc)
103 {
104         memset(vc, 0, sizeof(ViewContext));
105         vc->ar = CTX_wm_region(C);
106         vc->scene = CTX_data_scene(C);
107         vc->v3d = CTX_wm_view3d(C);
108         vc->rv3d = CTX_wm_region_view3d(C);
109         vc->obact = CTX_data_active_object(C);
110         vc->obedit = CTX_data_edit_object(C);
111 }
112
113 /*
114  * ob == NULL if you want global matrices
115  * */
116 void view3d_get_transformation(const ARegion *ar, RegionView3D *rv3d, Object *ob, bglMats *mats)
117 {
118         float cpy[4][4];
119         int i, j;
120
121         if (ob) {
122                 mul_m4_m4m4(cpy, rv3d->viewmat, ob->obmat);
123         }
124         else {
125                 copy_m4_m4(cpy, rv3d->viewmat);
126         }
127
128         for (i = 0; i < 4; ++i) {
129                 for (j = 0; j < 4; ++j) {
130                         mats->projection[i * 4 + j] = rv3d->winmat[i][j];
131                         mats->modelview[i * 4 + j] = cpy[i][j];
132                 }
133         }
134
135         mats->viewport[0] = ar->winrct.xmin;
136         mats->viewport[1] = ar->winrct.ymin;
137         mats->viewport[2] = ar->winx;
138         mats->viewport[3] = ar->winy;
139 }
140
141 /* ********************** view3d_select: selection manipulations ********************* */
142
143 /* local prototypes */
144
145 static void edbm_backbuf_check_and_select_verts(BMEditMesh *em, const bool select)
146 {
147         BMVert *eve;
148         BMIter iter;
149         unsigned int index = bm_wireoffs;
150
151         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
152                 if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
153                         if (EDBM_backbuf_check(index)) {
154                                 BM_vert_select_set(em->bm, eve, select);
155                         }
156                 }
157                 index++;
158         }
159 }
160
161 static void edbm_backbuf_check_and_select_edges(BMEditMesh *em, const bool select)
162 {
163         BMEdge *eed;
164         BMIter iter;
165         unsigned int index = bm_solidoffs;
166
167         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
168                 if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
169                         if (EDBM_backbuf_check(index)) {
170                                 BM_edge_select_set(em->bm, eed, select);
171                         }
172                 }
173                 index++;
174         }
175 }
176
177 static void edbm_backbuf_check_and_select_faces(BMEditMesh *em, const bool select)
178 {
179         BMFace *efa;
180         BMIter iter;
181         unsigned int index = 1;
182
183         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
184                 if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
185                         if (EDBM_backbuf_check(index)) {
186                                 BM_face_select_set(em->bm, efa, select);
187                         }
188                 }
189                 index++;
190         }
191 }
192
193
194 /* object mode, edbm_ prefix is confusing here, rename? */
195 static void edbm_backbuf_check_and_select_verts_obmode(Mesh *me, const bool select)
196 {
197         MVert *mv = me->mvert;
198         unsigned int index;
199
200         if (mv) {
201                 for (index = 1; index <= me->totvert; index++, mv++) {
202                         if (EDBM_backbuf_check(index)) {
203                                 if (!(mv->flag & ME_HIDE)) {
204                                         mv->flag = select ? (mv->flag | SELECT) : (mv->flag & ~SELECT);
205                                 }
206                         }
207                 }
208         }
209 }
210
211 /* object mode, edbm_ prefix is confusing here, rename? */
212 static void edbm_backbuf_check_and_select_tfaces(Mesh *me, const bool select)
213 {
214         MPoly *mpoly = me->mpoly;
215         unsigned int index;
216
217         if (mpoly) {
218                 for (index = 1; index <= me->totpoly; index++, mpoly++) {
219                         if (EDBM_backbuf_check(index)) {
220                                 mpoly->flag = select ? (mpoly->flag | ME_FACE_SEL) : (mpoly->flag & ~ME_FACE_SEL);
221                         }
222                 }
223         }
224 }
225
226 /* *********************** GESTURE AND LASSO ******************* */
227
228 typedef struct LassoSelectUserData {
229         ViewContext *vc;
230         const rcti *rect;
231         const rctf *rect_fl;
232         rctf       _rect_fl;
233         const int (*mcords)[2];
234         int moves;
235         bool select;
236
237         /* runtime */
238         int pass;
239         bool is_done;
240         bool is_changed;
241 } LassoSelectUserData;
242
243 static void view3d_userdata_lassoselect_init(LassoSelectUserData *r_data,
244                                              ViewContext *vc, const rcti *rect, const int (*mcords)[2],
245                                              const int moves, const bool select)
246 {
247         r_data->vc = vc;
248
249         r_data->rect = rect;
250         r_data->rect_fl = &r_data->_rect_fl;
251         BLI_rctf_rcti_copy(&r_data->_rect_fl, rect);
252
253         r_data->mcords = mcords;
254         r_data->moves = moves;
255         r_data->select = select;
256
257         /* runtime */
258         r_data->pass = 0;
259         r_data->is_done = false;
260         r_data->is_changed = false;
261 }
262
263 static int view3d_selectable_data(bContext *C)
264 {
265         Object *ob = CTX_data_active_object(C);
266
267         if (!ED_operator_region_view3d_active(C))
268                 return 0;
269
270         if (ob) {
271                 if (ob->mode & OB_MODE_EDIT) {
272                         if (ob->type == OB_FONT) {
273                                 return 0;
274                         }
275                 }
276                 else {
277                         if ((ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)) &&
278                             !paint_facesel_test(ob) && !paint_vertsel_test(ob))
279                         {
280                                 return 0;
281                         }
282                 }
283         }
284
285         return 1;
286 }
287
288
289 /* helper also for borderselect */
290 static bool edge_fully_inside_rect(const rctf *rect, const float v1[2], const float v2[2])
291 {
292         return BLI_rctf_isect_pt_v(rect, v1) && BLI_rctf_isect_pt_v(rect, v2);
293 }
294
295 static bool edge_inside_rect(const rctf *rect, const float v1[2], const float v2[2])
296 {
297         int d1, d2, d3, d4;
298         
299         /* check points in rect */
300         if (edge_fully_inside_rect(rect, v1, v2)) return 1;
301         
302         /* check points completely out rect */
303         if (v1[0] < rect->xmin && v2[0] < rect->xmin) return 0;
304         if (v1[0] > rect->xmax && v2[0] > rect->xmax) return 0;
305         if (v1[1] < rect->ymin && v2[1] < rect->ymin) return 0;
306         if (v1[1] > rect->ymax && v2[1] > rect->ymax) return 0;
307         
308         /* simple check lines intersecting. */
309         d1 = (v1[1] - v2[1]) * (v1[0] - rect->xmin) + (v2[0] - v1[0]) * (v1[1] - rect->ymin);
310         d2 = (v1[1] - v2[1]) * (v1[0] - rect->xmin) + (v2[0] - v1[0]) * (v1[1] - rect->ymax);
311         d3 = (v1[1] - v2[1]) * (v1[0] - rect->xmax) + (v2[0] - v1[0]) * (v1[1] - rect->ymax);
312         d4 = (v1[1] - v2[1]) * (v1[0] - rect->xmax) + (v2[0] - v1[0]) * (v1[1] - rect->ymin);
313         
314         if (d1 < 0 && d2 < 0 && d3 < 0 && d4 < 0) return 0;
315         if (d1 > 0 && d2 > 0 && d3 > 0 && d4 > 0) return 0;
316         
317         return 1;
318 }
319
320 static void do_lasso_select_pose__doSelectBone(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
321 {
322         LassoSelectUserData *data = userData;
323         bArmature *arm = data->vc->obact->data;
324
325         if (PBONE_SELECTABLE(arm, pchan->bone)) {
326                 bool is_point_done = false;
327                 int points_proj_tot = 0;
328
329                 const int x0 = screen_co_a[0];
330                 const int y0 = screen_co_a[1];
331                 const int x1 = screen_co_b[0];
332                 const int y1 = screen_co_b[1];
333
334                 /* project head location to screenspace */
335                 if (x0 != IS_CLIPPED) {
336                         points_proj_tot++;
337                         if (BLI_rcti_isect_pt(data->rect, x0, y0) &&
338                             BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, INT_MAX))
339                         {
340                                 is_point_done = true;
341                         }
342                 }
343
344                 /* project tail location to screenspace */
345                 if (x1 != IS_CLIPPED) {
346                         points_proj_tot++;
347                         if (BLI_rcti_isect_pt(data->rect, x1, y1) &&
348                             BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, INT_MAX))
349                         {
350                                 is_point_done = true;
351                         }
352                 }
353
354                 /* if one of points selected, we skip the bone itself */
355                 if ((is_point_done == true) ||
356                     ((is_point_done == false) && (points_proj_tot == 2) &&
357                      BLI_lasso_is_edge_inside(data->mcords, data->moves, x0, y0, x1, y1, INT_MAX)))
358                 {
359                         if (data->select) pchan->bone->flag |=  BONE_SELECTED;
360                         else              pchan->bone->flag &= ~BONE_SELECTED;
361                         data->is_changed = true;
362                 }
363                 data->is_changed |= is_point_done;
364         }
365 }
366 static void do_lasso_select_pose(ViewContext *vc, Object *ob, const int mcords[][2], short moves, const bool select)
367 {
368         ViewContext vc_tmp;
369         LassoSelectUserData data;
370         rcti rect;
371         
372         if ((ob->type != OB_ARMATURE) || (ob->pose == NULL)) {
373                 return;
374         }
375
376         vc_tmp = *vc;
377         vc_tmp.obact = ob;
378
379         BLI_lasso_boundbox(&rect, mcords, moves);
380
381         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
382
383         ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d);
384
385         pose_foreachScreenBone(&vc_tmp, do_lasso_select_pose__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
386
387         if (data.is_changed) {
388                 bArmature *arm = ob->data;
389                 if (arm->flag & ARM_HAS_VIZ_DEPS) {
390                         /* mask modifier ('armature' mode), etc. */
391                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
392                 }
393         }
394 }
395
396 static void object_deselect_all_visible(Scene *scene, View3D *v3d)
397 {
398         Base *base;
399
400         for (base = scene->base.first; base; base = base->next) {
401                 if (BASE_SELECTABLE(v3d, base)) {
402                         ED_base_object_select(base, BA_DESELECT);
403                 }
404         }
405 }
406
407 static void do_lasso_select_objects(ViewContext *vc, const int mcords[][2], const short moves,
408                                     const bool extend, const bool select)
409 {
410         Base *base;
411         
412         if (extend == false && select)
413                 object_deselect_all_visible(vc->scene, vc->v3d);
414
415         for (base = vc->scene->base.first; base; base = base->next) {
416                 if (BASE_SELECTABLE(vc->v3d, base)) { /* use this to avoid un-needed lasso lookups */
417                         ED_view3d_project_base(vc->ar, base);
418                         if (BLI_lasso_is_point_inside(mcords, moves, base->sx, base->sy, IS_CLIPPED)) {
419                                 
420                                 ED_base_object_select(base, select ? BA_SELECT : BA_DESELECT);
421                                 base->object->flag = base->flag;
422                         }
423                         if (vc->obact == base->object && (base->object->mode & OB_MODE_POSE)) {
424                                 do_lasso_select_pose(vc, base->object, mcords, moves, select);
425                         }
426                 }
427         }
428 }
429
430 static void do_lasso_select_mesh__doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
431 {
432         LassoSelectUserData *data = userData;
433
434         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
435             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
436         {
437                 BM_vert_select_set(data->vc->em->bm, eve, data->select);
438         }
439 }
440 static void do_lasso_select_mesh__doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
441 {
442         LassoSelectUserData *data = userData;
443
444         if (EDBM_backbuf_check(bm_solidoffs + index)) {
445                 const int x0 = screen_co_a[0];
446                 const int y0 = screen_co_a[1];
447                 const int x1 = screen_co_b[0];
448                 const int y1 = screen_co_b[1];
449
450                 if (data->pass == 0) {
451                         if (edge_fully_inside_rect(data->rect_fl, screen_co_a, screen_co_b)  &&
452                             BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, IS_CLIPPED) &&
453                             BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, IS_CLIPPED))
454                         {
455                                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
456                                 data->is_done = true;
457                         }
458                 }
459                 else {
460                         if (BLI_lasso_is_edge_inside(data->mcords, data->moves, x0, y0, x1, y1, IS_CLIPPED)) {
461                                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
462                         }
463                 }
464         }
465 }
466 static void do_lasso_select_mesh__doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
467 {
468         LassoSelectUserData *data = userData;
469
470         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
471             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
472         {
473                 BM_face_select_set(data->vc->em->bm, efa, data->select);
474         }
475 }
476
477 static void do_lasso_select_mesh(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
478 {
479         LassoSelectUserData data;
480         ToolSettings *ts = vc->scene->toolsettings;
481         rcti rect;
482         int bbsel;
483         
484         /* set editmesh */
485         vc->em = BKE_editmesh_from_object(vc->obedit);
486
487         BLI_lasso_boundbox(&rect, mcords, moves);
488
489         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
490
491         if (extend == false && select)
492                 EDBM_flag_disable_all(vc->em, BM_ELEM_SELECT);
493
494         /* for non zbuf projections, don't change the GL state */
495         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
496
497         glLoadMatrixf(vc->rv3d->viewmat);
498         bbsel = EDBM_backbuf_border_mask_init(vc, mcords, moves, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
499         
500         if (ts->selectmode & SCE_SELECT_VERTEX) {
501                 if (bbsel) {
502                         edbm_backbuf_check_and_select_verts(vc->em, select);
503                 }
504                 else {
505                         mesh_foreachScreenVert(vc, do_lasso_select_mesh__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
506                 }
507         }
508         if (ts->selectmode & SCE_SELECT_EDGE) {
509                 /* Does both bbsel and non-bbsel versions (need screen cos for both) */
510                 data.pass = 0;
511                 mesh_foreachScreenEdge(vc, do_lasso_select_mesh__doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
512
513                 if (data.is_done == false) {
514                         data.pass = 1;
515                         mesh_foreachScreenEdge(vc, do_lasso_select_mesh__doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
516                 }
517         }
518         
519         if (ts->selectmode & SCE_SELECT_FACE) {
520                 if (bbsel) {
521                         edbm_backbuf_check_and_select_faces(vc->em, select);
522                 }
523                 else {
524                         mesh_foreachScreenFace(vc, do_lasso_select_mesh__doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
525                 }
526         }
527         
528         EDBM_backbuf_free();
529         EDBM_selectmode_flush(vc->em);
530 }
531
532 static void do_lasso_select_curve__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
533 {
534         LassoSelectUserData *data = userData;
535         Object *obedit = data->vc->obedit;
536         Curve *cu = (Curve *)obedit->data;
537
538         if (BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED)) {
539                 if (bp) {
540                         bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
541                 }
542                 else {
543                         if (cu->drawflag & CU_HIDE_HANDLES) {
544                                 /* can only be (beztindex == 0) here since handles are hidden */
545                                 bezt->f1 = bezt->f2 = bezt->f3 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
546                         }
547                         else {
548                                 if (beztindex == 0) {
549                                         bezt->f1 = data->select ? (bezt->f1 | SELECT) : (bezt->f1 & ~SELECT);
550                                 }
551                                 else if (beztindex == 1) {
552                                         bezt->f2 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
553                                 }
554                                 else {
555                                         bezt->f3 = data->select ? (bezt->f3 | SELECT) : (bezt->f3 & ~SELECT);
556                                 }
557                         }
558                 }
559         }
560 }
561
562 static void do_lasso_select_curve(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
563 {
564         LassoSelectUserData data;
565         rcti rect;
566
567         BLI_lasso_boundbox(&rect, mcords, moves);
568
569         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
570
571         if (extend == false && select)
572                 ED_curve_deselect_all(vc->obedit->data);
573
574         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
575         nurbs_foreachScreenVert(vc, do_lasso_select_curve__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
576         BKE_curve_nurb_vert_active_validate(vc->obedit->data);
577 }
578
579 static void do_lasso_select_lattice__doSelect(void *userData, BPoint *bp, const float screen_co[2])
580 {
581         LassoSelectUserData *data = userData;
582
583         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
584             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
585         {
586                 bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
587         }
588 }
589 static void do_lasso_select_lattice(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
590 {
591         LassoSelectUserData data;
592         rcti rect;
593
594         BLI_lasso_boundbox(&rect, mcords, moves);
595
596         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
597
598         if (extend == false && select)
599                 ED_setflagsLatt(vc->obedit, 0);
600
601         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
602         lattice_foreachScreenVert(vc, do_lasso_select_lattice__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
603 }
604
605 static void do_lasso_select_armature__doSelectBone(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
606 {
607         LassoSelectUserData *data = userData;
608         bArmature *arm = data->vc->obedit->data;
609
610         if (data->select ? EBONE_SELECTABLE(arm, ebone) : EBONE_VISIBLE(arm, ebone)) {
611                 bool is_point_done = false;
612                 int points_proj_tot = 0;
613
614                 const int x0 = screen_co_a[0];
615                 const int y0 = screen_co_a[1];
616                 const int x1 = screen_co_b[0];
617                 const int y1 = screen_co_b[1];
618
619                 /* project head location to screenspace */
620                 if (x0 != IS_CLIPPED) {
621                         points_proj_tot++;
622                         if (BLI_rcti_isect_pt(data->rect, x0, y0) &&
623                             BLI_lasso_is_point_inside(data->mcords, data->moves, x0, y0, INT_MAX))
624                         {
625                                 is_point_done = true;
626                                 if (data->select) ebone->flag |=  BONE_ROOTSEL;
627                                 else              ebone->flag &= ~BONE_ROOTSEL;
628                         }
629                 }
630
631                 /* project tail location to screenspace */
632                 if (x1 != IS_CLIPPED) {
633                         points_proj_tot++;
634                         if (BLI_rcti_isect_pt(data->rect, x1, y1) &&
635                             BLI_lasso_is_point_inside(data->mcords, data->moves, x1, y1, INT_MAX))
636                         {
637                                 is_point_done = true;
638                                 if (data->select) ebone->flag |=  BONE_TIPSEL;
639                                 else              ebone->flag &= ~BONE_TIPSEL;
640                         }
641                 }
642
643                 /* if one of points selected, we skip the bone itself */
644                 if ((is_point_done == false) && (points_proj_tot == 2) &&
645                     BLI_lasso_is_edge_inside(data->mcords, data->moves, x0, y0, x1, y1, INT_MAX))
646                 {
647                         if (data->select) ebone->flag |=  (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
648                         else              ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
649                         data->is_changed = true;
650                 }
651
652                 data->is_changed |= is_point_done;
653         }
654 }
655
656 static void do_lasso_select_armature(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
657 {
658         LassoSelectUserData data;
659         rcti rect;
660
661         BLI_lasso_boundbox(&rect, mcords, moves);
662
663         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
664
665         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
666
667         if (extend == false && select)
668                 ED_armature_deselect_all_visible(vc->obedit);
669
670         armature_foreachScreenBone(vc, do_lasso_select_armature__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
671
672         if (data.is_changed) {
673                 bArmature *arm = vc->obedit->data;
674                 ED_armature_sync_selection(arm->edbo);
675                 ED_armature_validate_active(arm);
676                 WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obedit);
677         }
678 }
679
680 static void do_lasso_select_mball__doSelectElem(void *userData, struct MetaElem *ml, const float screen_co[2])
681 {
682         LassoSelectUserData *data = userData;
683
684         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
685             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], INT_MAX))
686         {
687                 if (data->select) ml->flag |=  SELECT;
688                 else              ml->flag &= ~SELECT;
689                 data->is_changed = true;
690         }
691 }
692 static void do_lasso_select_meta(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
693 {
694         LassoSelectUserData data;
695         rcti rect;
696
697         MetaBall *mb = (MetaBall *)vc->obedit->data;
698
699         if (extend == false && select)
700                 BKE_mball_deselect_all(mb);
701
702         BLI_lasso_boundbox(&rect, mcords, moves);
703
704         view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
705
706         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
707
708         mball_foreachScreenElem(vc, do_lasso_select_mball__doSelectElem, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
709 }
710
711 static void do_lasso_select_meshobject__doSelectVert(void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
712 {
713         LassoSelectUserData *data = userData;
714
715         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
716             BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
717         {
718                 BKE_BIT_TEST_SET(mv->flag, data->select, SELECT);
719         }
720 }
721 static void do_lasso_select_paintvert(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
722 {
723         const int use_zbuf = (vc->v3d->flag & V3D_ZBUF_SELECT);
724         Object *ob = vc->obact;
725         Mesh *me = ob->data;
726         rcti rect;
727
728         if (me == NULL || me->totvert == 0)
729                 return;
730
731         if (extend == false && select)
732                 paintvert_deselect_all_visible(ob, SEL_DESELECT, false);  /* flush selection at the end */
733
734         BLI_lasso_boundbox(&rect, mcords, moves);
735
736         if (use_zbuf) {
737                 bm_vertoffs = me->totvert + 1; /* max index array */
738
739                 EDBM_backbuf_border_mask_init(vc, mcords, moves, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
740
741                 edbm_backbuf_check_and_select_verts_obmode(me, select);
742
743                 EDBM_backbuf_free();
744         }
745         else {
746                 LassoSelectUserData data;
747
748                 view3d_userdata_lassoselect_init(&data, vc, &rect, mcords, moves, select);
749
750                 ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d);
751
752                 meshobject_foreachScreenVert(vc, do_lasso_select_meshobject__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
753
754         }
755
756         if (select == false) {
757                 BKE_mesh_mselect_validate(me);
758         }
759         paintvert_flush_flags(ob);
760 }
761 static void do_lasso_select_paintface(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
762 {
763         Object *ob = vc->obact;
764         Mesh *me = ob->data;
765         rcti rect;
766
767         if (me == NULL || me->totpoly == 0)
768                 return;
769
770         if (extend == false && select)
771                 paintface_deselect_all_visible(ob, SEL_DESELECT, false);  /* flush selection at the end */
772
773         bm_vertoffs = me->totpoly + 1; /* max index array */
774
775         BLI_lasso_boundbox(&rect, mcords, moves);
776         EDBM_backbuf_border_mask_init(vc, mcords, moves, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
777         
778         edbm_backbuf_check_and_select_tfaces(me, select);
779
780         EDBM_backbuf_free();
781
782         paintface_flush_flags(ob);
783 }
784
785 #if 0
786 static void do_lasso_select_node(int mcords[][2], short moves, const bool select)
787 {
788         SpaceNode *snode = sa->spacedata.first;
789         
790         bNode *node;
791         rcti rect;
792         int node_cent[2];
793         float node_centf[2];
794         
795         BLI_lasso_boundbox(&rect, mcords, moves);
796         
797         /* store selection in temp test flag */
798         for (node = snode->edittree->nodes.first; node; node = node->next) {
799                 node_centf[0] = BLI_RCT_CENTER_X(&node->totr);
800                 node_centf[1] = BLI_RCT_CENTER_Y(&node->totr);
801                 
802                 ipoco_to_areaco_noclip(G.v2d, node_centf, node_cent);
803                 if (BLI_rcti_isect_pt_v(&rect, node_cent) && BLI_lasso_is_point_inside(mcords, moves, node_cent[0], node_cent[1])) {
804                         if (select) {
805                                 node->flag |= SELECT;
806                         }
807                         else {
808                                 node->flag &= ~SELECT;
809                         }
810                 }
811         }
812         BIF_undo_push("Lasso select nodes");
813 }
814 #endif
815
816 static void view3d_lasso_select(bContext *C, ViewContext *vc,
817                                 const int mcords[][2], short moves,
818                                 bool extend, bool select)
819 {
820         Object *ob = CTX_data_active_object(C);
821
822         if (vc->obedit == NULL) { /* Object Mode */
823                 if (paint_facesel_test(ob))
824                         do_lasso_select_paintface(vc, mcords, moves, extend, select);
825                 else if (paint_vertsel_test(ob))
826                         do_lasso_select_paintvert(vc, mcords, moves, extend, select);
827                 else if (ob && (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))) {
828                         /* pass */
829                 }
830                 else if (ob && (ob->mode & OB_MODE_PARTICLE_EDIT))
831                         PE_lasso_select(C, mcords, moves, extend, select);
832                 else {
833                         do_lasso_select_objects(vc, mcords, moves, extend, select);
834                         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc->scene);
835                 }
836         }
837         else { /* Edit Mode */
838                 switch (vc->obedit->type) {
839                         case OB_MESH:
840                                 do_lasso_select_mesh(vc, mcords, moves, extend, select);
841                                 break;
842                         case OB_CURVE:
843                         case OB_SURF:
844                                 do_lasso_select_curve(vc, mcords, moves, extend, select);
845                                 break;
846                         case OB_LATTICE:
847                                 do_lasso_select_lattice(vc, mcords, moves, extend, select);
848                                 break;
849                         case OB_ARMATURE:
850                                 do_lasso_select_armature(vc, mcords, moves, extend, select);
851                                 break;
852                         case OB_MBALL:
853                                 do_lasso_select_meta(vc, mcords, moves, extend, select);
854                                 break;
855                         default:
856                                 assert(!"lasso select on incorrect object type");
857                                 break;
858                 }
859
860                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc->obedit->data);
861         }
862 }
863
864
865 /* lasso operator gives properties, but since old code works
866  * with short array we convert */
867 static int view3d_lasso_select_exec(bContext *C, wmOperator *op)
868 {
869         ViewContext vc;
870         int mcords_tot;
871         const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
872         
873         if (mcords) {
874                 bool extend, select;
875                 view3d_operator_needs_opengl(C);
876                 
877                 /* setup view context for argument to callbacks */
878                 view3d_set_viewcontext(C, &vc);
879                 
880                 extend = RNA_boolean_get(op->ptr, "extend");
881                 select = !RNA_boolean_get(op->ptr, "deselect");
882                 view3d_lasso_select(C, &vc, mcords, mcords_tot, extend, select);
883                 
884                 MEM_freeN((void *)mcords);
885
886                 return OPERATOR_FINISHED;
887         }
888         return OPERATOR_PASS_THROUGH;
889 }
890
891 void VIEW3D_OT_select_lasso(wmOperatorType *ot)
892 {
893         ot->name = "Lasso Select";
894         ot->description = "Select items using lasso selection";
895         ot->idname = "VIEW3D_OT_select_lasso";
896         
897         ot->invoke = WM_gesture_lasso_invoke;
898         ot->modal = WM_gesture_lasso_modal;
899         ot->exec = view3d_lasso_select_exec;
900         ot->poll = view3d_selectable_data;
901         ot->cancel = WM_gesture_lasso_cancel;
902         
903         /* flags */
904         ot->flag = OPTYPE_UNDO;
905         
906         RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
907         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
908         RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
909 }
910
911
912 /* ************************************************* */
913
914 #if 0
915 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
916 static unsigned int samplerect(unsigned int *buf, int size, unsigned int dontdo)
917 {
918         Base *base;
919         unsigned int *bufmin, *bufmax;
920         int a, b, rc, tel, len, dirvec[4][2], maxob;
921         unsigned int retval = 0;
922         
923         base = LASTBASE;
924         if (base == 0) return 0;
925         maxob = base->selcol;
926
927         len = (size - 1) / 2;
928         rc = 0;
929
930         dirvec[0][0] = 1;
931         dirvec[0][1] = 0;
932         dirvec[1][0] = 0;
933         dirvec[1][1] = -size;
934         dirvec[2][0] = -1;
935         dirvec[2][1] = 0;
936         dirvec[3][0] = 0;
937         dirvec[3][1] = size;
938
939         bufmin = buf;
940         bufmax = buf + size * size;
941         buf += len * size + len;
942
943         for (tel = 1; tel <= size; tel++) {
944
945                 for (a = 0; a < 2; a++) {
946                         for (b = 0; b < tel; b++) {
947
948                                 if (*buf && *buf <= maxob && *buf != dontdo) return *buf;
949                                 if (*buf == dontdo) retval = dontdo;  /* if only color dontdo is available, still return dontdo */
950                                 
951                                 buf += (dirvec[rc][0] + dirvec[rc][1]);
952
953                                 if (buf < bufmin || buf >= bufmax) return retval;
954                         }
955                         rc++;
956                         rc &= 3;
957                 }
958         }
959         return retval;
960 }
961 #endif
962
963 /* ************************** mouse select ************************* */
964
965
966 /* The max number of menu items in an object select menu */
967 typedef struct SelMenuItemF {
968         char idname[MAX_ID_NAME - 2];
969         int icon;
970 } SelMenuItemF;
971
972 #define SEL_MENU_SIZE   22
973 static SelMenuItemF object_mouse_select_menu_data[SEL_MENU_SIZE];
974
975 /* special (crappy) operator only for menu select */
976 static EnumPropertyItem *object_select_menu_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
977 {
978         EnumPropertyItem *item = NULL, item_tmp = {0};
979         int totitem = 0;
980         int i = 0;
981
982         /* don't need context but avoid docgen using this */
983         if (C == NULL || object_mouse_select_menu_data[i].idname[0] == '\0') {
984                 return DummyRNA_NULL_items;
985         }
986
987         for (; i < SEL_MENU_SIZE && object_mouse_select_menu_data[i].idname[0] != '\0'; i++) {
988                 item_tmp.name = object_mouse_select_menu_data[i].idname;
989                 item_tmp.identifier = object_mouse_select_menu_data[i].idname;
990                 item_tmp.value = i;
991                 item_tmp.icon = object_mouse_select_menu_data[i].icon;
992                 RNA_enum_item_add(&item, &totitem, &item_tmp);
993         }
994
995         RNA_enum_item_end(&item, &totitem);
996         *r_free = true;
997
998         return item;
999 }
1000
1001 static int object_select_menu_exec(bContext *C, wmOperator *op)
1002 {
1003         const int name_index = RNA_enum_get(op->ptr, "name");
1004         const bool toggle = RNA_boolean_get(op->ptr, "toggle");
1005         bool changed = false;
1006         const char *name = object_mouse_select_menu_data[name_index].idname;
1007
1008         if (!toggle) {
1009                 CTX_DATA_BEGIN (C, Base *, base, selectable_bases)
1010                 {
1011                         if (base->flag & SELECT) {
1012                                 ED_base_object_select(base, BA_DESELECT);
1013                                 changed = true;
1014                         }
1015                 }
1016                 CTX_DATA_END;
1017         }
1018
1019         CTX_DATA_BEGIN (C, Base *, base, selectable_bases)
1020         {
1021                 /* this is a bit dodjy, there should only be ONE object with this name, but library objects can mess this up */
1022                 if (STREQ(name, base->object->id.name + 2)) {
1023                         ED_base_object_activate(C, base);
1024                         ED_base_object_select(base, BA_SELECT);
1025                         changed = true;
1026                 }
1027         }
1028         CTX_DATA_END;
1029
1030         /* weak but ensures we activate menu again before using the enum */
1031         memset(object_mouse_select_menu_data, 0, sizeof(object_mouse_select_menu_data));
1032
1033         /* undo? */
1034         if (changed) {
1035                 WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, CTX_data_scene(C));
1036                 return OPERATOR_FINISHED;
1037         }
1038         else {
1039                 return OPERATOR_CANCELLED;
1040         }
1041 }
1042
1043 void VIEW3D_OT_select_menu(wmOperatorType *ot)
1044 {
1045         PropertyRNA *prop;
1046
1047         /* identifiers */
1048         ot->name = "Select Menu";
1049         ot->description = "Menu object selection";
1050         ot->idname = "VIEW3D_OT_select_menu";
1051
1052         /* api callbacks */
1053         ot->invoke = WM_menu_invoke;
1054         ot->exec = object_select_menu_exec;
1055
1056         /* flags */
1057         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1058
1059         /* keyingset to use (dynamic enum) */
1060         prop = RNA_def_enum(ot->srna, "name", DummyRNA_NULL_items, 0, "Object Name", "");
1061         RNA_def_enum_funcs(prop, object_select_menu_enum_itemf);
1062         RNA_def_property_flag(prop, PROP_HIDDEN);
1063         ot->prop = prop;
1064
1065         RNA_def_boolean(ot->srna, "toggle", 0, "Toggle", "Toggle selection instead of deselecting everything first");
1066 }
1067
1068 static void deselectall_except(Scene *scene, Base *b)   /* deselect all except b */
1069 {
1070         Base *base;
1071         
1072         for (base = FIRSTBASE; base; base = base->next) {
1073                 if (base->flag & SELECT) {
1074                         if (b != base) {
1075                                 ED_base_object_select(base, BA_DESELECT);
1076                         }
1077                 }
1078         }
1079 }
1080
1081 static Base *object_mouse_select_menu(bContext *C, ViewContext *vc, unsigned int *buffer, int hits, const int mval[2], short toggle)
1082 {
1083         short baseCount = 0;
1084         bool ok;
1085         LinkNode *linklist = NULL;
1086         
1087         CTX_DATA_BEGIN (C, Base *, base, selectable_bases)
1088         {
1089                 ok = false;
1090
1091                 /* two selection methods, the CTRL select uses max dist of 15 */
1092                 if (buffer) {
1093                         int a;
1094                         for (a = 0; a < hits; a++) {
1095                                 /* index was converted */
1096                                 if (base->selcol == buffer[(4 * a) + 3])
1097                                         ok = true;
1098                         }
1099                 }
1100                 else {
1101                         int temp, dist = 15;
1102                         ED_view3d_project_base(vc->ar, base);
1103                         
1104                         temp = abs(base->sx - mval[0]) + abs(base->sy - mval[1]);
1105                         if (temp < dist)
1106                                 ok = true;
1107                 }
1108
1109                 if (ok) {
1110                         baseCount++;
1111                         BLI_linklist_prepend(&linklist, base);
1112
1113                         if (baseCount == SEL_MENU_SIZE)
1114                                 break;
1115                 }
1116         }
1117         CTX_DATA_END;
1118
1119         if (baseCount == 0) {
1120                 return NULL;
1121         }
1122         if (baseCount == 1) {
1123                 Base *base = (Base *)linklist->link;
1124                 BLI_linklist_free(linklist, NULL);
1125                 return base;
1126         }
1127         else {
1128                 /* UI, full in static array values that we later use in an enum function */
1129                 LinkNode *node;
1130                 int i;
1131
1132                 memset(object_mouse_select_menu_data, 0, sizeof(object_mouse_select_menu_data));
1133
1134                 for (node = linklist, i = 0; node; node = node->next, i++) {
1135                         Base *base = node->link;
1136                         Object *ob = base->object;
1137                         char *name = ob->id.name + 2;
1138
1139                         BLI_strncpy(object_mouse_select_menu_data[i].idname, name, MAX_ID_NAME - 2);
1140                         object_mouse_select_menu_data[i].icon = uiIconFromID(&ob->id);
1141                 }
1142
1143                 {
1144                         PointerRNA ptr;
1145
1146                         WM_operator_properties_create(&ptr, "VIEW3D_OT_select_menu");
1147                         RNA_boolean_set(&ptr, "toggle", toggle);
1148                         WM_operator_name_call(C, "VIEW3D_OT_select_menu", WM_OP_INVOKE_DEFAULT, &ptr);
1149                         WM_operator_properties_free(&ptr);
1150                 }
1151
1152                 BLI_linklist_free(linklist, NULL);
1153                 return NULL;
1154         }
1155 }
1156
1157 static bool selectbuffer_has_bones(const unsigned int *buffer, const unsigned int hits)
1158 {
1159         unsigned int i;
1160         for (i = 0; i < hits; i++) {
1161                 if (buffer[(4 * i) + 3] & 0xFFFF0000) {
1162                         return true;
1163                 }
1164         }
1165         return false;
1166 }
1167
1168 /* utility function for mixed_bones_object_selectbuffer */
1169 static short selectbuffer_ret_hits_15(unsigned int *UNUSED(buffer), const short hits15)
1170 {
1171         return hits15;
1172 }
1173
1174 static short selectbuffer_ret_hits_9(unsigned int *buffer, const short hits15, const short hits9)
1175 {
1176         const int offs = 4 * hits15;
1177         memcpy(buffer, buffer + offs, 4 * offs);
1178         return hits9;
1179 }
1180
1181 static short selectbuffer_ret_hits_5(unsigned int *buffer, const short hits15, const short hits9, const short hits5)
1182 {
1183         const int offs = 4 * hits15 + 4 * hits9;
1184         memcpy(buffer, buffer + offs, 4 * offs);
1185         return hits5;
1186 }
1187
1188 /* we want a select buffer with bones, if there are... */
1189 /* so check three selection levels and compare */
1190 static short mixed_bones_object_selectbuffer(ViewContext *vc, unsigned int *buffer, const int mval[2])
1191 {
1192         rcti rect;
1193         int offs;
1194         short hits15, hits9 = 0, hits5 = 0;
1195         bool has_bones15 = false, has_bones9 = false, has_bones5 = false;
1196         
1197         BLI_rcti_init(&rect, mval[0] - 14, mval[0] + 14, mval[1] - 14, mval[1] + 14);
1198         hits15 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect);
1199         if (hits15 == 1) {
1200                 return selectbuffer_ret_hits_15(buffer, hits15);
1201         }
1202         else if (hits15 > 0) {
1203                 has_bones15 = selectbuffer_has_bones(buffer, hits15);
1204
1205                 offs = 4 * hits15;
1206                 BLI_rcti_init(&rect, mval[0] - 9, mval[0] + 9, mval[1] - 9, mval[1] + 9);
1207                 hits9 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect);
1208                 if (hits9 == 1) {
1209                         return selectbuffer_ret_hits_9(buffer, hits15, hits9);
1210                 }
1211                 else if (hits9 > 0) {
1212                         has_bones9 = selectbuffer_has_bones(buffer + offs, hits9);
1213
1214                         offs += 4 * hits9;
1215                         BLI_rcti_init(&rect, mval[0] - 5, mval[0] + 5, mval[1] - 5, mval[1] + 5);
1216                         hits5 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect);
1217                         if (hits5 == 1) {
1218                                 return selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5);
1219                         }
1220                         else if (hits5 > 0) {
1221                                 has_bones5 = selectbuffer_has_bones(buffer + offs, hits5);
1222                         }
1223                 }
1224
1225                 if      (has_bones5)  return selectbuffer_ret_hits_5(buffer,  hits15, hits9, hits5);
1226                 else if (has_bones9)  return selectbuffer_ret_hits_9(buffer,  hits15, hits9);
1227                 else if (has_bones15) return selectbuffer_ret_hits_15(buffer, hits15);
1228                 
1229                 if      (hits5 > 0) return selectbuffer_ret_hits_5(buffer,  hits15, hits9, hits5);
1230                 else if (hits9 > 0) return selectbuffer_ret_hits_9(buffer,  hits15, hits9);
1231                 else                return selectbuffer_ret_hits_15(buffer, hits15);
1232         }
1233         
1234         return 0;
1235 }
1236
1237 /* returns basact */
1238 static Base *mouse_select_eval_buffer(ViewContext *vc, unsigned int *buffer, int hits, const int mval[2],
1239                                       Base *startbase, bool has_bones)
1240 {
1241         Scene *scene = vc->scene;
1242         View3D *v3d = vc->v3d;
1243         Base *base, *basact = NULL;
1244         static int lastmval[2] = {-100, -100};
1245         int a;
1246         bool do_nearest = false;
1247         
1248         /* define if we use solid nearest select or not */
1249         if (v3d->drawtype > OB_WIRE) {
1250                 do_nearest = true;
1251                 if (ABS(mval[0] - lastmval[0]) < 3 && ABS(mval[1] - lastmval[1]) < 3) {
1252                         if (!has_bones) /* hrms, if theres bones we always do nearest */
1253                                 do_nearest = false;
1254                 }
1255         }
1256         lastmval[0] = mval[0]; lastmval[1] = mval[1];
1257         
1258         if (do_nearest) {
1259                 unsigned int min = 0xFFFFFFFF;
1260                 int selcol = 0, notcol = 0;
1261                 
1262                 
1263                 if (has_bones) {
1264                         /* we skip non-bone hits */
1265                         for (a = 0; a < hits; a++) {
1266                                 if (min > buffer[4 * a + 1] && (buffer[4 * a + 3] & 0xFFFF0000) ) {
1267                                         min = buffer[4 * a + 1];
1268                                         selcol = buffer[4 * a + 3] & 0xFFFF;
1269                                 }
1270                         }
1271                 }
1272                 else {
1273                         /* only exclude active object when it is selected... */
1274                         if (BASACT && (BASACT->flag & SELECT) && hits > 1) notcol = BASACT->selcol;
1275                         
1276                         for (a = 0; a < hits; a++) {
1277                                 if (min > buffer[4 * a + 1] && notcol != (buffer[4 * a + 3] & 0xFFFF)) {
1278                                         min = buffer[4 * a + 1];
1279                                         selcol = buffer[4 * a + 3] & 0xFFFF;
1280                                 }
1281                         }
1282                 }
1283                 
1284                 base = FIRSTBASE;
1285                 while (base) {
1286                         if (BASE_SELECTABLE(v3d, base)) {
1287                                 if (base->selcol == selcol) break;
1288                         }
1289                         base = base->next;
1290                 }
1291                 if (base) basact = base;
1292         }
1293         else {
1294                 
1295                 base = startbase;
1296                 while (base) {
1297                         /* skip objects with select restriction, to prevent prematurely ending this loop
1298                          * with an un-selectable choice */
1299                         if (base->object->restrictflag & OB_RESTRICT_SELECT) {
1300                                 base = base->next;
1301                                 if (base == NULL) base = FIRSTBASE;
1302                                 if (base == startbase) break;
1303                         }
1304                         
1305                         if (BASE_SELECTABLE(v3d, base)) {
1306                                 for (a = 0; a < hits; a++) {
1307                                         if (has_bones) {
1308                                                 /* skip non-bone objects */
1309                                                 if ((buffer[4 * a + 3] & 0xFFFF0000)) {
1310                                                         if (base->selcol == (buffer[(4 * a) + 3] & 0xFFFF))
1311                                                                 basact = base;
1312                                                 }
1313                                         }
1314                                         else {
1315                                                 if (base->selcol == (buffer[(4 * a) + 3] & 0xFFFF))
1316                                                         basact = base;
1317                                         }
1318                                 }
1319                         }
1320                         
1321                         if (basact) break;
1322                         
1323                         base = base->next;
1324                         if (base == NULL) base = FIRSTBASE;
1325                         if (base == startbase) break;
1326                 }
1327         }
1328         
1329         return basact;
1330 }
1331
1332 /* mval comes from event->mval, only use within region handlers */
1333 Base *ED_view3d_give_base_under_cursor(bContext *C, const int mval[2])
1334 {
1335         ViewContext vc;
1336         Base *basact = NULL;
1337         unsigned int buffer[4 * MAXPICKBUF];
1338         int hits;
1339         
1340         /* setup view context for argument to callbacks */
1341         view3d_operator_needs_opengl(C);
1342         view3d_set_viewcontext(C, &vc);
1343         
1344         hits = mixed_bones_object_selectbuffer(&vc, buffer, mval);
1345         
1346         if (hits > 0) {
1347                 const bool has_bones = selectbuffer_has_bones(buffer, hits);
1348                 basact = mouse_select_eval_buffer(&vc, buffer, hits, mval, vc.scene->base.first, has_bones);
1349         }
1350         
1351         return basact;
1352 }
1353
1354 static void deselect_all_tracks(MovieTracking *tracking)
1355 {
1356         MovieTrackingObject *object;
1357
1358         object = tracking->objects.first;
1359         while (object) {
1360                 ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, object);
1361                 MovieTrackingTrack *track = tracksbase->first;
1362
1363                 while (track) {
1364                         BKE_tracking_track_deselect(track, TRACK_AREA_ALL);
1365
1366                         track = track->next;
1367                 }
1368
1369                 object = object->next;
1370         }
1371 }
1372
1373 /* mval is region coords */
1374 static bool mouse_select(bContext *C, const int mval[2],
1375                          bool extend, bool deselect, bool toggle, bool obcenter, bool enumerate, bool object)
1376 {
1377         ViewContext vc;
1378         ARegion *ar = CTX_wm_region(C);
1379         View3D *v3d = CTX_wm_view3d(C);
1380         Scene *scene = CTX_data_scene(C);
1381         Base *base, *startbase = NULL, *basact = NULL, *oldbasact = NULL;
1382         bool is_obedit;
1383         float dist = 100.0f;
1384         int retval = false;
1385         short hits;
1386         const float mval_fl[2] = {(float)mval[0], (float)mval[1]};
1387
1388         
1389         /* setup view context for argument to callbacks */
1390         view3d_set_viewcontext(C, &vc);
1391
1392         is_obedit = (vc.obedit != NULL);
1393         if (object) {
1394                 /* signal for view3d_opengl_select to skip editmode objects */
1395                 vc.obedit = NULL;
1396         }
1397         
1398         /* always start list from basact in wire mode */
1399         startbase =  FIRSTBASE;
1400         if (BASACT && BASACT->next) startbase = BASACT->next;
1401         
1402         /* This block uses the control key to make the object selected by its center point rather than its contents */
1403         /* in editmode do not activate */
1404         if (obcenter) {
1405                 
1406                 /* note; shift+alt goes to group-flush-selecting */
1407                 if (enumerate) {
1408                         basact = object_mouse_select_menu(C, &vc, NULL, 0, mval, toggle);
1409                 }
1410                 else {
1411                         base = startbase;
1412                         while (base) {
1413                                 if (BASE_SELECTABLE(v3d, base)) {
1414                                         float screen_co[2];
1415                                         if (ED_view3d_project_float_global(ar, base->object->obmat[3], screen_co,
1416                                                                            V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
1417                                         {
1418                                                 float dist_temp = len_manhattan_v2v2(mval_fl, screen_co);
1419                                                 if (base == BASACT) dist_temp += 10.0f;
1420                                                 if (dist_temp < dist) {
1421                                                         dist = dist_temp;
1422                                                         basact = base;
1423                                                 }
1424                                         }
1425                                 }
1426                                 base = base->next;
1427                                 
1428                                 if (base == NULL) base = FIRSTBASE;
1429                                 if (base == startbase) break;
1430                         }
1431                 }
1432         }
1433         else {
1434                 unsigned int buffer[4 * MAXPICKBUF];
1435
1436                 /* if objects have posemode set, the bones are in the same selection buffer */
1437                 
1438                 hits = mixed_bones_object_selectbuffer(&vc, buffer, mval);
1439                 
1440                 if (hits > 0) {
1441                         /* note: bundles are handling in the same way as bones */
1442                         const bool has_bones = selectbuffer_has_bones(buffer, hits);
1443
1444                         /* note; shift+alt goes to group-flush-selecting */
1445                         if (has_bones == 0 && enumerate) {
1446                                 basact = object_mouse_select_menu(C, &vc, buffer, hits, mval, toggle);
1447                         }
1448                         else {
1449                                 basact = mouse_select_eval_buffer(&vc, buffer, hits, mval, startbase, has_bones);
1450                         }
1451                         
1452                         if (has_bones && basact) {
1453                                 if (basact->object->type == OB_CAMERA) {
1454                                         if (BASACT == basact) {
1455                                                 int i, hitresult;
1456                                                 bool changed = false;
1457
1458                                                 for (i = 0; i < hits; i++) {
1459                                                         hitresult = buffer[3 + (i * 4)];
1460
1461                                                         /* if there's bundles in buffer select bundles first,
1462                                                          * so non-camera elements should be ignored in buffer */
1463                                                         if (basact->selcol != (hitresult & 0xFFFF)) {
1464                                                                 continue;
1465                                                         }
1466
1467                                                         /* index of bundle is 1<<16-based. if there's no "bone" index
1468                                                          * in height word, this buffer value belongs to camera. not to bundle */
1469                                                         if (buffer[4 * i + 3] & 0xFFFF0000) {
1470                                                                 MovieClip *clip = BKE_object_movieclip_get(scene, basact->object, false);
1471                                                                 MovieTracking *tracking = &clip->tracking;
1472                                                                 ListBase *tracksbase;
1473                                                                 MovieTrackingTrack *track;
1474
1475                                                                 track = BKE_tracking_track_get_indexed(&clip->tracking, hitresult >> 16, &tracksbase);
1476
1477                                                                 if (TRACK_SELECTED(track) && extend) {
1478                                                                         changed = false;
1479                                                                         BKE_tracking_track_deselect(track, TRACK_AREA_ALL);
1480                                                                 }
1481                                                                 else {
1482                                                                         int oldsel = TRACK_SELECTED(track) ? 1 : 0;
1483                                                                         if (!extend)
1484                                                                                 deselect_all_tracks(tracking);
1485
1486                                                                         BKE_tracking_track_select(tracksbase, track, TRACK_AREA_ALL, extend);
1487
1488                                                                         if (oldsel != (TRACK_SELECTED(track) ? 1 : 0))
1489                                                                                 changed = true;
1490                                                                 }
1491
1492                                                                 basact->flag |= SELECT;
1493                                                                 basact->object->flag = basact->flag;
1494
1495                                                                 retval = true;
1496
1497                                                                 WM_event_add_notifier(C, NC_MOVIECLIP | ND_SELECT, track);
1498                                                                 WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
1499
1500                                                                 break;
1501                                                         }
1502                                                 }
1503
1504                                                 if (!changed) {
1505                                                         /* fallback to regular object selection if no new bundles were selected,
1506                                                          * allows to select object parented to reconstruction object */
1507                                                         basact = mouse_select_eval_buffer(&vc, buffer, hits, mval, startbase, 0);
1508                                                 }
1509                                         }
1510                                 }
1511                                 else if (ED_do_pose_selectbuffer(scene, basact, buffer, hits, extend, deselect, toggle) ) {
1512                                         /* then bone is found */
1513                                 
1514                                         /* we make the armature selected: 
1515                                          * not-selected active object in posemode won't work well for tools */
1516                                         basact->flag |= SELECT;
1517                                         basact->object->flag = basact->flag;
1518                                         
1519                                         retval = true;
1520                                         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, basact->object);
1521                                         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_ACTIVE, basact->object);
1522                                         
1523                                         /* in weightpaint, we use selected bone to select vertexgroup, so no switch to new active object */
1524                                         if (BASACT && (BASACT->object->mode & OB_MODE_WEIGHT_PAINT)) {
1525                                                 /* prevent activating */
1526                                                 basact = NULL;
1527                                         }
1528
1529                                 }
1530                                 /* prevent bone selecting to pass on to object selecting */
1531                                 if (basact == BASACT)
1532                                         basact = NULL;
1533                         }
1534                 }
1535         }
1536         
1537         /* so, do we have something selected? */
1538         if (basact) {
1539                 retval = true;
1540                 
1541                 if (vc.obedit) {
1542                         /* only do select */
1543                         deselectall_except(scene, basact);
1544                         ED_base_object_select(basact, BA_SELECT);
1545                 }
1546                 /* also prevent making it active on mouse selection */
1547                 else if (BASE_SELECTABLE(v3d, basact)) {
1548
1549                         oldbasact = BASACT;
1550                         
1551                         if (extend) {
1552                                 ED_base_object_select(basact, BA_SELECT);
1553                         }
1554                         else if (deselect) {
1555                                 ED_base_object_select(basact, BA_DESELECT);
1556                         }
1557                         else if (toggle) {
1558                                 if (basact->flag & SELECT) {
1559                                         if (basact == oldbasact) {
1560                                                 ED_base_object_select(basact, BA_DESELECT);
1561                                         }
1562                                 }
1563                                 else {
1564                                         ED_base_object_select(basact, BA_SELECT);
1565                                 }
1566                         }
1567                         else {
1568                                 deselectall_except(scene, basact);
1569                                 ED_base_object_select(basact, BA_SELECT);
1570                         }
1571
1572                         if ((oldbasact != basact) && (is_obedit == false)) {
1573                                 ED_base_object_activate(C, basact); /* adds notifier */
1574                         }
1575                 }
1576
1577                 WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
1578         }
1579
1580         return retval;
1581 }
1582
1583 /* ********************  border and circle ************************************** */
1584
1585 typedef struct BoxSelectUserData {
1586         ViewContext *vc;
1587         const rcti *rect;
1588         const rctf *rect_fl;
1589         rctf       _rect_fl;
1590         bool select;
1591
1592         /* runtime */
1593         int pass;
1594         bool is_done;
1595         bool is_changed;
1596 } BoxSelectUserData;
1597
1598 static void view3d_userdata_boxselect_init(BoxSelectUserData *r_data,
1599                                            ViewContext *vc, const rcti *rect, const bool select)
1600 {
1601         r_data->vc = vc;
1602
1603         r_data->rect = rect;
1604         r_data->rect_fl = &r_data->_rect_fl;
1605         BLI_rctf_rcti_copy(&r_data->_rect_fl, rect);
1606
1607         r_data->select = select;
1608
1609         /* runtime */
1610         r_data->pass = 0;
1611         r_data->is_done = false;
1612         r_data->is_changed = false;
1613 }
1614
1615 bool edge_inside_circle(const float cent[2], float radius, const float screen_co_a[2], const float screen_co_b[2])
1616 {
1617         const float radius_squared = radius * radius;
1618         return (dist_squared_to_line_segment_v2(cent, screen_co_a, screen_co_b) < radius_squared);
1619 }
1620
1621 static void do_paintvert_box_select__doSelectVert(void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
1622 {
1623         BoxSelectUserData *data = userData;
1624
1625         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1626                 BKE_BIT_TEST_SET(mv->flag, data->select, SELECT);
1627         }
1628 }
1629 static int do_paintvert_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1630 {
1631         const int use_zbuf = (vc->v3d->flag & V3D_ZBUF_SELECT);
1632         Mesh *me;
1633         MVert *mvert;
1634         struct ImBuf *ibuf;
1635         unsigned int *rt;
1636         int a, index;
1637         char *selar;
1638         int sx = BLI_rcti_size_x(rect) + 1;
1639         int sy = BLI_rcti_size_y(rect) + 1;
1640
1641         me = vc->obact->data;
1642
1643         if (me == NULL || me->totvert == 0 || sx * sy <= 0)
1644                 return OPERATOR_CANCELLED;
1645
1646
1647         if (extend == false && select)
1648                 paintvert_deselect_all_visible(vc->obact, SEL_DESELECT, false);
1649
1650         if (use_zbuf) {
1651                 selar = MEM_callocN(me->totvert + 1, "selar");
1652                 view3d_validate_backbuf(vc);
1653
1654                 ibuf = IMB_allocImBuf(sx, sy, 32, IB_rect);
1655                 rt = ibuf->rect;
1656                 glReadPixels(rect->xmin + vc->ar->winrct.xmin,  rect->ymin + vc->ar->winrct.ymin, sx, sy, GL_RGBA, GL_UNSIGNED_BYTE,  ibuf->rect);
1657                 if (ENDIAN_ORDER == B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1658
1659                 a = sx * sy;
1660                 while (a--) {
1661                         if (*rt) {
1662                                 index = WM_framebuffer_to_index(*rt);
1663                                 if (index <= me->totvert) selar[index] = 1;
1664                         }
1665                         rt++;
1666                 }
1667
1668                 mvert = me->mvert;
1669                 for (a = 1; a <= me->totvert; a++, mvert++) {
1670                         if (selar[a]) {
1671                                 if ((mvert->flag & ME_HIDE) == 0) {
1672                                         if (select) mvert->flag |=  SELECT;
1673                                         else        mvert->flag &= ~SELECT;
1674                                 }
1675                         }
1676                 }
1677
1678                 IMB_freeImBuf(ibuf);
1679                 MEM_freeN(selar);
1680
1681 #ifdef __APPLE__
1682                 glReadBuffer(GL_BACK);
1683 #endif
1684         }
1685         else {
1686                 BoxSelectUserData data;
1687
1688                 view3d_userdata_boxselect_init(&data, vc, rect, select);
1689
1690                 ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d);
1691
1692                 meshobject_foreachScreenVert(vc, do_paintvert_box_select__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1693         }
1694
1695         if (select == false) {
1696                 BKE_mesh_mselect_validate(me);
1697         }
1698         paintvert_flush_flags(vc->obact);
1699
1700         return OPERATOR_FINISHED;
1701 }
1702
1703 static void do_nurbs_box_select__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
1704 {
1705         BoxSelectUserData *data = userData;
1706         Object *obedit = data->vc->obedit;
1707         Curve *cu = (Curve *)obedit->data;
1708
1709         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1710                 if (bp) {
1711                         bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
1712                 }
1713                 else {
1714                         if (cu->drawflag & CU_HIDE_HANDLES) {
1715                                 /* can only be (beztindex == 0) here since handles are hidden */
1716                                 bezt->f1 = bezt->f2 = bezt->f3 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
1717                         }
1718                         else {
1719                                 if (beztindex == 0) {
1720                                         bezt->f1 = data->select ? (bezt->f1 | SELECT) : (bezt->f1 & ~SELECT);
1721                                 }
1722                                 else if (beztindex == 1) {
1723                                         bezt->f2 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
1724                                 }
1725                                 else {
1726                                         bezt->f3 = data->select ? (bezt->f3 | SELECT) : (bezt->f3 & ~SELECT);
1727                                 }
1728                         }
1729                 }
1730         }
1731 }
1732 static int do_nurbs_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1733 {
1734         BoxSelectUserData data;
1735         
1736         view3d_userdata_boxselect_init(&data, vc, rect, select);
1737
1738         if (extend == false && select)
1739                 ED_curve_deselect_all(vc->obedit->data);
1740
1741         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
1742         nurbs_foreachScreenVert(vc, do_nurbs_box_select__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1743         BKE_curve_nurb_vert_active_validate(vc->obedit->data);
1744
1745         return OPERATOR_FINISHED;
1746 }
1747
1748 static void do_lattice_box_select__doSelect(void *userData, BPoint *bp, const float screen_co[2])
1749 {
1750         BoxSelectUserData *data = userData;
1751
1752         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1753                 bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
1754         }
1755 }
1756 static int do_lattice_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1757 {
1758         BoxSelectUserData data;
1759
1760         view3d_userdata_boxselect_init(&data, vc, rect, select);
1761
1762         if (extend == false && select)
1763                 ED_setflagsLatt(vc->obedit, 0);
1764
1765         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
1766         lattice_foreachScreenVert(vc, do_lattice_box_select__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1767         
1768         return OPERATOR_FINISHED;
1769 }
1770
1771 static void do_mesh_box_select__doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
1772 {
1773         BoxSelectUserData *data = userData;
1774
1775         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1776                 BM_vert_select_set(data->vc->em->bm, eve, data->select);
1777         }
1778 }
1779 static void do_mesh_box_select__doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
1780 {
1781         BoxSelectUserData *data = userData;
1782
1783         if (EDBM_backbuf_check(bm_solidoffs + index)) {
1784                 if (data->pass == 0) {
1785                         if (edge_fully_inside_rect(data->rect_fl, screen_co_a, screen_co_b)) {
1786                                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
1787                                 data->is_done = true;
1788                         }
1789                 }
1790                 else {
1791                         if (edge_inside_rect(data->rect_fl, screen_co_a, screen_co_b)) {
1792                                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
1793                         }
1794                 }
1795         }
1796 }
1797 static void do_mesh_box_select__doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
1798 {
1799         BoxSelectUserData *data = userData;
1800
1801         if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
1802                 BM_face_select_set(data->vc->em->bm, efa, data->select);
1803         }
1804 }
1805 static int do_mesh_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1806 {
1807         BoxSelectUserData data;
1808         ToolSettings *ts = vc->scene->toolsettings;
1809         int bbsel;
1810         
1811         view3d_userdata_boxselect_init(&data, vc, rect, select);
1812
1813         if (extend == false && select)
1814                 EDBM_flag_disable_all(vc->em, BM_ELEM_SELECT);
1815
1816         /* for non zbuf projections, don't change the GL state */
1817         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
1818
1819         glLoadMatrixf(vc->rv3d->viewmat);
1820         bbsel = EDBM_backbuf_border_init(vc, rect->xmin, rect->ymin, rect->xmax, rect->ymax);
1821
1822         if (ts->selectmode & SCE_SELECT_VERTEX) {
1823                 if (bbsel) {
1824                         edbm_backbuf_check_and_select_verts(vc->em, select);
1825                 }
1826                 else {
1827                         mesh_foreachScreenVert(vc, do_mesh_box_select__doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1828                 }
1829         }
1830         if (ts->selectmode & SCE_SELECT_EDGE) {
1831                 /* Does both bbsel and non-bbsel versions (need screen cos for both) */
1832
1833                 data.pass = 0;
1834                 mesh_foreachScreenEdge(vc, do_mesh_box_select__doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
1835
1836                 if (data.is_done == 0) {
1837                         data.pass = 1;
1838                         mesh_foreachScreenEdge(vc, do_mesh_box_select__doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
1839                 }
1840         }
1841         
1842         if (ts->selectmode & SCE_SELECT_FACE) {
1843                 if (bbsel) {
1844                         edbm_backbuf_check_and_select_faces(vc->em, select);
1845                 }
1846                 else {
1847                         mesh_foreachScreenFace(vc, do_mesh_box_select__doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
1848                 }
1849         }
1850         
1851         EDBM_backbuf_free();
1852                 
1853         EDBM_selectmode_flush(vc->em);
1854         
1855         return OPERATOR_FINISHED;
1856 }
1857
1858 static int do_meta_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1859 {
1860         MetaBall *mb = (MetaBall *)vc->obedit->data;
1861         MetaElem *ml;
1862         int a;
1863
1864         unsigned int buffer[4 * MAXPICKBUF];
1865         short hits;
1866
1867         hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect);
1868
1869         if (extend == false && select)
1870                 BKE_mball_deselect_all(mb);
1871         
1872         for (ml = mb->editelems->first; ml; ml = ml->next) {
1873                 for (a = 0; a < hits; a++) {
1874                         if (ml->selcol1 == buffer[(4 * a) + 3]) {
1875                                 ml->flag |= MB_SCALE_RAD;
1876                                 if (select) ml->flag |= SELECT;
1877                                 else ml->flag &= ~SELECT;
1878                                 break;
1879                         }
1880                         if (ml->selcol2 == buffer[(4 * a) + 3]) {
1881                                 ml->flag &= ~MB_SCALE_RAD;
1882                                 if (select) ml->flag |= SELECT;
1883                                 else ml->flag &= ~SELECT;
1884                                 break;
1885                         }
1886                 }
1887         }
1888
1889         return OPERATOR_FINISHED;
1890 }
1891
1892 static int do_armature_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
1893 {
1894         bArmature *arm = vc->obedit->data;
1895         EditBone *ebone;
1896         int a;
1897
1898         unsigned int buffer[4 * MAXPICKBUF];
1899         short hits;
1900
1901         hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect);
1902         
1903         /* clear flag we use to detect point was affected */
1904         for (ebone = arm->edbo->first; ebone; ebone = ebone->next)
1905                 ebone->flag &= ~BONE_DONE;
1906         
1907         if (extend == false && select)
1908                 ED_armature_deselect_all_visible(vc->obedit);
1909
1910         /* first we only check points inside the border */
1911         for (a = 0; a < hits; a++) {
1912                 int index = buffer[(4 * a) + 3];
1913                 if (index != -1) {
1914                         ebone = BLI_findlink(arm->edbo, index & ~(BONESEL_ANY));
1915                         if ((select == false) || ((ebone->flag & BONE_UNSELECTABLE) == 0)) {
1916                                 if (index & BONESEL_TIP) {
1917                                         ebone->flag |= BONE_DONE;
1918                                         if (select) ebone->flag |= BONE_TIPSEL;
1919                                         else ebone->flag &= ~BONE_TIPSEL;
1920                                 }
1921                                 
1922                                 if (index & BONESEL_ROOT) {
1923                                         ebone->flag |= BONE_DONE;
1924                                         if (select) ebone->flag |= BONE_ROOTSEL;
1925                                         else ebone->flag &= ~BONE_ROOTSEL;
1926                                 }
1927                         }
1928                 }
1929         }
1930         
1931         /* now we have to flush tag from parents... */
1932         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1933                 if (ebone->parent && (ebone->flag & BONE_CONNECTED)) {
1934                         if (ebone->parent->flag & BONE_DONE)
1935                                 ebone->flag |= BONE_DONE;
1936                 }
1937         }
1938         
1939         /* only select/deselect entire bones when no points where in the rect */
1940         for (a = 0; a < hits; a++) {
1941                 int index = buffer[(4 * a) + 3];
1942                 if (index != -1) {
1943                         ebone = BLI_findlink(arm->edbo, index & ~(BONESEL_ANY));
1944                         if (index & BONESEL_BONE) {
1945                                 if ((select == false) || ((ebone->flag & BONE_UNSELECTABLE) == 0)) {
1946                                         if (!(ebone->flag & BONE_DONE)) {
1947                                                 if (select)
1948                                                         ebone->flag |= (BONE_ROOTSEL | BONE_TIPSEL | BONE_SELECTED);
1949                                                 else
1950                                                         ebone->flag &= ~(BONE_ROOTSEL | BONE_TIPSEL | BONE_SELECTED);
1951                                         }
1952                                 }
1953                         }
1954                 }
1955         }
1956         
1957         ED_armature_sync_selection(arm->edbo);
1958         
1959         return OPERATOR_CANCELLED;
1960 }
1961
1962 static int do_object_pose_box_select(bContext *C, ViewContext *vc, rcti *rect, bool select, bool extend)
1963 {
1964         Bone *bone;
1965         Object *ob = vc->obact;
1966         unsigned int *vbuffer = NULL; /* selection buffer       */
1967         unsigned int *col;          /* color in buffer  */
1968         int bone_only;
1969         int bone_selected = 0;
1970         int totobj = MAXPICKBUF; /* XXX solve later */
1971         short hits;
1972         
1973         if ((ob) && (ob->mode & OB_MODE_POSE))
1974                 bone_only = 1;
1975         else
1976                 bone_only = 0;
1977         
1978         if (extend == false && select) {
1979                 if (bone_only) {
1980                         CTX_DATA_BEGIN (C, bPoseChannel *, pchan, visible_pose_bones)
1981                         {
1982                                 if ((select == false) || ((pchan->bone->flag & BONE_UNSELECTABLE) == 0)) {
1983                                         pchan->bone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1984                                 }
1985                         }
1986                         CTX_DATA_END;
1987                 }
1988                 else {
1989                         object_deselect_all_visible(vc->scene, vc->v3d);
1990                 }
1991         }
1992
1993         /* selection buffer now has bones potentially too, so we add MAXPICKBUF */
1994         vbuffer = MEM_mallocN(4 * (totobj + MAXPICKBUF) * sizeof(unsigned int), "selection buffer");
1995         hits = view3d_opengl_select(vc, vbuffer, 4 * (totobj + MAXPICKBUF), rect);
1996         /*
1997          * LOGIC NOTES (theeth):
1998          * The buffer and ListBase have the same relative order, which makes the selection
1999          * very simple. Loop through both data sets at the same time, if the color
2000          * is the same as the object, we have a hit and can move to the next color
2001          * and object pair, if not, just move to the next object,
2002          * keeping the same color until we have a hit.
2003          * 
2004          * The buffer order is defined by OGL standard, hopefully no stupid GFX card
2005          * does it incorrectly.
2006          */
2007
2008         if (hits > 0) { /* no need to loop if there's no hit */
2009                 Base *base;
2010                 col = vbuffer + 3;
2011                 
2012                 for (base = vc->scene->base.first; base && hits; base = base->next) {
2013                         if (BASE_SELECTABLE(vc->v3d, base)) {
2014                                 while (base->selcol == (*col & 0xFFFF)) {   /* we got an object */
2015                                         if (*col & 0xFFFF0000) {                    /* we got a bone */
2016                                                 bone = get_indexed_bone(base->object, *col & ~(BONESEL_ANY));
2017                                                 if (bone) {
2018                                                         if (select) {
2019                                                                 if ((bone->flag & BONE_UNSELECTABLE) == 0) {
2020                                                                         bone->flag |= BONE_SELECTED;
2021                                                                         bone_selected = 1;
2022                                                                 }
2023                                                         }
2024                                                         else {
2025                                                                 bArmature *arm = base->object->data;
2026                                                                 bone->flag &= ~BONE_SELECTED;
2027                                                                 if (arm->act_bone == bone)
2028                                                                         arm->act_bone = NULL;
2029                                                         }
2030                                                 }
2031                                         }
2032                                         else if (!bone_only) {
2033                                                 ED_base_object_select(base, select ? BA_SELECT : BA_DESELECT);
2034                                         }
2035                                         
2036                                         col += 4; /* next color */
2037                                         hits--;
2038                                         if (hits == 0) break;
2039                                 }
2040                         }
2041                         
2042                         if (bone_selected) {
2043                                 if (base->object && (base->object->type == OB_ARMATURE)) {
2044                                         bArmature *arm = base->object->data;
2045                                         
2046                                         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, base->object);
2047                                         
2048                                         if (arm && (arm->flag & ARM_HAS_VIZ_DEPS)) {
2049                                                 /* mask modifier ('armature' mode), etc. */
2050                                                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2051                                         }
2052                                 }
2053                         }
2054                 }
2055                 
2056                 WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc->scene);
2057         }
2058         MEM_freeN(vbuffer);
2059
2060         return hits > 0 ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2061 }
2062
2063 static int view3d_borderselect_exec(bContext *C, wmOperator *op)
2064 {
2065         ViewContext vc;
2066         rcti rect;
2067         bool extend;
2068         bool select;
2069
2070         int ret = OPERATOR_CANCELLED;
2071
2072         view3d_operator_needs_opengl(C);
2073
2074         /* setup view context for argument to callbacks */
2075         view3d_set_viewcontext(C, &vc);
2076         
2077         select = (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT);
2078         WM_operator_properties_border_to_rcti(op, &rect);
2079         extend = RNA_boolean_get(op->ptr, "extend");
2080
2081         if (vc.obedit) {
2082                 switch (vc.obedit->type) {
2083                         case OB_MESH:
2084                                 vc.em = BKE_editmesh_from_object(vc.obedit);
2085                                 ret = do_mesh_box_select(&vc, &rect, select, extend);
2086 //                      if (EM_texFaceCheck())
2087                                 if (ret & OPERATOR_FINISHED) {
2088                                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
2089                                 }
2090                                 break;
2091                         case OB_CURVE:
2092                         case OB_SURF:
2093                                 ret = do_nurbs_box_select(&vc, &rect, select, extend);
2094                                 if (ret & OPERATOR_FINISHED) {
2095                                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
2096                                 }
2097                                 break;
2098                         case OB_MBALL:
2099                                 ret = do_meta_box_select(&vc, &rect, select, extend);
2100                                 if (ret & OPERATOR_FINISHED) {
2101                                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
2102                                 }
2103                                 break;
2104                         case OB_ARMATURE:
2105                                 ret = do_armature_box_select(&vc, &rect, select, extend);
2106                                 if (ret & OPERATOR_FINISHED) {
2107                                         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, vc.obedit);
2108                                 }
2109                                 break;
2110                         case OB_LATTICE:
2111                                 ret = do_lattice_box_select(&vc, &rect, select, extend);
2112                                 if (ret & OPERATOR_FINISHED) {
2113                                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
2114                                 }
2115                                 break;
2116                         default:
2117                                 assert(!"border select on incorrect object type");
2118                                 break;
2119                 }
2120         }
2121         else {  /* no editmode, unified for bones and objects */
2122                 if (vc.obact && vc.obact->mode & OB_MODE_SCULPT) {
2123                         ret = do_sculpt_mask_box_select(&vc, &rect, select, extend);
2124                 }
2125                 else if (vc.obact && paint_facesel_test(vc.obact)) {
2126                         ret = do_paintface_box_select(&vc, &rect, select, extend);
2127                 }
2128                 else if (vc.obact && paint_vertsel_test(vc.obact)) {
2129                         ret = do_paintvert_box_select(&vc, &rect, select, extend);
2130                 }
2131                 else if (vc.obact && vc.obact->mode & OB_MODE_PARTICLE_EDIT) {
2132                         ret = PE_border_select(C, &rect, select, extend);
2133                 }
2134                 else { /* object mode with none active */
2135                         ret = do_object_pose_box_select(C, &vc, &rect, select, extend);
2136                 }
2137         }
2138
2139         return ret;
2140
2141
2142
2143 /* *****************Selection Operators******************* */
2144
2145 /* ****** Border Select ****** */
2146 void VIEW3D_OT_select_border(wmOperatorType *ot)
2147 {
2148         /* identifiers */
2149         ot->name = "Border Select";
2150         ot->description = "Select items using border selection";
2151         ot->idname = "VIEW3D_OT_select_border";
2152         
2153         /* api callbacks */
2154         ot->invoke = WM_border_select_invoke;
2155         ot->exec = view3d_borderselect_exec;
2156         ot->modal = WM_border_select_modal;
2157         ot->poll = view3d_selectable_data;
2158         ot->cancel = WM_border_select_cancel;
2159         
2160         /* flags */
2161         ot->flag = OPTYPE_UNDO;
2162         
2163         /* rna */
2164         WM_operator_properties_gesture_border(ot, true);
2165 }
2166
2167
2168 /* mouse selection in weight paint */
2169 /* gets called via generic mouse select operator */
2170 static bool mouse_weight_paint_vertex_select(bContext *C, const int mval[2], bool extend, bool deselect, bool toggle, Object *obact)
2171 {
2172         View3D *v3d = CTX_wm_view3d(C);
2173         const int use_zbuf = (v3d->flag & V3D_ZBUF_SELECT);
2174
2175         Mesh *me = obact->data; /* already checked for NULL */
2176         unsigned int index = 0;
2177         MVert *mv;
2178
2179         if (ED_mesh_pick_vert(C, obact, mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, use_zbuf)) {
2180                 mv = &me->mvert[index];
2181                 if (extend) {
2182                         mv->flag |= SELECT;
2183                 }
2184                 else if (deselect) {
2185                         mv->flag &= ~SELECT;
2186                 }
2187                 else if (toggle) {
2188                         mv->flag ^= SELECT;
2189                 }
2190                 else {
2191                         paintvert_deselect_all_visible(obact, SEL_DESELECT, false);
2192                         mv->flag |= SELECT;
2193                 }
2194
2195                 /* update mselect */
2196                 if (mv->flag & SELECT) {
2197                         BKE_mesh_mselect_active_set(me, index, ME_VSEL);
2198                 }
2199                 else {
2200                         BKE_mesh_mselect_validate(me);
2201                 }
2202
2203                 paintvert_flush_flags(obact);
2204                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
2205                 return true;
2206         }
2207         return false;
2208 }
2209
2210 /* ****** Mouse Select ****** */
2211
2212
2213 static int view3d_select_exec(bContext *C, wmOperator *op)
2214 {
2215         Object *obedit = CTX_data_edit_object(C);
2216         Object *obact = CTX_data_active_object(C);
2217         bool extend = RNA_boolean_get(op->ptr, "extend");
2218         bool deselect = RNA_boolean_get(op->ptr, "deselect");
2219         bool toggle = RNA_boolean_get(op->ptr, "toggle");
2220         bool center = RNA_boolean_get(op->ptr, "center");
2221         bool enumerate = RNA_boolean_get(op->ptr, "enumerate");
2222         bool object = (RNA_boolean_get(op->ptr, "object") && obedit);  /* only force object select for editmode */
2223         bool retval = false;
2224         int location[2];
2225
2226         RNA_int_get_array(op->ptr, "location", location);
2227
2228         view3d_operator_needs_opengl(C);
2229
2230         if (object) {
2231                 obedit = NULL;
2232                 obact = NULL;
2233
2234                 /* ack, this is incorrect but to do this correctly we would need an
2235                  * alternative editmode/objectmode keymap, this copies the functionality
2236                  * from 2.4x where Ctrl+Select in editmode does object select only */
2237                 center = false;
2238         }
2239
2240         if (obedit && object == false) {
2241                 if (obedit->type == OB_MESH)
2242                         retval = EDBM_select_pick(C, location, extend, deselect, toggle);
2243                 else if (obedit->type == OB_ARMATURE)
2244                         retval = mouse_armature(C, location, extend, deselect, toggle);
2245                 else if (obedit->type == OB_LATTICE)
2246                         retval = mouse_lattice(C, location, extend, deselect, toggle);
2247                 else if (ELEM(obedit->type, OB_CURVE, OB_SURF))
2248                         retval = mouse_nurb(C, location, extend, deselect, toggle);
2249                 else if (obedit->type == OB_MBALL)
2250                         retval = mouse_mball(C, location, extend, deselect, toggle);
2251                         
2252         }
2253         else if (obact && obact->mode & OB_MODE_SCULPT)
2254                 return OPERATOR_CANCELLED;
2255         else if (obact && obact->mode & OB_MODE_PARTICLE_EDIT)
2256                 return PE_mouse_particles(C, location, extend, deselect, toggle);
2257         else if (obact && paint_facesel_test(obact))
2258                 retval = paintface_mouse_select(C, obact, location, extend, deselect, toggle);
2259         else if (paint_vertsel_test(obact))
2260                 retval = mouse_weight_paint_vertex_select(C, location, extend, deselect, toggle, obact);
2261         else
2262                 retval = mouse_select(C, location, extend, deselect, toggle, center, enumerate, object);
2263
2264         /* passthrough allows tweaks
2265          * FINISHED to signal one operator worked
2266          * */
2267         if (retval)
2268                 return OPERATOR_PASS_THROUGH | OPERATOR_FINISHED;
2269         else
2270                 return OPERATOR_PASS_THROUGH;  /* nothing selected, just passthrough */
2271 }
2272
2273 static int view3d_select_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2274 {
2275         RNA_int_set_array(op->ptr, "location", event->mval);
2276
2277         return view3d_select_exec(C, op);
2278 }
2279
2280 void VIEW3D_OT_select(wmOperatorType *ot)
2281 {
2282         PropertyRNA *prop;
2283
2284         /* identifiers */
2285         ot->name = "Activate/Select";
2286         ot->description = "Activate/select item(s)";
2287         ot->idname = "VIEW3D_OT_select";
2288         
2289         /* api callbacks */
2290         ot->invoke = view3d_select_invoke;
2291         ot->exec = view3d_select_exec;
2292         ot->poll = ED_operator_view3d_active;
2293         
2294         /* flags */
2295         ot->flag = OPTYPE_UNDO;
2296         
2297         /* properties */
2298         WM_operator_properties_mouse_select(ot);
2299
2300         RNA_def_boolean(ot->srna, "center", 0, "Center", "Use the object center when selecting, in editmode used to extend object selection");
2301         RNA_def_boolean(ot->srna, "enumerate", 0, "Enumerate", "List objects under the mouse (object mode only)");
2302         RNA_def_boolean(ot->srna, "object", 0, "Object", "Use object selection (editmode only)");
2303
2304         prop = RNA_def_int_vector(ot->srna, "location", 2, NULL, INT_MIN, INT_MAX, "Location", "Mouse location", INT_MIN, INT_MAX);
2305         RNA_def_property_flag(prop, PROP_HIDDEN);
2306 }
2307
2308
2309 /* -------------------- circle select --------------------------------------------- */
2310
2311 typedef struct CircleSelectUserData {
2312         ViewContext *vc;
2313         bool select;
2314         int   mval[2];
2315         float mval_fl[2];
2316         float radius;
2317         float radius_squared;
2318
2319         /* runtime */
2320         bool is_changed;
2321 } CircleSelectUserData;
2322
2323 static void view3d_userdata_circleselect_init(CircleSelectUserData *r_data,
2324                                               ViewContext *vc, const bool select, const int mval[2], const float rad)
2325 {
2326         r_data->vc = vc;
2327         r_data->select = select;
2328         copy_v2_v2_int(r_data->mval, mval);
2329         r_data->mval_fl[0] = mval[0];
2330         r_data->mval_fl[1] = mval[1];
2331
2332         r_data->radius = rad;
2333         r_data->radius_squared = rad * rad;
2334
2335         /* runtime */
2336         r_data->is_changed = false;
2337 }
2338
2339 static void mesh_circle_doSelectVert(void *userData, BMVert *eve, const float screen_co[2], int UNUSED(index))
2340 {
2341         CircleSelectUserData *data = userData;
2342
2343         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2344                 BM_vert_select_set(data->vc->em->bm, eve, data->select);
2345         }
2346 }
2347 static void mesh_circle_doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int UNUSED(index))
2348 {
2349         CircleSelectUserData *data = userData;
2350
2351         if (edge_inside_circle(data->mval_fl, data->radius, screen_co_a, screen_co_b)) {
2352                 BM_edge_select_set(data->vc->em->bm, eed, data->select);
2353         }
2354 }
2355 static void mesh_circle_doSelectFace(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
2356 {
2357         CircleSelectUserData *data = userData;
2358
2359         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2360                 BM_face_select_set(data->vc->em->bm, efa, data->select);
2361         }
2362 }
2363
2364 static void mesh_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2365 {
2366         ToolSettings *ts = vc->scene->toolsettings;
2367         int bbsel;
2368         CircleSelectUserData data;
2369         
2370         bbsel = EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
2371         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
2372
2373         vc->em = BKE_editmesh_from_object(vc->obedit);
2374
2375         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2376
2377         if (ts->selectmode & SCE_SELECT_VERTEX) {
2378                 if (bbsel) {
2379                         edbm_backbuf_check_and_select_verts(vc->em, select);
2380                 }
2381                 else {
2382                         mesh_foreachScreenVert(vc, mesh_circle_doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2383                 }
2384         }
2385
2386         if (ts->selectmode & SCE_SELECT_EDGE) {
2387                 if (bbsel) {
2388                         edbm_backbuf_check_and_select_edges(vc->em, select);
2389                 }
2390                 else {
2391                         mesh_foreachScreenEdge(vc, mesh_circle_doSelectEdge, &data, V3D_PROJ_TEST_CLIP_NEAR);
2392                 }
2393         }
2394         
2395         if (ts->selectmode & SCE_SELECT_FACE) {
2396                 if (bbsel) {
2397                         edbm_backbuf_check_and_select_faces(vc->em, select);
2398                 }
2399                 else {
2400                         mesh_foreachScreenFace(vc, mesh_circle_doSelectFace, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2401                 }
2402         }
2403
2404         EDBM_backbuf_free();
2405         EDBM_selectmode_flush(vc->em);
2406 }
2407
2408 static void paint_facesel_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2409 {
2410         Object *ob = vc->obact;
2411         Mesh *me = ob->data;
2412         bool bbsel;
2413
2414         bm_vertoffs = me->totpoly + 1; /* max index array */
2415
2416         bbsel = EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
2417         if (bbsel) {
2418                 edbm_backbuf_check_and_select_tfaces(me, select);
2419                 EDBM_backbuf_free();
2420                 paintface_flush_flags(ob);
2421         }
2422 }
2423
2424 static void paint_vertsel_circle_select_doSelectVert(void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
2425 {
2426         CircleSelectUserData *data = userData;
2427
2428         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2429                 BKE_BIT_TEST_SET(mv->flag, data->select, SELECT);
2430         }
2431 }
2432 static void paint_vertsel_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2433 {
2434         const int use_zbuf = (vc->v3d->flag & V3D_ZBUF_SELECT);
2435         Object *ob = vc->obact;
2436         Mesh *me = ob->data;
2437         bool bbsel;
2438         /* CircleSelectUserData data = {NULL}; */ /* UNUSED */
2439
2440         if (use_zbuf) {
2441                 bm_vertoffs = me->totvert + 1; /* max index array */
2442
2443                 bbsel = EDBM_backbuf_circle_init(vc, mval[0], mval[1], (short)(rad + 1.0f));
2444                 if (bbsel) {
2445                         edbm_backbuf_check_and_select_verts_obmode(me, select);
2446                         EDBM_backbuf_free();
2447                 }
2448         }
2449         else {
2450                 CircleSelectUserData data;
2451
2452                 ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d); /* for foreach's screen/vert projection */
2453
2454                 view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2455                 meshobject_foreachScreenVert(vc, paint_vertsel_circle_select_doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2456         }
2457
2458         if (select != LEFTMOUSE) {
2459                 BKE_mesh_mselect_validate(me);
2460         }
2461         paintvert_flush_flags(ob);
2462 }
2463
2464
2465 static void nurbscurve_circle_doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
2466 {
2467         CircleSelectUserData *data = userData;
2468         Object *obedit = data->vc->obedit;
2469         Curve *cu = (Curve *)obedit->data;
2470
2471         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2472                 if (bp) {
2473                         bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
2474                 }
2475                 else {
2476                         if (cu->drawflag & CU_HIDE_HANDLES) {
2477                                 /* can only be (beztindex == 0) here since handles are hidden */
2478                                 bezt->f1 = bezt->f2 = bezt->f3 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
2479                         }
2480                         else {
2481                                 if (beztindex == 0) {
2482                                         bezt->f1 = data->select ? (bezt->f1 | SELECT) : (bezt->f1 & ~SELECT);
2483                                 }
2484                                 else if (beztindex == 1) {
2485                                         bezt->f2 = data->select ? (bezt->f2 | SELECT) : (bezt->f2 & ~SELECT);
2486                                 }
2487                                 else {
2488                                         bezt->f3 = data->select ? (bezt->f3 | SELECT) : (bezt->f3 & ~SELECT);
2489                                 }
2490                         }
2491                 }
2492         }
2493 }
2494 static void nurbscurve_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2495 {
2496         CircleSelectUserData data;
2497
2498         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2499
2500         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
2501         nurbs_foreachScreenVert(vc, nurbscurve_circle_doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2502         BKE_curve_nurb_vert_active_validate(vc->obedit->data);
2503 }
2504
2505
2506 static void latticecurve_circle_doSelect(void *userData, BPoint *bp, const float screen_co[2])
2507 {
2508         CircleSelectUserData *data = userData;
2509
2510         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2511                 bp->f1 = data->select ? (bp->f1 | SELECT) : (bp->f1 & ~SELECT);
2512         }
2513 }
2514 static void lattice_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2515 {
2516         CircleSelectUserData data;
2517
2518         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2519
2520         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d); /* for foreach's screen/vert projection */
2521         lattice_foreachScreenVert(vc, latticecurve_circle_doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2522 }
2523
2524
2525 /* NOTE: pose-bone case is copied from editbone case... */
2526 static short pchan_circle_doSelectJoint(void *userData, bPoseChannel *pchan, const float screen_co[2])
2527 {
2528         CircleSelectUserData *data = userData;
2529
2530         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2531                 if (data->select)
2532                         pchan->bone->flag |= BONE_SELECTED;
2533                 else
2534                         pchan->bone->flag &= ~BONE_SELECTED;
2535                 return 1;
2536         }
2537         return 0;
2538 }
2539 static void do_circle_select_pose__doSelectBone(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
2540 {
2541         CircleSelectUserData *data = userData;
2542         bArmature *arm = data->vc->obact->data;
2543
2544         if (PBONE_SELECTABLE(arm, pchan->bone)) {
2545                 bool is_point_done = false;
2546                 int points_proj_tot = 0;
2547
2548                 /* project head location to screenspace */
2549                 if (screen_co_a[0] != IS_CLIPPED) {
2550                         points_proj_tot++;
2551                         if (pchan_circle_doSelectJoint(data, pchan, screen_co_a)) {
2552                                 is_point_done = true;
2553                         }
2554                 }
2555
2556                 /* project tail location to screenspace */
2557                 if (screen_co_b[0] != IS_CLIPPED) {
2558                         points_proj_tot++;
2559                         if (pchan_circle_doSelectJoint(data, pchan, screen_co_b)) {
2560                                 is_point_done = true;
2561                         }
2562                 }
2563
2564                 /* check if the head and/or tail is in the circle
2565                  * - the call to check also does the selection already
2566                  */
2567
2568                 /* only if the endpoints didn't get selected, deal with the middle of the bone too
2569                  * It works nicer to only do this if the head or tail are not in the circle,
2570                  * otherwise there is no way to circle select joints alone */
2571                 if ((is_point_done == false) && (points_proj_tot == 2) &&
2572                     edge_inside_circle(data->mval_fl, data->radius, screen_co_a, screen_co_b))
2573                 {
2574                         if (data->select) pchan->bone->flag |= BONE_SELECTED;
2575                         else              pchan->bone->flag &= ~BONE_SELECTED;
2576                         data->is_changed = true;
2577                 }
2578
2579                 data->is_changed |= is_point_done;
2580         }
2581 }
2582 static void pose_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2583 {
2584         CircleSelectUserData data;
2585         
2586         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2587
2588         ED_view3d_init_mats_rv3d(vc->obact, vc->rv3d); /* for foreach's screen/vert projection */
2589         
2590         pose_foreachScreenBone(vc, do_circle_select_pose__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2591
2592         if (data.is_changed) {
2593                 bArmature *arm = vc->obact->data;
2594
2595                 WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obact);
2596
2597                 if (arm->flag & ARM_HAS_VIZ_DEPS) {
2598                         /* mask modifier ('armature' mode), etc. */
2599                         DAG_id_tag_update(&vc->obact->id, OB_RECALC_DATA);
2600                 }
2601         }
2602 }
2603
2604 static short armature_circle_doSelectJoint(void *userData, EditBone *ebone, const float screen_co[2], short head)
2605 {
2606         CircleSelectUserData *data = userData;
2607
2608         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2609                 if (head) {
2610                         if (data->select)
2611                                 ebone->flag |= BONE_ROOTSEL;
2612                         else 
2613                                 ebone->flag &= ~BONE_ROOTSEL;
2614                 }
2615                 else {
2616                         if (data->select)
2617                                 ebone->flag |= BONE_TIPSEL;
2618                         else 
2619                                 ebone->flag &= ~BONE_TIPSEL;
2620                 }
2621                 return 1;
2622         }
2623         return 0;
2624 }
2625 static void do_circle_select_armature__doSelectBone(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
2626 {
2627         CircleSelectUserData *data = userData;
2628         bArmature *arm = data->vc->obedit->data;
2629
2630         if (data->select ? EBONE_SELECTABLE(arm, ebone) : EBONE_VISIBLE(arm, ebone)) {
2631                 bool is_point_done = false;
2632                 int points_proj_tot = 0;
2633
2634                 /* project head location to screenspace */
2635                 if (screen_co_a[0] != IS_CLIPPED) {
2636                         points_proj_tot++;
2637                         if (armature_circle_doSelectJoint(data, ebone, screen_co_a, true)) {
2638                                 is_point_done = true;
2639                         }
2640                 }
2641
2642                 /* project tail location to screenspace */
2643                 if (screen_co_b[0] != IS_CLIPPED) {
2644                         points_proj_tot++;
2645                         if (armature_circle_doSelectJoint(data, ebone, screen_co_b, false)) {
2646                                 is_point_done = true;
2647                         }
2648                 }
2649
2650                 /* check if the head and/or tail is in the circle
2651                  * - the call to check also does the selection already
2652                  */
2653
2654                 /* only if the endpoints didn't get selected, deal with the middle of the bone too
2655                  * It works nicer to only do this if the head or tail are not in the circle,
2656                  * otherwise there is no way to circle select joints alone */
2657                 if ((is_point_done == false) && (points_proj_tot == 2) &&
2658                     edge_inside_circle(data->mval_fl, data->radius, screen_co_a, screen_co_b))
2659                 {
2660                         if (data->select) ebone->flag |=  (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2661                         else              ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2662                         data->is_changed = true;
2663                 }
2664
2665                 data->is_changed |= is_point_done;
2666         }
2667 }
2668 static void armature_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2669 {
2670         CircleSelectUserData data;
2671         bArmature *arm = vc->obedit->data;
2672
2673         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2674
2675         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
2676
2677         armature_foreachScreenBone(vc, do_circle_select_armature__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2678
2679         if (data.is_changed) {
2680                 ED_armature_sync_selection(arm->edbo);
2681                 ED_armature_validate_active(arm);
2682                 WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obedit);
2683         }
2684 }
2685
2686 static void do_circle_select_mball__doSelectElem(void *userData, struct MetaElem *ml, const float screen_co[2])
2687 {
2688         CircleSelectUserData *data = userData;
2689
2690         if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
2691                 if (data->select) ml->flag |=  SELECT;
2692                 else              ml->flag &= ~SELECT;
2693                 data->is_changed = true;
2694         }
2695 }
2696 static void mball_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2697 {
2698         CircleSelectUserData data;
2699
2700         view3d_userdata_circleselect_init(&data, vc, select, mval, rad);
2701
2702         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
2703
2704         mball_foreachScreenElem(vc, do_circle_select_mball__doSelectElem, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
2705 }
2706
2707 /** Callbacks for circle selection in Editmode */
2708
2709 static void obedit_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2710 {
2711         switch (vc->obedit->type) {
2712                 case OB_MESH:
2713                         mesh_circle_select(vc, select, mval, rad);
2714                         break;
2715                 case OB_CURVE:
2716                 case OB_SURF:
2717                         nurbscurve_circle_select(vc, select, mval, rad);
2718                         break;
2719                 case OB_LATTICE:
2720                         lattice_circle_select(vc, select, mval, rad);
2721                         break;
2722                 case OB_ARMATURE:
2723                         armature_circle_select(vc, select, mval, rad);
2724                         break;
2725                 case OB_MBALL:
2726                         mball_circle_select(vc, select, mval, rad);
2727                         break;
2728                 default:
2729                         return;
2730         }
2731 }
2732
2733 static bool object_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
2734 {
2735         Scene *scene = vc->scene;
2736         const float radius_squared = rad * rad;
2737         const float mval_fl[2] = {mval[0], mval[1]};
2738         bool changed = false;
2739         const int select_flag = select ? SELECT : 0;
2740
2741
2742         Base *base;
2743         for (base = FIRSTBASE; base; base = base->next) {
2744                 if (BASE_SELECTABLE(vc->v3d, base) && ((base->flag & SELECT) != select_flag)) {
2745                         float screen_co[2];
2746                         if (ED_view3d_project_float_global(vc->ar, base->object->obmat[3], screen_co,
2747                                                            V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
2748                         {
2749                                 if (len_squared_v2v2(mval_fl, screen_co) <= radius_squared) {
2750                                         ED_base_object_select(base, select ? BA_SELECT : BA_DESELECT);
2751                                         changed = true;
2752                                 }
2753                         }
2754                 }
2755         }
2756
2757         return changed;
2758 }
2759
2760 /* not a real operator, only for circle test */
2761 static int view3d_circle_select_exec(bContext *C, wmOperator *op)
2762 {
2763         Scene *scene = CTX_data_scene(C);
2764         Object *obact = CTX_data_active_object(C);
2765         const int radius = RNA_int_get(op->ptr, "radius");
2766         const int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
2767         const bool select = (gesture_mode == GESTURE_MODAL_SELECT);
2768         const int mval[2] = {RNA_int_get(op->ptr, "x"),
2769                              RNA_int_get(op->ptr, "y")};
2770
2771         if (CTX_data_edit_object(C) || paint_facesel_test(obact) || paint_vertsel_test(obact) ||
2772             (obact && (obact->mode & (OB_MODE_PARTICLE_EDIT | OB_MODE_POSE))) )
2773         {
2774                 ViewContext vc;
2775                 
2776                 view3d_operator_needs_opengl(C);
2777                 
2778                 view3d_set_viewcontext(C, &vc);
2779
2780                 if (CTX_data_edit_object(C)) {
2781                         obedit_circle_select(&vc, select, mval, (float)radius);
2782                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
2783                 }
2784                 else if (paint_facesel_test(obact)) {
2785                         paint_facesel_circle_select(&vc, select, mval, (float)radius);
2786                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
2787                 }
2788                 else if (paint_vertsel_test(obact)) {
2789                         paint_vertsel_circle_select(&vc, select, mval, (float)radius);
2790                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
2791                 }
2792                 else if (obact->mode & OB_MODE_POSE)
2793                         pose_circle_select(&vc, select, mval, (float)radius);
2794                 else
2795                         return PE_circle_select(C, select, mval, (float)radius);
2796         }
2797         else if (obact && obact->mode & OB_MODE_SCULPT) {
2798                 return OPERATOR_CANCELLED;
2799         }
2800         else {
2801                 ViewContext vc;
2802                 view3d_set_viewcontext(C, &vc);
2803
2804                 if (object_circle_select(&vc, select, mval, (float)radius)) {
2805                         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
2806                 }
2807         }
2808         
2809         return OPERATOR_FINISHED;
2810 }
2811
2812 void VIEW3D_OT_select_circle(wmOperatorType *ot)
2813 {
2814         ot->name = "Circle Select";
2815         ot->description = "Select items using circle selection";
2816         ot->idname = "VIEW3D_OT_select_circle";
2817         
2818         ot->invoke = WM_gesture_circle_invoke;
2819         ot->modal = WM_gesture_circle_modal;
2820         ot->exec = view3d_circle_select_exec;
2821         ot->poll = view3d_selectable_data;
2822         ot->cancel = WM_gesture_circle_cancel;
2823         
2824         /* flags */
2825         ot->flag = OPTYPE_UNDO;
2826         
2827         RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
2828         RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
2829         RNA_def_int(ot->srna, "radius", 0, INT_MIN, INT_MAX, "Radius", "", INT_MIN, INT_MAX);
2830         RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Event Type", "", INT_MIN, INT_MAX);
2831 }