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