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