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