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