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