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