svn merge ^/trunk/blender -r46714:46724 --- before tile branch merge
[blender.git] / source / blender / editors / space_clip / tracking_ops.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) 2011 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation,
23  *                 Sergey Sharybin
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/space_clip/tracking_ops.c
29  *  \ingroup spclip
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_camera_types.h"
35 #include "DNA_constraint_types.h"
36 #include "DNA_gpencil_types.h"
37 #include "DNA_movieclip_types.h"
38 #include "DNA_object_types.h"   /* SELECT */
39 #include "DNA_scene_types.h"
40
41 #include "BLI_utildefines.h"
42 #include "BLI_math.h"
43 #include "BLI_listbase.h"
44 #include "BLI_rect.h"
45 #include "BLI_lasso.h"
46 #include "BLI_blenlib.h"
47
48 #include "BKE_main.h"
49 #include "BKE_context.h"
50 #include "BKE_constraint.h"
51 #include "BKE_movieclip.h"
52 #include "BKE_tracking.h"
53 #include "BKE_global.h"
54 #include "BKE_depsgraph.h"
55 #include "BKE_object.h"
56 #include "BKE_report.h"
57 #include "BKE_scene.h"
58 #include "BKE_library.h"
59 #include "BKE_sound.h"
60
61 #include "WM_api.h"
62 #include "WM_types.h"
63
64 #include "ED_screen.h"
65 #include "ED_clip.h"
66 #include "ED_keyframing.h"
67
68 #include "IMB_imbuf_types.h"
69 #include "IMB_imbuf.h"
70
71 #include "UI_interface.h"
72
73 #include "RNA_access.h"
74 #include "RNA_define.h"
75
76 #include "PIL_time.h"
77
78 #include "UI_view2d.h"
79
80 #include "clip_intern.h"        // own include
81
82 static float dist_to_crns(float co[2], float pos[2], float crns[4][2]);
83
84 /********************** add marker operator *********************/
85
86 static void add_marker(SpaceClip *sc, float x, float y)
87 {
88         MovieClip *clip = ED_space_clip(sc);
89         MovieTracking *tracking = &clip->tracking;
90         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
91         MovieTrackingTrack *track;
92         int width, height;
93
94         ED_space_clip_size(sc, &width, &height);
95
96         track = BKE_tracking_add_track(tracking, tracksbase, x, y, sc->user.framenr, width, height);
97
98         BKE_tracking_select_track(tracksbase, track, TRACK_AREA_ALL, 0);
99
100         clip->tracking.act_track = track;
101 }
102
103 static int add_marker_exec(bContext *C, wmOperator *op)
104 {
105         SpaceClip *sc = CTX_wm_space_clip(C);
106         MovieClip *clip = ED_space_clip(sc);
107         float pos[2];
108         int width, height;
109
110         ED_space_clip_size(sc, &width, &height);
111         if (!width || !height)
112                 return OPERATOR_CANCELLED;
113
114         RNA_float_get_array(op->ptr, "location", pos);
115
116         add_marker(sc, pos[0], pos[1]);
117
118         /* reset offset from locked position, so frame jumping wouldn't be so confusing */
119         sc->xlockof = 0;
120         sc->ylockof = 0;
121
122         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
123
124         return OPERATOR_FINISHED;
125 }
126
127 static int add_marker_invoke(bContext *C, wmOperator *op, wmEvent *event)
128 {
129         float co[2];
130
131         ED_clip_mouse_pos(C, event, co);
132
133         RNA_float_set_array(op->ptr, "location", co);
134
135         return add_marker_exec(C, op);
136 }
137
138 void CLIP_OT_add_marker(wmOperatorType *ot)
139 {
140         /* identifiers */
141         ot->name = "Add Marker";
142         ot->idname = "CLIP_OT_add_marker";
143         ot->description = "Place new marker at specified location";
144
145         /* api callbacks */
146         ot->invoke = add_marker_invoke;
147         ot->exec = add_marker_exec;
148         ot->poll = ED_space_clip_tracking_size_poll;
149
150         /* flags */
151         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
152
153         /* properties */
154         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MIN, FLT_MAX,
155                 "Location", "Location of marker on frame", -1.0f, 1.0f);
156 }
157
158 /********************** delete track operator *********************/
159
160 static int delete_track_exec(bContext *C, wmOperator *UNUSED(op))
161 {
162         SpaceClip *sc = CTX_wm_space_clip(C);
163         MovieClip *clip = ED_space_clip(sc);
164         MovieTracking *tracking = &clip->tracking;
165         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
166         MovieTrackingTrack *track = tracksbase->first, *next;
167
168         while (track) {
169                 next = track->next;
170
171                 if (TRACK_VIEW_SELECTED(sc, track))
172                         clip_delete_track(C, clip, tracksbase, track);
173
174                 track = next;
175         }
176
177         /* nothing selected now, unlock view so it can be scrolled nice again */
178         sc->flag &= ~SC_LOCK_SELECTION;
179
180         return OPERATOR_FINISHED;
181 }
182
183 void CLIP_OT_delete_track(wmOperatorType *ot)
184 {
185         /* identifiers */
186         ot->name = "Delete Track";
187         ot->idname = "CLIP_OT_delete_track";
188         ot->description = "Delete selected tracks";
189
190         /* api callbacks */
191         ot->invoke = WM_operator_confirm;
192         ot->exec = delete_track_exec;
193         ot->poll = ED_space_clip_tracking_poll;
194
195         /* flags */
196         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
197 }
198
199 /********************** delete marker operator *********************/
200
201 static int delete_marker_exec(bContext *C, wmOperator *UNUSED(op))
202 {
203         SpaceClip *sc = CTX_wm_space_clip(C);
204         MovieClip *clip = ED_space_clip(sc);
205         ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
206         MovieTrackingTrack *track = tracksbase->first, *next;
207         int framenr = sc->user.framenr;
208         int has_selection = 0;
209
210         while (track) {
211                 next = track->next;
212
213                 if (TRACK_VIEW_SELECTED(sc, track)) {
214                         MovieTrackingMarker *marker = BKE_tracking_exact_marker(track, framenr);
215
216                         if (marker) {
217                                 has_selection |= track->markersnr > 1;
218
219                                 clip_delete_marker(C, clip, tracksbase, track, marker);
220                         }
221                 }
222
223                 track = next;
224         }
225
226         if (!has_selection) {
227                 /* nothing selected now, unlock view so it can be scrolled nice again */
228                 sc->flag &= ~SC_LOCK_SELECTION;
229         }
230
231         return OPERATOR_FINISHED;
232 }
233
234 void CLIP_OT_delete_marker(wmOperatorType *ot)
235 {
236         /* identifiers */
237         ot->name = "Delete Marker";
238         ot->idname = "CLIP_OT_delete_marker";
239         ot->description = "Delete marker for current frame from selected tracks";
240
241         /* api callbacks */
242         ot->invoke = WM_operator_confirm;
243         ot->exec = delete_marker_exec;
244         ot->poll = ED_space_clip_tracking_poll;
245
246         /* flags */
247         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
248 }
249
250 /********************** slide marker operator *********************/
251
252 #define SLIDE_ACTION_POS        0
253 #define SLIDE_ACTION_SIZE       1
254 #define SLIDE_ACTION_OFFSET     2
255
256 typedef struct {
257         int area, action;
258         MovieTrackingTrack *track;
259         MovieTrackingMarker *marker;
260
261         int mval[2];
262         int width, height;
263         float *min, *max, *pos, *offset, (*corners)[2];
264         float smin[2], smax[2], spos[2], soff[2], scorners[4][2];
265         float (*smarkers)[2];
266
267         int lock, accurate, scale;
268 } SlideMarkerData;
269
270 static SlideMarkerData *create_slide_marker_data(SpaceClip *sc, MovieTrackingTrack *track,
271                                                  MovieTrackingMarker *marker, wmEvent *event,
272                                                                                                  int area, int corner, int action, int width, int height)
273 {
274         SlideMarkerData *data = MEM_callocN(sizeof(SlideMarkerData), "slide marker data");
275
276         marker = BKE_tracking_ensure_marker(track, sc->user.framenr);
277
278         data->area = area;
279         data->action = action;
280         data->track = track;
281         data->marker = marker;
282
283         if (area == TRACK_AREA_POINT) {
284                 data->pos = marker->pos;
285                 data->offset = track->offset;
286                 copy_v2_v2(data->spos, marker->pos);
287                 copy_v2_v2(data->soff, track->offset);
288         }
289         else if (area == TRACK_AREA_PAT) {
290                 if (action == SLIDE_ACTION_SIZE) {
291                         data->corners = marker->pattern_corners;
292                 }
293                 else if (action == SLIDE_ACTION_OFFSET) {
294                         int a;
295
296                         data->pos = marker->pos;
297                         data->offset = track->offset;
298
299                         copy_v2_v2(data->soff, track->offset);
300
301                         data->smarkers = MEM_callocN(sizeof(*data->smarkers)*track->markersnr, "slide marekrs");
302                         for (a = 0; a < track->markersnr; a++)
303                                 copy_v2_v2(data->smarkers[a], track->markers[a].pos);
304                 }
305                 else if (action == SLIDE_ACTION_POS) {
306                         data->corners = marker->pattern_corners;
307                         data->pos = marker->pattern_corners[corner];
308
309                         copy_v2_v2(data->spos, data->pos);
310                 }
311         }
312         else if (area == TRACK_AREA_SEARCH) {
313                 data->min = track->search_min;
314                 data->max = track->search_max;
315         }
316
317         if ((area == TRACK_AREA_SEARCH) ||
318                 (area == TRACK_AREA_PAT && action != SLIDE_ACTION_OFFSET))
319         {
320                 if (data->corners) {
321                         memcpy(data->scorners, data->corners, sizeof(data->scorners));
322                 }
323                 else {
324                         copy_v2_v2(data->smin, data->min);
325                         copy_v2_v2(data->smax, data->max);
326                 }
327         }
328
329         data->mval[0] = event->mval[0];
330         data->mval[1] = event->mval[1];
331
332         data->width = width;
333         data->height = height;
334
335         if (action == SLIDE_ACTION_SIZE)
336                 data->lock = 1;
337
338         return data;
339 }
340
341 static int mouse_on_corner(SpaceClip *sc, MovieTrackingTrack *track, MovieTrackingMarker *marker,
342                            int area, float co[2], int corner, int width, int height)
343 {
344         int inside = 0;
345         float size = 12.0f;
346         float min[2], max[2];
347         float crn[2], dx, dy, tdx, tdy;
348
349         if (area == TRACK_AREA_SEARCH) {
350                 copy_v2_v2(min, track->search_min);
351                 copy_v2_v2(max, track->search_max);
352         }
353         else {
354                 BKE_tracking_marker_pattern_minmax(marker, min, max);
355         }
356
357         dx = size / width / sc->zoom;
358         dy = size / height / sc->zoom;
359
360         tdx = 5.0f / width / sc->zoom;
361         tdy = 5.0f / height / sc->zoom;
362
363         dx = MIN2(dx, (max[0] - min[0]) / 6.0f) + tdx;
364         dy = MIN2(dy, (max[1] - min[1]) / 6.0f) + tdy;
365
366         if (corner == 0) {
367                 crn[0] = marker->pos[0] + max[0];
368                 crn[1] = marker->pos[1] + min[1];
369
370                 inside = co[0] >= crn[0] - dx && co[0] <= crn[0] + tdx && co[1] >= crn[1] - tdy && co[1] <= crn[1] + dy;
371         }
372         else {
373                 crn[0] = marker->pos[0] + min[0];
374                 crn[1] = marker->pos[1] + max[1];
375
376                 inside = co[0] >= crn[0] - dx && co[0] <= crn[0] + dx && co[1] >= crn[1] - dy && co[1] <= crn[1] + dy;
377         }
378
379         return inside;
380 }
381
382 static int get_mouse_pattern_corner(SpaceClip *sc, MovieTrackingMarker *marker, float co[2], int width, int height)
383 {
384         int i, next;
385         float len = FLT_MAX, dx, dy;
386
387         for (i = 0; i < 4; i++) {
388                 float cur_len;
389
390                 next = (i + 1) % 4;
391
392                 cur_len = len_v2v2(marker->pattern_corners[i], marker->pattern_corners[next]);
393
394                 len = MIN2(cur_len, len);
395         }
396
397         dx = 6.0f / width / sc->zoom;
398         dy = 6.0f / height / sc->zoom;
399
400         dx = MIN2(dx * 2.0f / 3.0f, len / 6.0f);
401         dy = MIN2(dy * 2.0f / 3.0f, len * width / height / 6.0f);
402
403         for (i = 0; i < 4; i++) {
404                 float crn[2];
405                 int inside;
406
407                 add_v2_v2v2(crn, marker->pattern_corners[i], marker->pos);
408
409                 inside = IN_RANGE_INCL(co[0], crn[0] - dx, crn[0] + dx) &&
410                          IN_RANGE_INCL(co[1], crn[1] - dy, crn[1] + dy);
411
412                 if (inside)
413                         return i;
414         }
415
416         return -1;
417 }
418
419 static int mouse_on_offset(SpaceClip *sc, MovieTrackingTrack *track, MovieTrackingMarker *marker,
420                            float co[2], int width, int height)
421 {
422         float pos[2], dx, dy;
423         float pat_min[2], pat_max[2];
424
425         BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max);
426
427         add_v2_v2v2(pos, marker->pos, track->offset);
428
429         dx = 12.0f / width / sc->zoom;
430         dy = 12.0f / height / sc->zoom;
431
432         dx = MIN2(dx, (pat_max[0] - pat_min[0]) / 2.0f);
433         dy = MIN2(dy, (pat_max[1] - pat_min[1]) / 2.0f);
434
435         return co[0] >= pos[0] - dx && co[0] <= pos[0] + dx && co[1] >= pos[1] - dy && co[1] <= pos[1] + dy;
436 }
437
438 static int slide_check_corners(float (*corners)[2])
439 {
440         int i, next, prev;
441         float cross = 0.0f;
442         float p[2] = {0.0f, 0.0f};
443
444         if (!isect_point_quad_v2(p, corners[0], corners[1], corners[2], corners[3]))
445                 return FALSE;
446
447         for (i = 0; i < 4; i++) {
448                 float v1[2], v2[2], cur_cross;
449
450                 next = (i + 1) % 4;
451                 prev = (4 + i - 1) % 4;
452
453                 sub_v2_v2v2(v1, corners[i], corners[prev]);
454                 sub_v2_v2v2(v2, corners[next], corners[i]);
455
456                 cur_cross = cross_v2v2(v1, v2);
457
458                 if (fabsf(cur_cross) > FLT_EPSILON) {
459                         if (cross == 0.0f) {
460                                 cross = cur_cross;
461                         }
462                         else if (cross * cur_cross < 0.0f) {
463                                 return FALSE;
464                         }
465                 }
466         }
467
468         return TRUE;
469 }
470
471 static void hide_cursor(bContext *C)
472 {
473         wmWindow *win = CTX_wm_window(C);
474
475         WM_cursor_set(win, CURSOR_NONE);
476 }
477
478 static void show_cursor(bContext *C)
479 {
480         wmWindow *win = CTX_wm_window(C);
481
482         WM_cursor_set(win, CURSOR_STD);
483 }
484
485 static void *slide_marker_customdata(bContext *C, wmEvent *event)
486 {
487         SpaceClip *sc = CTX_wm_space_clip(C);
488         MovieClip *clip = ED_space_clip(sc);
489         MovieTrackingTrack *track;
490         int width, height;
491         float co[2];
492         void *customdata = NULL;
493         ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
494
495         ED_space_clip_size(sc, &width, &height);
496
497         if (width == 0 || height == 0)
498                 return NULL;
499
500         ED_clip_mouse_pos(C, event, co);
501
502         track = tracksbase->first;
503         while (track) {
504                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
505                         MovieTrackingMarker *marker = BKE_tracking_get_marker(track, sc->user.framenr);
506
507                         if ((marker->flag & MARKER_DISABLED) == 0) {
508                                 if (!customdata) {
509                                         if (mouse_on_offset(sc, track, marker, co, width, height))
510                                                 customdata = create_slide_marker_data(sc, track, marker, event, TRACK_AREA_POINT, 0,
511                                                                                       SLIDE_ACTION_POS, width, height);
512                                 }
513
514                                 if (sc->flag & SC_SHOW_MARKER_SEARCH) {
515                                         if (mouse_on_corner(sc, track, marker, TRACK_AREA_SEARCH, co, 1, width, height)) {
516                                                 customdata = create_slide_marker_data(sc, track, marker, event, TRACK_AREA_SEARCH, 0,
517                                                                                       SLIDE_ACTION_OFFSET, width, height);
518                                         }
519                                         else if (mouse_on_corner(sc, track, marker, TRACK_AREA_SEARCH, co, 0, width, height)) {
520                                                 customdata = create_slide_marker_data(sc, track, marker, event, TRACK_AREA_SEARCH, 0,
521                                                                                       SLIDE_ACTION_SIZE, width, height);
522                                         }
523                                 }
524
525                                 if (!customdata && (sc->flag & SC_SHOW_MARKER_PATTERN)) {
526                                         /* XXX: need to be real check if affine tracking is enabled, but for now not
527                                          *      sure how to do this, so assume affine tracker is always enabled */
528                                         if (TRUE) {
529                                                 int corner = get_mouse_pattern_corner(sc, marker, co, width, height);
530
531                                                 if (corner != -1) {
532                                                         customdata = create_slide_marker_data(sc, track, marker, event, TRACK_AREA_PAT, corner,
533                                                                                               SLIDE_ACTION_POS, width, height);
534                                                 }
535                                         }
536                                         else {
537                                                 if (mouse_on_corner(sc, track, marker, TRACK_AREA_PAT, co, 1,  width, height)) {
538                                                         customdata = create_slide_marker_data(sc, track, marker, event, TRACK_AREA_PAT, 0,
539                                                                                               SLIDE_ACTION_OFFSET, width, height);
540                                                 }
541
542                                                 if (!customdata && mouse_on_corner(sc, track, marker, TRACK_AREA_PAT, co, 0, width, height)) {
543                                                         customdata = create_slide_marker_data(sc, track, marker, event, TRACK_AREA_PAT, 0,
544                                                                                               SLIDE_ACTION_SIZE, width, height);
545                                                 }
546                                         }
547                                 }
548
549                                 if (customdata)
550                                         break;
551                         }
552                 }
553
554                 track = track->next;
555         }
556
557         return customdata;
558 }
559
560 static int slide_marker_invoke(bContext *C, wmOperator *op, wmEvent *event)
561 {
562         SlideMarkerData *slidedata = slide_marker_customdata(C, event);
563
564         if (slidedata) {
565                 SpaceClip *sc = CTX_wm_space_clip(C);
566                 MovieClip *clip = ED_space_clip(sc);
567                 MovieTracking *tracking = &clip->tracking;
568
569                 tracking->act_track = slidedata->track;
570
571                 op->customdata = slidedata;
572
573                 hide_cursor(C);
574                 WM_event_add_modal_handler(C, op);
575
576                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
577
578                 return OPERATOR_RUNNING_MODAL;
579         }
580
581         return OPERATOR_PASS_THROUGH;
582 }
583
584 static void cancel_mouse_slide(SlideMarkerData *data)
585 {
586         /* cancel sliding */
587         if (data->area == TRACK_AREA_POINT) {
588                 if (data->action == SLIDE_ACTION_OFFSET)
589                         copy_v2_v2(data->offset, data->soff);
590                 else
591                         copy_v2_v2(data->pos, data->spos);
592         }
593         else {
594                 if ((data->action == SLIDE_ACTION_SIZE) ||
595                     (data->action == SLIDE_ACTION_POS && data->area == TRACK_AREA_PAT))
596                 {
597                         if (data->corners) {
598                                 memcpy(data->corners, data->scorners, sizeof(data->scorners));
599                         }
600                         else {
601                                 copy_v2_v2(data->min, data->smin);
602                                 copy_v2_v2(data->max, data->smax);
603                         }
604                 }
605                 else {
606                         int a;
607
608                         for (a = 0; a < data->track->markersnr; a++)
609                                 copy_v2_v2(data->track->markers[a].pos, data->smarkers[a]);
610
611                         copy_v2_v2(data->offset, data->soff);
612                 }
613         }
614 }
615
616 static void free_slide_data(SlideMarkerData *data)
617 {
618         if (data->smarkers)
619                 MEM_freeN(data->smarkers);
620
621         MEM_freeN(data);
622 }
623
624 static int slide_marker_modal(bContext *C, wmOperator *op, wmEvent *event)
625 {
626         SpaceClip *sc = CTX_wm_space_clip(C);
627         SlideMarkerData *data = (SlideMarkerData *)op->customdata;
628         float dx, dy, mdelta[2];
629
630         switch (event->type) {
631                 case LEFTCTRLKEY:
632                 case RIGHTCTRLKEY:
633                 case LEFTSHIFTKEY:
634                 case RIGHTSHIFTKEY:
635                         if (data->action == SLIDE_ACTION_SIZE)
636                                 if (ELEM(event->type, LEFTCTRLKEY, RIGHTCTRLKEY))
637                                         data->lock = event->val == KM_RELEASE;
638
639                         if (data->action == SLIDE_ACTION_POS)
640                                 if (ELEM(event->type, LEFTCTRLKEY, RIGHTCTRLKEY))
641                                         data->scale = event->val == KM_PRESS;
642
643                         if (ELEM(event->type, LEFTSHIFTKEY, RIGHTSHIFTKEY))
644                                 data->accurate = event->val == KM_PRESS;
645
646                         /* no break! update area size */
647
648                 case MOUSEMOVE:
649                         mdelta[0] = event->mval[0] - data->mval[0];
650                         mdelta[1] = event->mval[1] - data->mval[1];
651
652                         dx = mdelta[0] / data->width / sc->zoom;
653
654                         if (data->lock)
655                                 dy = -dx / data->height * data->width;
656                         else
657                                 dy = mdelta[1] / data->height / sc->zoom;
658
659                         if (data->accurate) {
660                                 dx /= 5;
661                                 dy /= 5;
662                         }
663
664                         if (data->area == TRACK_AREA_POINT) {
665                                 if (data->action == SLIDE_ACTION_OFFSET) {
666                                         data->offset[0] = data->soff[0] + dx;
667                                         data->offset[1] = data->soff[1] + dy;
668                                 }
669                                 else {
670                                         data->pos[0] = data->spos[0] + dx;
671                                         data->pos[1] = data->spos[1] + dy;
672                                 }
673
674                                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
675                                 DAG_id_tag_update(&sc->clip->id, 0);
676                         }
677                         else {
678                                 if (data->action == SLIDE_ACTION_SIZE) {
679                                         if (data->corners) {
680                                                 data->corners[0][0] = data->scorners[0][0] - dx;
681                                                 data->corners[0][1] = data->scorners[0][1] + dy;
682
683                                                 data->corners[1][0] = data->scorners[1][0] + dx;
684                                                 data->corners[1][1] = data->scorners[1][1] + dy;
685
686                                                 data->corners[2][0] = data->scorners[2][0] + dx;
687                                                 data->corners[2][1] = data->scorners[2][1] - dy;
688
689                                                 data->corners[3][0] = data->scorners[3][0] - dx;
690                                                 data->corners[3][1] = data->scorners[3][1] - dy;
691                                         }
692                                         else {
693                                                 data->min[0] = data->smin[0] - dx;
694                                                 data->max[0] = data->smax[0] + dx;
695
696                                                 data->min[1] = data->smin[1] + dy;
697                                                 data->max[1] = data->smax[1] - dy;
698                                         }
699
700                                         if (data->area == TRACK_AREA_SEARCH)
701                                                 BKE_tracking_clamp_track(data->track, CLAMP_SEARCH_DIM);
702                                         else
703                                                 BKE_tracking_clamp_track(data->track, CLAMP_PAT_DIM);
704                                 }
705                                 else if (data->action == SLIDE_ACTION_OFFSET) {
706                                         float d[2] = {dx, dy};
707
708                                         if (data->area == TRACK_AREA_SEARCH) {
709                                                 add_v2_v2v2(data->min, data->smin, d);
710                                                 add_v2_v2v2(data->max, data->smax, d);
711                                         }
712                                         else {
713                                                 int a;
714
715                                                 for (a = 0; a < data->track->markersnr; a++)
716                                                         add_v2_v2v2(data->track->markers[a].pos, data->smarkers[a], d);
717
718                                                 sub_v2_v2v2(data->offset, data->soff, d);
719                                         }
720
721                                         if (data->area == TRACK_AREA_SEARCH)
722                                                 BKE_tracking_clamp_track(data->track, CLAMP_SEARCH_POS);
723                                 }
724                                 else if (data->action == SLIDE_ACTION_POS) {
725                                         if (data->scale) {
726                                                 float scale = 1.0f + 10.0f * (dx - dy);
727
728                                                 if (scale > 0.0f) {
729                                                         int a;
730
731                                                         for (a = 0; a < 4; a++) {
732                                                                 mul_v2_v2fl(data->corners[a], data->scorners[a], scale);
733                                                         }
734                                                 }
735                                         }
736                                         else {
737                                                 float spos[2];
738
739                                                 copy_v2_v2(spos, data->pos);
740
741                                                 /* corners might've been scaled before, restore their original position */
742                                                 memcpy(data->corners, data->scorners, sizeof(data->scorners));
743
744                                                 data->pos[0] = data->spos[0] + dx;
745                                                 data->pos[1] = data->spos[1] + dy;
746
747                                                 if (!slide_check_corners(data->corners)) {
748                                                         copy_v2_v2(data->pos, spos);
749                                                 }
750                                         }
751
752                                         /* currently only patterns are allowed to have such combination of event and data */
753                                         BKE_tracking_clamp_track(data->track, CLAMP_PAT_DIM);
754                                 }
755                         }
756
757                         data->marker->flag &= ~MARKER_TRACKED;
758
759                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
760
761                         break;
762
763                 case LEFTMOUSE:
764                         if (event->val == KM_RELEASE) {
765                                 free_slide_data(op->customdata);
766
767                                 show_cursor(C);
768
769                                 return OPERATOR_FINISHED;
770                         }
771
772                         break;
773
774                 case ESCKEY:
775                         cancel_mouse_slide(op->customdata);
776
777                         free_slide_data(op->customdata);
778
779                         show_cursor(C);
780
781                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
782
783                         return OPERATOR_CANCELLED;
784         }
785
786         return OPERATOR_RUNNING_MODAL;
787 }
788
789 void CLIP_OT_slide_marker(wmOperatorType *ot)
790 {
791         /* identifiers */
792         ot->name = "Slide Marker";
793         ot->description = "Slide marker areas";
794         ot->idname = "CLIP_OT_slide_marker";
795
796         /* api callbacks */
797         ot->poll = ED_space_clip_tracking_size_poll;
798         ot->invoke = slide_marker_invoke;
799         ot->modal = slide_marker_modal;
800
801         /* flags */
802         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_GRAB_POINTER | OPTYPE_BLOCKING;
803
804         /* properties */
805         RNA_def_float_vector(ot->srna, "offset", 2, NULL, -FLT_MAX, FLT_MAX,
806                 "Offset", "Offset in floating point units, 1.0 is the width and height of the image", -FLT_MAX, FLT_MAX);
807 }
808
809 /********************** mouse select operator *********************/
810
811 static int mouse_on_side(float co[2], float x1, float y1, float x2, float y2, float epsx, float epsy)
812 {
813         if (x1 > x2)
814
815                 SWAP(float, x1, x2);
816
817         if (y1 > y2)
818                 SWAP(float, y1, y2);
819
820         return (co[0] >= x1 - epsx && co[0] <= x2 + epsx) && (co[1] >= y1 - epsy && co[1] <= y2 + epsy);
821 }
822
823 static int mouse_on_rect(float co[2], float pos[2], float min[2], float max[2], float epsx, float epsy)
824 {
825         return mouse_on_side(co, pos[0] + min[0], pos[1] + min[1], pos[0] + max[0], pos[1] + min[1], epsx, epsy) ||
826                mouse_on_side(co, pos[0] + min[0], pos[1] + min[1], pos[0] + min[0], pos[1] + max[1], epsx, epsy) ||
827                mouse_on_side(co, pos[0] + min[0], pos[1] + max[1], pos[0] + max[0], pos[1] + max[1], epsx, epsy) ||
828                mouse_on_side(co, pos[0] + max[0], pos[1] + min[1], pos[0] + max[0], pos[1] + max[1], epsx, epsy);
829 }
830
831 static int mouse_on_crns(float co[2], float pos[2], float crns[4][2], float epsx, float epsy)
832 {
833         float dist = dist_to_crns(co, pos, crns);
834
835         return dist < MAX2(epsx, epsy);
836 }
837
838 static int track_mouse_area(SpaceClip *sc, float co[2], MovieTrackingTrack *track)
839 {
840         MovieTrackingMarker *marker = BKE_tracking_get_marker(track, sc->user.framenr);
841         float pat_min[2], pat_max[2];
842         float epsx, epsy;
843         int width, height;
844
845         ED_space_clip_size(sc, &width, &height);
846
847         BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max);
848
849         epsx = MIN4(pat_min[0] - track->search_min[0], track->search_max[0] - pat_max[0],
850                     fabsf(pat_min[0]), fabsf(pat_max[0])) / 2;
851         epsy = MIN4(pat_min[1] - track->search_min[1], track->search_max[1] - pat_max[1],
852                     fabsf(pat_min[1]), fabsf(pat_max[1])) / 2;
853
854         epsx = MAX2(epsx, 2.0f / width);
855         epsy = MAX2(epsy, 2.0f / height);
856
857         if (sc->flag & SC_SHOW_MARKER_SEARCH) {
858                 if (mouse_on_rect(co, marker->pos, track->search_min, track->search_max, epsx, epsy))
859                         return TRACK_AREA_SEARCH;
860         }
861
862         if ((marker->flag & MARKER_DISABLED) == 0) {
863                 if (sc->flag & SC_SHOW_MARKER_PATTERN)
864                         if (mouse_on_crns(co, marker->pos, marker->pattern_corners, epsx, epsy))
865                                 return TRACK_AREA_PAT;
866
867                 epsx = 12.0f / width;
868                 epsy = 12.0f / height;
869
870                 if (fabsf(co[0] - marker->pos[0] - track->offset[0]) < epsx &&
871                     fabsf(co[1] - marker->pos[1] - track->offset[1]) <= epsy)
872                 {
873                         return TRACK_AREA_POINT;
874                 }
875         }
876
877         return TRACK_AREA_NONE;
878 }
879
880 static float dist_to_rect(float co[2], float pos[2], float min[2], float max[2])
881 {
882         float d1, d2, d3, d4;
883         float p[2] = {co[0] - pos[0], co[1] - pos[1]};
884         float v1[2] = {min[0], min[1]}, v2[2] = {max[0], min[1]},
885               v3[2] = {max[0], max[1]}, v4[2] = {min[0], max[1]};
886
887         d1 = dist_to_line_segment_v2(p, v1, v2);
888         d2 = dist_to_line_segment_v2(p, v2, v3);
889         d3 = dist_to_line_segment_v2(p, v3, v4);
890         d4 = dist_to_line_segment_v2(p, v4, v1);
891
892         return MIN4(d1, d2, d3, d4);
893 }
894
895 static float dist_to_crns(float co[2], float pos[2], float crns[4][2])
896 {
897         float d1, d2, d3, d4;
898         float p[2] = {co[0] - pos[0], co[1] - pos[1]};
899         float *v1 = crns[0], *v2 = crns[1],
900               *v3 = crns[2], *v4 = crns[3];
901
902         d1 = dist_to_line_segment_v2(p, v1, v2);
903         d2 = dist_to_line_segment_v2(p, v2, v3);
904         d3 = dist_to_line_segment_v2(p, v3, v4);
905         d4 = dist_to_line_segment_v2(p, v4, v1);
906
907         return MIN4(d1, d2, d3, d4);
908 }
909
910 static MovieTrackingTrack *find_nearest_track(SpaceClip *sc, ListBase *tracksbase, float co[2])
911 {
912         MovieTrackingTrack *track = NULL, *cur;
913         float mindist = 0.0f;
914
915         cur = tracksbase->first;
916         while (cur) {
917                 MovieTrackingMarker *marker = BKE_tracking_get_marker(cur, sc->user.framenr);
918
919                 if (((cur->flag & TRACK_HIDDEN) == 0) && MARKER_VISIBLE(sc, cur, marker)) {
920                         float dist, d1, d2 = FLT_MAX, d3 = FLT_MAX;
921
922                         /* distance to marker point */
923                         d1 = sqrtf((co[0] - marker->pos[0] - cur->offset[0]) * (co[0] - marker->pos[0] - cur->offset[0]) +
924                                            (co[1] - marker->pos[1] - cur->offset[1]) * (co[1] - marker->pos[1] - cur->offset[1]));
925
926                         /* distance to pattern boundbox */
927                         if (sc->flag & SC_SHOW_MARKER_PATTERN)
928                                 d2 = dist_to_crns(co, marker->pos, marker->pattern_corners);
929
930                         /* distance to search boundbox */
931                         if (sc->flag & SC_SHOW_MARKER_SEARCH && TRACK_VIEW_SELECTED(sc, cur))
932                                 d3 = dist_to_rect(co, marker->pos, cur->search_min, cur->search_max);
933
934                         /* choose minimal distance. useful for cases of overlapped markers. */
935                         dist = MIN3(d1, d2, d3);
936
937                         if (track == NULL || dist < mindist) {
938                                 track = cur;
939                                 mindist = dist;
940                         }
941                 }
942
943                 cur = cur->next;
944         }
945
946         return track;
947 }
948
949 static int mouse_select(bContext *C, float co[2], int extend)
950 {
951         SpaceClip *sc = CTX_wm_space_clip(C);
952         MovieClip *clip = ED_space_clip(sc);
953         MovieTracking *tracking = &clip->tracking;
954         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
955         MovieTrackingTrack *act_track = BKE_tracking_active_track(tracking);
956         MovieTrackingTrack *track = NULL;       /* selected marker */
957
958         track = find_nearest_track(sc, tracksbase, co);
959
960         if (track) {
961                 int area = track_mouse_area(sc, co, track);
962
963                 if (!extend || !TRACK_VIEW_SELECTED(sc, track))
964                         area = TRACK_AREA_ALL;
965
966                 if (extend && TRACK_AREA_SELECTED(track, area)) {
967                         if (track == act_track)
968                                 BKE_tracking_deselect_track(track, area);
969                         else
970                                 clip->tracking.act_track = track;
971                 }
972                 else {
973                         if (area == TRACK_AREA_POINT)
974                                 area = TRACK_AREA_ALL;
975
976                         BKE_tracking_select_track(tracksbase, track, area, extend);
977                         clip->tracking.act_track = track;
978                 }
979         }
980
981         if (!extend) {
982                 sc->xlockof = 0.0f;
983                 sc->ylockof = 0.0f;
984         }
985
986         BKE_tracking_dopesheet_tag_update(tracking);
987
988         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
989
990         return OPERATOR_FINISHED;
991 }
992
993 static int select_exec(bContext *C, wmOperator *op)
994 {
995         float co[2];
996         int extend;
997
998         RNA_float_get_array(op->ptr, "location", co);
999         extend = RNA_boolean_get(op->ptr, "extend");
1000
1001         return mouse_select(C, co, extend);
1002 }
1003
1004 static int select_invoke(bContext *C, wmOperator *op, wmEvent *event)
1005 {
1006         float co[2];
1007         int extend = RNA_boolean_get(op->ptr, "extend");
1008
1009         if (!extend) {
1010                 SlideMarkerData *slidedata = slide_marker_customdata(C, event);
1011
1012                 if (slidedata) {
1013                         SpaceClip *sc = CTX_wm_space_clip(C);
1014                         MovieClip *clip = ED_space_clip(sc);
1015
1016                         clip->tracking.act_track = slidedata->track;
1017
1018                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
1019
1020                         MEM_freeN(slidedata);
1021
1022                         return OPERATOR_PASS_THROUGH;
1023                 }
1024         }
1025
1026         ED_clip_mouse_pos(C, event, co);
1027         RNA_float_set_array(op->ptr, "location", co);
1028
1029         return select_exec(C, op);
1030 }
1031
1032 void CLIP_OT_select(wmOperatorType *ot)
1033 {
1034         /* identifiers */
1035         ot->name = "Select";
1036         ot->description = "Select tracking markers";
1037         ot->idname = "CLIP_OT_select";
1038
1039         /* api callbacks */
1040         ot->exec = select_exec;
1041         ot->invoke = select_invoke;
1042         ot->poll = ED_space_clip_tracking_poll;
1043
1044         /* flags */
1045         ot->flag = OPTYPE_UNDO;
1046
1047         /* properties */
1048         RNA_def_boolean(ot->srna, "extend", 0,
1049                 "Extend", "Extend selection rather than clearing the existing selection");
1050         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
1051                 "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
1052 }
1053
1054 /********************** border select operator *********************/
1055
1056 static int border_select_exec(bContext *C, wmOperator *op)
1057 {
1058         SpaceClip *sc = CTX_wm_space_clip(C);
1059         MovieClip *clip = ED_space_clip(sc);
1060         MovieTracking *tracking = &clip->tracking;
1061         MovieTrackingTrack *track;
1062         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
1063         rcti rect;
1064         rctf rectf;
1065         int change = FALSE, mode, extend;
1066
1067         /* get rectangle from operator */
1068         rect.xmin = RNA_int_get(op->ptr, "xmin");
1069         rect.ymin = RNA_int_get(op->ptr, "ymin");
1070         rect.xmax = RNA_int_get(op->ptr, "xmax");
1071         rect.ymax = RNA_int_get(op->ptr, "ymax");
1072
1073         ED_clip_point_stable_pos(C, rect.xmin, rect.ymin, &rectf.xmin, &rectf.ymin);
1074         ED_clip_point_stable_pos(C, rect.xmax, rect.ymax, &rectf.xmax, &rectf.ymax);
1075
1076         mode = RNA_int_get(op->ptr, "gesture_mode");
1077         extend = RNA_boolean_get(op->ptr, "extend");
1078
1079         /* do actual selection */
1080         track = tracksbase->first;
1081         while (track) {
1082                 if ((track->flag & TRACK_HIDDEN) == 0) {
1083                         MovieTrackingMarker *marker = BKE_tracking_get_marker(track, sc->user.framenr);
1084
1085                         if (MARKER_VISIBLE(sc, track, marker)) {
1086                                 if (BLI_in_rctf(&rectf, marker->pos[0], marker->pos[1])) {
1087                                         BKE_tracking_track_flag(track, TRACK_AREA_ALL, SELECT, mode != GESTURE_MODAL_SELECT);
1088                                 }
1089                                 else if (!extend) {
1090                                         BKE_tracking_track_flag(track, TRACK_AREA_ALL, SELECT, 1);
1091                                 }
1092
1093                                 change = TRUE;
1094                         }
1095                 }
1096
1097                 track = track->next;
1098         }
1099
1100         if (change) {
1101                 BKE_tracking_dopesheet_tag_update(tracking);
1102
1103                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
1104
1105                 return OPERATOR_FINISHED;
1106         }
1107
1108         return OPERATOR_CANCELLED;
1109 }
1110
1111 void CLIP_OT_select_border(wmOperatorType *ot)
1112 {
1113         /* identifiers */
1114         ot->name = "Border Select";
1115         ot->description = "Select markers using border selection";
1116         ot->idname = "CLIP_OT_select_border";
1117
1118         /* api callbacks */
1119         ot->invoke = WM_border_select_invoke;
1120         ot->exec = border_select_exec;
1121         ot->modal = WM_border_select_modal;
1122         ot->poll = ED_space_clip_tracking_poll;
1123
1124         /* flags */
1125         ot->flag = OPTYPE_UNDO;
1126
1127         /* properties */
1128         WM_operator_properties_gesture_border(ot, TRUE);
1129 }
1130
1131
1132 static int do_lasso_select_marker(bContext *C, int mcords[][2], short moves, short select)
1133 {
1134         ARegion *ar = CTX_wm_region(C);
1135         SpaceClip *sc = CTX_wm_space_clip(C);
1136         MovieClip *clip = ED_space_clip(sc);
1137         MovieTracking *tracking = &clip->tracking;
1138         MovieTrackingTrack *track;
1139         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
1140         rcti rect;
1141         int change = FALSE;
1142
1143         /* get rectangle from operator */
1144         BLI_lasso_boundbox(&rect, mcords, moves);
1145
1146         /* do actual selection */
1147         track = tracksbase->first;
1148         while (track) {
1149                 if ((track->flag & TRACK_HIDDEN) == 0) {
1150                         MovieTrackingMarker *marker = BKE_tracking_get_marker(track, sc->user.framenr);
1151
1152                         if (MARKER_VISIBLE(sc, track, marker)) {
1153                                 float screen_co[2];
1154
1155                                 /* marker in screen coords */
1156                                 ED_clip_point_stable_pos__reverse(sc, ar, marker->pos, screen_co);
1157
1158                                 if (BLI_in_rcti(&rect, screen_co[0], screen_co[1]) &&
1159                                     BLI_lasso_is_point_inside(mcords, moves, screen_co[0], screen_co[1], V2D_IS_CLIPPED))
1160                                 {
1161                                         BKE_tracking_track_flag(track, TRACK_AREA_ALL, SELECT, !select);
1162                                 }
1163
1164                                 change = TRUE;
1165                         }
1166                 }
1167
1168                 track = track->next;
1169         }
1170
1171         if (change) {
1172                 BKE_tracking_dopesheet_tag_update(tracking);
1173
1174                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
1175         }
1176
1177         return change;
1178 }
1179
1180 static int clip_lasso_select_exec(bContext *C, wmOperator *op)
1181 {
1182         int mcords_tot;
1183         int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
1184
1185         if (mcords) {
1186                 short select;
1187
1188                 select = !RNA_boolean_get(op->ptr, "deselect");
1189                 do_lasso_select_marker(C, mcords, mcords_tot, select);
1190
1191                 MEM_freeN(mcords);
1192
1193                 return OPERATOR_FINISHED;
1194         }
1195         return OPERATOR_PASS_THROUGH;
1196 }
1197
1198 void CLIP_OT_select_lasso(wmOperatorType *ot)
1199 {
1200         /* identifiers */
1201         ot->name = "Lasso Select";
1202         ot->description = "Select markers using lasso selection";
1203         ot->idname = "CLIP_OT_select_lasso";
1204
1205         /* api callbacks */
1206         ot->invoke = WM_gesture_lasso_invoke;
1207         ot->modal = WM_gesture_lasso_modal;
1208         ot->exec = clip_lasso_select_exec;
1209         ot->poll = ED_space_clip_tracking_poll;
1210         ot->cancel = WM_gesture_lasso_cancel;
1211
1212         /* flags */
1213         ot->flag = OPTYPE_UNDO;
1214
1215         /* properties */
1216         RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
1217         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
1218         RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
1219 }
1220
1221 /********************** circle select operator *********************/
1222
1223 static int marker_inside_ellipse(MovieTrackingMarker *marker, float offset[2], float ellipse[2])
1224 {
1225         /* normalized ellipse: ell[0] = scaleX, ell[1] = scaleY */
1226         float x, y;
1227
1228         x = (marker->pos[0] - offset[0])*ellipse[0];
1229         y = (marker->pos[1] - offset[1])*ellipse[1];
1230
1231         return x*x + y*y < 1.0f;
1232 }
1233
1234 static int circle_select_exec(bContext *C, wmOperator *op)
1235 {
1236         SpaceClip *sc = CTX_wm_space_clip(C);
1237         MovieClip *clip = ED_space_clip(sc);
1238         ARegion *ar = CTX_wm_region(C);
1239         MovieTracking *tracking = &clip->tracking;
1240         MovieTrackingTrack *track;
1241         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
1242         int x, y, radius, width, height, mode, change = FALSE;
1243         float zoomx, zoomy, offset[2], ellipse[2];
1244
1245         /* get operator properties */
1246         x = RNA_int_get(op->ptr, "x");
1247         y = RNA_int_get(op->ptr, "y");
1248         radius = RNA_int_get(op->ptr, "radius");
1249
1250         mode = RNA_int_get(op->ptr, "gesture_mode");
1251
1252         /* compute ellipse and position in unified coordinates */
1253         ED_space_clip_size(sc, &width, &height);
1254         ED_space_clip_zoom(sc, ar, &zoomx, &zoomy);
1255
1256         ellipse[0] = width * zoomx / radius;
1257         ellipse[1] = height * zoomy / radius;
1258
1259         ED_clip_point_stable_pos(C, x, y, &offset[0], &offset[1]);
1260
1261         /* do selection */
1262         track = tracksbase->first;
1263         while (track) {
1264                 if ((track->flag & TRACK_HIDDEN) == 0) {
1265                         MovieTrackingMarker *marker = BKE_tracking_get_marker(track, sc->user.framenr);
1266
1267                         if (MARKER_VISIBLE(sc, track, marker) && marker_inside_ellipse(marker, offset, ellipse)) {
1268                                 BKE_tracking_track_flag(track, TRACK_AREA_ALL, SELECT, mode != GESTURE_MODAL_SELECT);
1269
1270                                 change = TRUE;
1271                         }
1272                 }
1273
1274                 track = track->next;
1275         }
1276
1277         if (change) {
1278                 BKE_tracking_dopesheet_tag_update(tracking);
1279
1280                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
1281
1282                 return OPERATOR_FINISHED;
1283         }
1284
1285         return OPERATOR_CANCELLED;
1286 }
1287
1288 void CLIP_OT_select_circle(wmOperatorType *ot)
1289 {
1290         /* identifiers */
1291         ot->name = "Circle Select";
1292         ot->description = "Select markers using circle selection";
1293         ot->idname = "CLIP_OT_select_circle";
1294
1295         /* api callbacks */
1296         ot->invoke = WM_gesture_circle_invoke;
1297         ot->modal = WM_gesture_circle_modal;
1298         ot->exec = circle_select_exec;
1299         ot->poll = ED_space_clip_tracking_poll;
1300
1301         /* flags */
1302         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1303
1304         /* properties */
1305         RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
1306         RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
1307         RNA_def_int(ot->srna, "radius", 0, INT_MIN, INT_MAX, "Radius", "", INT_MIN, INT_MAX);
1308         RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
1309 }
1310
1311 /********************** select all operator *********************/
1312
1313 static int select_all_exec(bContext *C, wmOperator *op)
1314 {
1315         SpaceClip *sc = CTX_wm_space_clip(C);
1316         MovieClip *clip = ED_space_clip(sc);
1317         MovieTracking *tracking = &clip->tracking;
1318         MovieTrackingTrack *track = NULL;       /* selected track */
1319         MovieTrackingMarker *marker;
1320         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
1321         int action = RNA_enum_get(op->ptr, "action");
1322         int framenr = sc->user.framenr;
1323         int has_selection = FALSE;
1324
1325         if (action == SEL_TOGGLE) {
1326                 action = SEL_SELECT;
1327                 track = tracksbase->first;
1328                 while (track) {
1329                         if (TRACK_VIEW_SELECTED(sc, track)) {
1330                                 marker = BKE_tracking_get_marker(track, framenr);
1331
1332                                 if (MARKER_VISIBLE(sc, track, marker)) {
1333                                         action = SEL_DESELECT;
1334                                         break;
1335                                 }
1336                         }
1337
1338                         track = track->next;
1339                 }
1340         }
1341
1342         track = tracksbase->first;
1343         while (track) {
1344                 if ((track->flag & TRACK_HIDDEN) == 0) {
1345                         marker = BKE_tracking_get_marker(track, framenr);
1346
1347                         if (MARKER_VISIBLE(sc, track, marker)) {
1348                                 switch (action) {
1349                                         case SEL_SELECT:
1350                                                 track->flag |= SELECT;
1351                                                 track->pat_flag |= SELECT;
1352                                                 track->search_flag |= SELECT;
1353                                                 break;
1354                                         case SEL_DESELECT:
1355                                                 track->flag &= ~SELECT;
1356                                                 track->pat_flag &= ~SELECT;
1357                                                 track->search_flag &= ~SELECT;
1358                                                 break;
1359                                         case SEL_INVERT:
1360                                                 track->flag ^= SELECT;
1361                                                 track->pat_flag ^= SELECT;
1362                                                 track->search_flag ^= SELECT;
1363                                                 break;
1364                                 }
1365                         }
1366                 }
1367
1368                 if (TRACK_VIEW_SELECTED(sc, track))
1369                         has_selection = TRUE;
1370
1371                 track = track->next;
1372         }
1373
1374         if (!has_selection)
1375                 sc->flag &= ~SC_LOCK_SELECTION;
1376
1377         BKE_tracking_dopesheet_tag_update(tracking);
1378
1379         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
1380
1381         return OPERATOR_FINISHED;
1382 }
1383
1384 void CLIP_OT_select_all(wmOperatorType *ot)
1385 {
1386         /* identifiers */
1387         ot->name = "(De)select All";
1388         ot->description = "Change selection of all tracking markers";
1389         ot->idname = "CLIP_OT_select_all";
1390
1391         /* api callbacks */
1392         ot->exec = select_all_exec;
1393         ot->poll = ED_space_clip_tracking_poll;
1394
1395         /* flags */
1396         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1397
1398         WM_operator_properties_select_all(ot);
1399 }
1400
1401 /********************** select grouped operator *********************/
1402
1403 static int select_groped_exec(bContext *C, wmOperator *op)
1404 {
1405         SpaceClip *sc = CTX_wm_space_clip(C);
1406         MovieClip *clip = ED_space_clip(sc);
1407         MovieTrackingTrack *track;
1408         MovieTrackingMarker *marker;
1409         MovieTracking *tracking = &clip->tracking;
1410         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
1411         int group = RNA_enum_get(op->ptr, "group");
1412
1413         track = tracksbase->first;
1414         while (track) {
1415                 int ok = FALSE;
1416
1417                 marker = BKE_tracking_get_marker(track, sc->user.framenr);
1418
1419                 if (group == 0) { /* Keyframed */
1420                         ok = marker->framenr == sc->user.framenr && (marker->flag & MARKER_TRACKED) == 0;
1421                 }
1422                 else if (group == 1) { /* Estimated */
1423                         ok = marker->framenr != sc->user.framenr;
1424                 }
1425                 else if (group == 2) { /* tracked */
1426                         ok = marker->framenr == sc->user.framenr && (marker->flag & MARKER_TRACKED);
1427                 }
1428                 else if (group == 3) { /* locked */
1429                         ok = track->flag & TRACK_LOCKED;
1430                 }
1431                 else if (group == 4) { /* disabled */
1432                         ok = marker->flag & MARKER_DISABLED;
1433                 }
1434                 else if (group == 5) { /* color */
1435                         MovieTrackingTrack *act_track = BKE_tracking_active_track(tracking);
1436
1437                         if (act_track) {
1438                                 ok = (track->flag & TRACK_CUSTOMCOLOR) == (act_track->flag & TRACK_CUSTOMCOLOR);
1439
1440                                 if (ok && track->flag & TRACK_CUSTOMCOLOR)
1441                                         ok = equals_v3v3(track->color, act_track->color);
1442                         }
1443                 }
1444                 else if (group == 6) { /* failed */
1445                         ok = (track->flag & TRACK_HAS_BUNDLE) == 0;
1446                 }
1447
1448                 if (ok) {
1449                         track->flag |= SELECT;
1450                         if (sc->flag & SC_SHOW_MARKER_PATTERN)
1451                                 track->pat_flag |= SELECT;
1452                         if (sc->flag & SC_SHOW_MARKER_SEARCH)
1453                                 track->search_flag |= SELECT;
1454                 }
1455
1456                 track = track->next;
1457         }
1458
1459         BKE_tracking_dopesheet_tag_update(tracking);
1460
1461         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
1462
1463         return OPERATOR_FINISHED;
1464 }
1465
1466 void CLIP_OT_select_grouped(wmOperatorType *ot)
1467 {
1468         static EnumPropertyItem select_group_items[] = {
1469                         {0, "KEYFRAMED", 0, "Keyframed tracks", "Select all keyframed tracks"},
1470                         {1, "ESTIMATED", 0, "Estimated tracks", "Select all estimated tracks"},
1471                         {2, "TRACKED", 0, "Tracked tracks", "Select all tracked tracks"},
1472                         {3, "LOCKED", 0, "Locked tracks", "Select all locked tracks"},
1473                         {4, "DISABLED", 0, "Disabled tracks", "Select all disabled tracks"},
1474                         {5, "COLOR", 0, "Tracks with same color", "Select all tracks with same color as active track"},
1475                         {6, "FAILED", 0, "Failed Tracks", "Select all tracks which failed to be reconstructed"},
1476                         {0, NULL, 0, NULL, NULL}
1477         };
1478
1479         /* identifiers */
1480         ot->name = "Select Grouped";
1481         ot->description = "Select all tracks from specified group";
1482         ot->idname = "CLIP_OT_select_grouped";
1483
1484         /* api callbacks */
1485         ot->exec = select_groped_exec;
1486         ot->poll = ED_space_clip_tracking_size_poll;
1487
1488         /* flags */
1489         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1490
1491         /* proeprties */
1492         RNA_def_enum(ot->srna, "group", select_group_items, TRACK_CLEAR_REMAINED, "Action", "Clear action to execute");
1493 }
1494
1495 /********************** track operator *********************/
1496
1497 typedef struct TrackMarkersJob {
1498         struct MovieTrackingContext *context;   /* tracking context */
1499         int sfra, efra, lastfra;        /* Start, end and recently tracked frames */
1500         int backwards;                          /* Backwards tracking flag */
1501         MovieClip *clip;                        /* Clip which is tracking */
1502         float delay;                            /* Delay in milliseconds to allow tracking at fixed FPS */
1503
1504         struct Main *main;
1505         struct Scene *scene;
1506         struct bScreen *screen;
1507 } TrackMarkersJob;
1508
1509 static int track_markers_testbreak(void)
1510 {
1511         return G.afbreek;
1512 }
1513
1514 static int track_count_markers(SpaceClip *sc, MovieClip *clip)
1515 {
1516         int tot = 0;
1517         ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
1518         MovieTrackingTrack *track;
1519         int framenr = sc->user.framenr;
1520
1521         track = tracksbase->first;
1522         while (track) {
1523                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
1524                         MovieTrackingMarker *marker = BKE_tracking_get_marker(track, framenr);
1525
1526                         if (!marker || (marker->flag & MARKER_DISABLED) == 0)
1527                                 tot++;
1528                 }
1529
1530                 track = track->next;
1531         }
1532
1533         return tot;
1534 }
1535
1536 static void clear_invisible_track_selection(SpaceClip *sc, MovieClip *clip)
1537 {
1538         ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
1539         int hidden = 0;
1540
1541         if ((sc->flag & SC_SHOW_MARKER_PATTERN) == 0)
1542                 hidden |= TRACK_AREA_PAT;
1543
1544         if ((sc->flag & SC_SHOW_MARKER_SEARCH) == 0)
1545                 hidden |= TRACK_AREA_SEARCH;
1546
1547         if (hidden) {
1548                 MovieTrackingTrack *track = tracksbase->first;
1549
1550                 while (track) {
1551                         if ((track->flag & TRACK_HIDDEN) == 0)
1552                                 BKE_tracking_track_flag(track, hidden, SELECT, 1);
1553
1554                         track = track->next;
1555                 }
1556         }
1557 }
1558
1559 static void track_init_markers(SpaceClip *sc, MovieClip *clip, int *frames_limit_r)
1560 {
1561         ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
1562         MovieTrackingTrack *track;
1563         int framenr = sc->user.framenr;
1564         int frames_limit = 0;
1565
1566         clear_invisible_track_selection(sc, clip);
1567
1568         track = tracksbase->first;
1569         while (track) {
1570                 if (TRACK_VIEW_SELECTED(sc, track)) {
1571                         if ((track->flag & TRACK_HIDDEN) == 0 && (track->flag & TRACK_LOCKED) == 0) {
1572                                 BKE_tracking_ensure_marker(track, framenr);
1573
1574                                 if (track->frames_limit) {
1575                                         if (frames_limit == 0)
1576                                                 frames_limit = track->frames_limit;
1577                                         else
1578                                                 frames_limit = MIN2(frames_limit, track->frames_limit);
1579                                 }
1580                         }
1581                 }
1582
1583                 track = track->next;
1584         }
1585
1586         *frames_limit_r = frames_limit;
1587 }
1588
1589 static int track_markers_check_direction(int backwards, int curfra, int efra)
1590 {
1591         if (backwards) {
1592                 if (curfra < efra)
1593                         return FALSE;
1594         }
1595         else {
1596                 if (curfra > efra)
1597                         return FALSE;
1598         }
1599
1600         return TRUE;
1601 }
1602
1603 static int track_markers_initjob(bContext *C, TrackMarkersJob *tmj, int backwards)
1604 {
1605         SpaceClip *sc = CTX_wm_space_clip(C);
1606         MovieClip *clip = ED_space_clip(sc);
1607         Scene *scene = CTX_data_scene(C);
1608         MovieTrackingSettings *settings = &clip->tracking.settings;
1609         int frames_limit;
1610
1611         track_init_markers(sc, clip, &frames_limit);
1612
1613         tmj->sfra = sc->user.framenr;
1614         tmj->clip = clip;
1615         tmj->backwards = backwards;
1616
1617         if (backwards)
1618                 tmj->efra = SFRA;
1619         else
1620                 tmj->efra = EFRA;
1621
1622         /* limit frames to be tracked by user setting */
1623         if (frames_limit) {
1624                 if (backwards)
1625                         tmj->efra = MAX2(tmj->efra, tmj->sfra - frames_limit);
1626                 else
1627                         tmj->efra = MIN2(tmj->efra, tmj->sfra + frames_limit);
1628         }
1629
1630         if (settings->speed != TRACKING_SPEED_FASTEST) {
1631                 tmj->delay = 1.0f / scene->r.frs_sec * 1000.0f;
1632
1633                 if (settings->speed == TRACKING_SPEED_HALF)
1634                         tmj->delay *= 2;
1635                 else if (settings->speed == TRACKING_SPEED_QUARTER)
1636                         tmj->delay *= 4;
1637                 else if (settings->speed == TRACKING_SPEED_DOUBLE)
1638                         tmj->delay /= 2;
1639         }
1640
1641         tmj->context = BKE_tracking_context_new(clip, &sc->user, backwards, 1);
1642
1643         clip->tracking_context = tmj->context;
1644
1645         tmj->lastfra = tmj->sfra;
1646
1647         /* XXX: silly to store this, but this data is needed to update scene and movie-clip
1648          *      frame numbers when tracking is finished. This introduces better feedback for artists.
1649          *      Maybe there's another way to solve this problem, but can't think better way atm.
1650          *      Anyway, this way isn't more unstable as animation rendering animation
1651          *      which uses the same approach (except storing screen). */
1652         tmj->scene = scene;
1653         tmj->main = CTX_data_main(C);
1654         tmj->screen = CTX_wm_screen(C);
1655
1656         return track_markers_check_direction(backwards, tmj->sfra, tmj->efra);
1657 }
1658
1659 static void track_markers_startjob(void *tmv, short *stop, short *do_update, float *progress)
1660 {
1661         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1662         int framenr = tmj->sfra;
1663         //double t = PIL_check_seconds_timer();
1664
1665         while (framenr != tmj->efra) {
1666                 if (tmj->delay > 0) {
1667                         /* tracking should happen with fixed fps. Calculate time
1668                          * using current timer value before tracking frame and after.
1669                          *
1670                          * Small (and maybe unneeded optimization): do not calculate exec_time
1671                          * for "Fastest" tracking */
1672
1673                         double start_time = PIL_check_seconds_timer(), exec_time;
1674
1675                         if (!BKE_tracking_next(tmj->context))
1676                                 break;
1677
1678                         exec_time = PIL_check_seconds_timer() - start_time;
1679                         if (tmj->delay > (float)exec_time)
1680                                 PIL_sleep_ms(tmj->delay - (float)exec_time);
1681                 }
1682                 else if (!BKE_tracking_next(tmj->context))
1683                                 break;
1684
1685                 *do_update = TRUE;
1686                 *progress = (float)(framenr - tmj->sfra) / (tmj->efra - tmj->sfra);
1687
1688                 if (tmj->backwards)
1689                         framenr--;
1690                 else
1691                         framenr++;
1692
1693                 tmj->lastfra = framenr;
1694
1695                 if (*stop || track_markers_testbreak())
1696                         break;
1697         }
1698
1699         //printf("Tracking time: %lf\n", PIL_check_seconds_timer()-t);
1700 }
1701
1702 static void track_markers_updatejob(void *tmv)
1703 {
1704         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1705
1706         BKE_tracking_sync(tmj->context);
1707 }
1708
1709 static void track_markers_freejob(void *tmv)
1710 {
1711         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1712
1713         tmj->clip->tracking_context = NULL;
1714         tmj->scene->r.cfra = tmj->lastfra;
1715         ED_update_for_newframe(tmj->main, tmj->scene, tmj->screen, 0);
1716
1717         BKE_tracking_sync(tmj->context);
1718         BKE_tracking_context_free(tmj->context);
1719
1720         MEM_freeN(tmj);
1721
1722         WM_main_add_notifier(NC_SCENE | ND_FRAME, tmj->scene);
1723 }
1724
1725 static int track_markers_exec(bContext *C, wmOperator *op)
1726 {
1727         SpaceClip *sc = CTX_wm_space_clip(C);
1728         MovieClip *clip = ED_space_clip(sc);
1729         Scene *scene = CTX_data_scene(C);
1730         struct MovieTrackingContext *context;
1731         int framenr = sc->user.framenr;
1732         int sfra = framenr, efra;
1733         int backwards = RNA_boolean_get(op->ptr, "backwards");
1734         int sequence = RNA_boolean_get(op->ptr, "sequence");
1735         int frames_limit;
1736
1737         if (track_count_markers(sc, clip) == 0)
1738                 return OPERATOR_CANCELLED;
1739
1740         track_init_markers(sc, clip, &frames_limit);
1741
1742         if (backwards)
1743                 efra = SFRA;
1744         else
1745                 efra = EFRA;
1746
1747         /* limit frames to be tracked by user setting */
1748         if (frames_limit) {
1749                 if (backwards)
1750                         efra = MAX2(efra, sfra - frames_limit);
1751                 else
1752                         efra = MIN2(efra, sfra + frames_limit);
1753         }
1754
1755         if (!track_markers_check_direction(backwards, framenr, efra))
1756                 return OPERATOR_CANCELLED;
1757
1758         /* do not disable tracks due to threshold when tracking frame-by-frame */
1759         context = BKE_tracking_context_new(clip, &sc->user, backwards, sequence);
1760
1761         while (framenr != efra) {
1762                 if (!BKE_tracking_next(context))
1763                         break;
1764
1765                 if (backwards) framenr--;
1766                 else framenr++;
1767
1768                 if (!sequence)
1769                         break;
1770         }
1771
1772         BKE_tracking_sync(context);
1773         BKE_tracking_context_free(context);
1774
1775         /* update scene current frame to the lastes tracked frame */
1776         scene->r.cfra = framenr;
1777
1778         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1779         WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
1780
1781         return OPERATOR_FINISHED;
1782 }
1783
1784 static int track_markers_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1785 {
1786         TrackMarkersJob *tmj;
1787         ScrArea *sa = CTX_wm_area(C);
1788         SpaceClip *sc = CTX_wm_space_clip(C);
1789         MovieClip *clip = ED_space_clip(sc);
1790         wmJob *steve;
1791         int backwards = RNA_boolean_get(op->ptr, "backwards");
1792         int sequence = RNA_boolean_get(op->ptr, "sequence");
1793
1794         if (WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C))) {
1795                 /* only one tracking is allowed at a time */
1796                 return OPERATOR_CANCELLED;
1797         }
1798
1799         if (clip->tracking_context)
1800                 return OPERATOR_CANCELLED;
1801
1802         if (track_count_markers(sc, clip) == 0)
1803                 return OPERATOR_CANCELLED;
1804
1805         if (!sequence)
1806                 return track_markers_exec(C, op);
1807
1808         tmj = MEM_callocN(sizeof(TrackMarkersJob), "TrackMarkersJob data");
1809         if (!track_markers_initjob(C, tmj, backwards)) {
1810                 track_markers_freejob(tmj);
1811
1812                 return OPERATOR_CANCELLED;
1813         }
1814
1815         /* setup job */
1816         steve = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Track Markers", WM_JOB_PROGRESS);
1817         WM_jobs_customdata(steve, tmj, track_markers_freejob);
1818
1819         /* if there's delay set in tracking job, tracking should happen
1820          * with fixed FPS. To deal with editor refresh we have to synchronize
1821          * tracks from job and tracks in clip. Do this in timer callback
1822          * to prevent threading conflicts. */
1823         if (tmj->delay > 0)
1824                 WM_jobs_timer(steve, tmj->delay / 1000.0f, NC_MOVIECLIP | NA_EVALUATED, 0);
1825         else
1826                 WM_jobs_timer(steve, 0.2, NC_MOVIECLIP | NA_EVALUATED, 0);
1827
1828         WM_jobs_callbacks(steve, track_markers_startjob, NULL, track_markers_updatejob, NULL);
1829
1830         G.afbreek = 0;
1831
1832         WM_jobs_start(CTX_wm_manager(C), steve);
1833         WM_cursor_wait(0);
1834
1835         /* add modal handler for ESC */
1836         WM_event_add_modal_handler(C, op);
1837
1838         return OPERATOR_RUNNING_MODAL;
1839 }
1840
1841 static int track_markers_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1842 {
1843         /* no running tracking, remove handler and pass through */
1844         if (0 == WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C)))
1845                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
1846
1847         /* running tracking */
1848         switch (event->type) {
1849                 case ESCKEY:
1850                         return OPERATOR_RUNNING_MODAL;
1851                         break;
1852         }
1853
1854         return OPERATOR_PASS_THROUGH;
1855 }
1856
1857 void CLIP_OT_track_markers(wmOperatorType *ot)
1858 {
1859         /* identifiers */
1860         ot->name = "Track Markers";
1861         ot->description = "Track selected markers";
1862         ot->idname = "CLIP_OT_track_markers";
1863
1864         /* api callbacks */
1865         ot->exec = track_markers_exec;
1866         ot->invoke = track_markers_invoke;
1867         ot->poll = ED_space_clip_tracking_frame_poll;
1868         ot->modal = track_markers_modal;
1869
1870         /* flags */
1871         ot->flag = OPTYPE_UNDO;
1872
1873         /* properties */
1874         RNA_def_boolean(ot->srna, "backwards", 0, "Backwards", "Do backwards tracking");
1875         RNA_def_boolean(ot->srna, "sequence", 0, "Track Sequence", "Track marker during image sequence rather than single image");
1876 }
1877
1878 /********************** solve camera operator *********************/
1879
1880 typedef struct {
1881         Scene *scene;
1882         MovieClip *clip;
1883         MovieClipUser user;
1884
1885         ReportList *reports;
1886
1887         char stats_message[256];
1888
1889         struct MovieReconstructContext *context;
1890 } SolveCameraJob;
1891
1892 static int solve_camera_initjob(bContext *C, SolveCameraJob *scj, wmOperator *op, char *error_msg, int max_error)
1893 {
1894         SpaceClip *sc = CTX_wm_space_clip(C);
1895         MovieClip *clip = ED_space_clip(sc);
1896         Scene *scene = CTX_data_scene(C);
1897         MovieTracking *tracking = &clip->tracking;
1898         MovieTrackingSettings *settings = &clip->tracking.settings;
1899         MovieTrackingObject *object = BKE_tracking_active_object(tracking);
1900         int width, height;
1901
1902         if (!BKE_tracking_can_reconstruct(tracking, object, error_msg, max_error))
1903                 return 0;
1904
1905         /* could fail if footage uses images with different sizes */
1906         BKE_movieclip_get_size(clip, &sc->user, &width, &height);
1907
1908         scj->clip = clip;
1909         scj->scene = scene;
1910         scj->reports = op->reports;
1911         scj->user = sc->user;
1912
1913         scj->context = BKE_tracking_reconstruction_context_new(tracking, object,
1914                         settings->keyframe1, settings->keyframe2, width, height);
1915
1916         tracking->stats = MEM_callocN(sizeof(MovieTrackingStats), "solve camera stats");
1917
1918         return 1;
1919 }
1920
1921 static void solve_camera_updatejob(void *scv)
1922 {
1923         SolveCameraJob *scj = (SolveCameraJob *)scv;
1924         MovieTracking *tracking = &scj->clip->tracking;
1925
1926         BLI_strncpy(tracking->stats->message, scj->stats_message, sizeof(tracking->stats->message));
1927 }
1928
1929 static void solve_camera_startjob(void *scv, short *stop, short *do_update, float *progress)
1930 {
1931         SolveCameraJob *scj = (SolveCameraJob *)scv;
1932
1933         BKE_tracking_solve_reconstruction(scj->context, stop, do_update, progress,
1934                         scj->stats_message, sizeof(scj->stats_message));
1935 }
1936
1937 static void solve_camera_freejob(void *scv)
1938 {
1939         SolveCameraJob *scj = (SolveCameraJob *)scv;
1940         MovieTracking *tracking = &scj->clip->tracking;
1941         Scene *scene = scj->scene;
1942         MovieClip *clip = scj->clip;
1943         int solved;
1944
1945         if (!scj->context) {
1946                 /* job weren't fully initialized due to some error */
1947                 MEM_freeN(scj);
1948                 return;
1949         }
1950
1951         solved = BKE_tracking_finish_reconstruction(scj->context, tracking);
1952
1953         if (!solved)
1954                 BKE_report(scj->reports, RPT_WARNING, "Some data failed to reconstruct, see console for details");
1955         else
1956                 BKE_reportf(scj->reports, RPT_INFO, "Average re-projection error %.3f", tracking->reconstruction.error);
1957
1958         /* set currently solved clip as active for scene */
1959         if (scene->clip)
1960                 id_us_min(&clip->id);
1961
1962         scene->clip = clip;
1963         id_us_plus(&clip->id);
1964
1965         /* set blender camera focal length so result would look fine there */
1966         if (scene->camera) {
1967                 Camera *camera = (Camera*)scene->camera->data;
1968                 int width, height;
1969
1970                 BKE_movieclip_get_size(clip, &scj->user, &width, &height);
1971
1972                 BKE_tracking_camera_to_blender(tracking, scene, camera, width, height);
1973
1974                 WM_main_add_notifier(NC_OBJECT, camera);
1975         }
1976
1977         MEM_freeN(tracking->stats);
1978         tracking->stats = NULL;
1979
1980         DAG_id_tag_update(&clip->id, 0);
1981
1982         WM_main_add_notifier(NC_MOVIECLIP | NA_EVALUATED, clip);
1983         WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, NULL);
1984
1985         /* update active clip displayed in scene buttons */
1986         WM_main_add_notifier(NC_SCENE, scene);
1987
1988         BKE_tracking_reconstruction_context_free(scj->context);
1989         MEM_freeN(scj);
1990 }
1991
1992 static int solve_camera_exec(bContext *C, wmOperator *op)
1993 {
1994         SolveCameraJob *scj;
1995         char error_msg[256] = "\0";
1996
1997         scj = MEM_callocN(sizeof(SolveCameraJob), "SolveCameraJob data");
1998         if (!solve_camera_initjob(C, scj, op, error_msg, sizeof(error_msg))) {
1999                 if (error_msg[0])
2000                         BKE_report(op->reports, RPT_ERROR, error_msg);
2001
2002                 solve_camera_freejob(scj);
2003
2004                 return OPERATOR_CANCELLED;
2005         }
2006
2007         solve_camera_startjob(scj, NULL, NULL, NULL);
2008
2009         solve_camera_freejob(scj);
2010
2011         return OPERATOR_FINISHED;
2012 }
2013
2014 static int solve_camera_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2015 {
2016         SolveCameraJob *scj;
2017         ScrArea *sa = CTX_wm_area(C);
2018         SpaceClip *sc = CTX_wm_space_clip(C);
2019         MovieClip *clip = ED_space_clip(sc);
2020         MovieTracking *tracking = &clip->tracking;
2021         MovieTrackingReconstruction *reconstruction = BKE_tracking_get_reconstruction(tracking);
2022         wmJob *steve;
2023         char error_msg[256] = "\0";
2024
2025         if (WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C))) {
2026                 /* only one solve is allowed at a time */
2027                 return OPERATOR_CANCELLED;
2028         }
2029
2030         scj = MEM_callocN(sizeof(SolveCameraJob), "SolveCameraJob data");
2031         if (!solve_camera_initjob(C, scj, op, error_msg, sizeof(error_msg))) {
2032                 if (error_msg[0])
2033                         BKE_report(op->reports, RPT_ERROR, error_msg);
2034
2035                 solve_camera_freejob(scj);
2036
2037                 return OPERATOR_CANCELLED;
2038         }
2039
2040         BLI_strncpy(tracking->stats->message, "Solving camera | Preparing solve", sizeof(tracking->stats->message));
2041
2042         /* hide reconstruction statistics from previous solve */
2043         reconstruction->flag &= ~TRACKING_RECONSTRUCTED;
2044         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2045
2046         /* setup job */
2047         steve = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Solve Camera", WM_JOB_PROGRESS);
2048         WM_jobs_customdata(steve, scj, solve_camera_freejob);
2049         WM_jobs_timer(steve, 0.1, NC_MOVIECLIP | NA_EVALUATED, 0);
2050         WM_jobs_callbacks(steve, solve_camera_startjob, NULL, solve_camera_updatejob, NULL);
2051
2052         G.afbreek = 0;
2053
2054         WM_jobs_start(CTX_wm_manager(C), steve);
2055         WM_cursor_wait(0);
2056
2057         /* add modal handler for ESC */
2058         WM_event_add_modal_handler(C, op);
2059
2060         return OPERATOR_RUNNING_MODAL;
2061 }
2062
2063 static int solve_camera_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
2064 {
2065         /* no running solver, remove handler and pass through */
2066         if (0 == WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C)))
2067                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
2068
2069         /* running tracking */
2070         switch (event->type) {
2071                 case ESCKEY:
2072                         return OPERATOR_RUNNING_MODAL;
2073                         break;
2074         }
2075
2076         return OPERATOR_PASS_THROUGH;
2077 }
2078
2079 void CLIP_OT_solve_camera(wmOperatorType *ot)
2080 {
2081         /* identifiers */
2082         ot->name = "Solve Camera";
2083         ot->description = "Solve camera motion from tracks";
2084         ot->idname = "CLIP_OT_solve_camera";
2085
2086         /* api callbacks */
2087         ot->exec = solve_camera_exec;
2088         ot->invoke = solve_camera_invoke;
2089         ot->modal = solve_camera_modal;
2090         ot->poll = ED_space_clip_tracking_poll;
2091
2092         /* flags */
2093         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2094 }
2095
2096 /********************** clear solution operator *********************/
2097
2098 static int clear_solution_exec(bContext *C, wmOperator *UNUSED(op))
2099 {
2100         SpaceClip *sc = CTX_wm_space_clip(C);
2101         MovieClip *clip = ED_space_clip(sc);
2102         MovieTracking *tracking = &clip->tracking;
2103         ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
2104         MovieTrackingReconstruction *reconstruction = BKE_tracking_get_reconstruction(tracking);
2105         MovieTrackingTrack *track = tracksbase->first;
2106
2107         while (track) {
2108                 track->flag &= ~TRACK_HAS_BUNDLE;
2109
2110                 track = track->next;
2111         }
2112
2113         if (reconstruction->cameras)
2114                 MEM_freeN(reconstruction->cameras);
2115
2116         reconstruction->cameras = NULL;
2117         reconstruction->camnr = 0;
2118
2119         reconstruction->flag &= ~TRACKING_RECONSTRUCTED;
2120
2121         DAG_id_tag_update(&clip->id, 0);
2122
2123         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2124         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL);
2125
2126         return OPERATOR_FINISHED;
2127 }
2128
2129 void CLIP_OT_clear_solution(wmOperatorType *ot)
2130 {
2131         /* identifiers */
2132         ot->name = "Clear Solution";
2133         ot->description = "Clear all calculated data";
2134         ot->idname = "CLIP_OT_clear_solution";
2135
2136         /* api callbacks */
2137         ot->exec = clear_solution_exec;
2138         ot->poll = ED_space_clip_tracking_poll;
2139
2140         /* flags */
2141         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2142 }
2143
2144 /********************** clear track operator *********************/
2145
2146 static int clear_track_path_exec(bContext *C, wmOperator *op)
2147 {
2148         SpaceClip *sc = CTX_wm_space_clip(C);
2149         MovieClip *clip = ED_space_clip(sc);
2150         MovieTrackingTrack *track;
2151         ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
2152         int action = RNA_enum_get(op->ptr, "action");
2153         int clear_active = RNA_boolean_get(op->ptr, "clear_active");
2154
2155         if (clear_active) {
2156                 track = BKE_tracking_active_track(&clip->tracking);
2157                 BKE_tracking_clear_path(track, sc->user.framenr, action);
2158         }
2159         else {
2160                 track = tracksbase->first;
2161                 while (track) {
2162                         if (TRACK_VIEW_SELECTED(sc, track))
2163                                 BKE_tracking_clear_path(track, sc->user.framenr, action);
2164
2165                         track = track->next;
2166                 }
2167         }
2168
2169         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2170
2171         return OPERATOR_FINISHED;
2172 }
2173
2174 void CLIP_OT_clear_track_path(wmOperatorType *ot)
2175 {
2176         static EnumPropertyItem clear_path_actions[] = {
2177                         {TRACK_CLEAR_UPTO, "UPTO", 0, "Clear up-to", "Clear path up to current frame"},
2178                         {TRACK_CLEAR_REMAINED, "REMAINED", 0, "Clear remained", "Clear path at remaining frames (after current)"},
2179                         {TRACK_CLEAR_ALL, "ALL", 0, "Clear all", "Clear the whole path"},
2180                         {0, NULL, 0, NULL, NULL}
2181         };
2182
2183         /* identifiers */
2184         ot->name = "Clear Track Path";
2185         ot->description = "Clear tracks after/before current position or clear the whole track";
2186         ot->idname = "CLIP_OT_clear_track_path";
2187
2188         /* api callbacks */
2189         ot->exec = clear_track_path_exec;
2190         ot->poll = ED_space_clip_tracking_poll;
2191
2192         /* flags */
2193         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2194
2195         /* proeprties */
2196         RNA_def_enum(ot->srna, "action", clear_path_actions, TRACK_CLEAR_REMAINED, "Action", "Clear action to execute");
2197         RNA_def_boolean(ot->srna, "clear_active", 0, "Clear Active", "Clear active track only instead of all selected tracks");
2198 }
2199
2200 /********************** disable markers operator *********************/
2201
2202 static int disable_markers_exec(bContext *C, wmOperator *op)
2203 {
2204         SpaceClip *sc = CTX_wm_space_clip(C);
2205         MovieClip *clip = ED_space_clip(sc);
2206         MovieTracking *tracking = &clip->tracking;
2207         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
2208         MovieTrackingTrack *track = tracksbase->first;
2209         int action = RNA_enum_get(op->ptr, "action");
2210
2211         while (track) {
2212                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
2213                         MovieTrackingMarker *marker = BKE_tracking_ensure_marker(track, sc->user.framenr);
2214
2215                         if (action == 0)
2216                                 marker->flag |= MARKER_DISABLED;
2217                         else if (action == 1)
2218                                 marker->flag &= ~MARKER_DISABLED;
2219                         else marker->flag ^= MARKER_DISABLED;
2220                 }
2221
2222                 track = track->next;
2223         }
2224
2225         DAG_id_tag_update(&clip->id, 0);
2226
2227         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2228
2229         return OPERATOR_FINISHED;
2230 }
2231
2232 void CLIP_OT_disable_markers(wmOperatorType *ot)
2233 {
2234         static EnumPropertyItem actions_items[] = {
2235                         {0, "DISABLE", 0, "Disable", "Disable selected markers"},
2236                         {1, "ENABLE", 0, "Enable", "Enable selected markers"},
2237                         {2, "TOGGLE", 0, "Toggle", "Toggle disabled flag for selected markers"},
2238                         {0, NULL, 0, NULL, NULL}
2239         };
2240
2241         /* identifiers */
2242         ot->name = "Disable Markers";
2243         ot->description = "Disable/enable selected markers";
2244         ot->idname = "CLIP_OT_disable_markers";
2245
2246         /* api callbacks */
2247         ot->exec = disable_markers_exec;
2248         ot->poll = ED_space_clip_tracking_poll;
2249
2250         /* flags */
2251         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2252
2253         /* properties */
2254         RNA_def_enum(ot->srna, "action", actions_items, 0, "Action", "Disable action to execute");
2255 }
2256
2257 /********************** set origin operator *********************/
2258
2259 static Object *get_camera_with_movieclip(Scene *scene, MovieClip *clip)
2260 {
2261         Object *camera = scene->camera;
2262         Base *base;
2263
2264         if (camera && BKE_object_movieclip_get(scene, camera, 0) == clip)
2265                 return camera;
2266
2267         base = scene->base.first;
2268         while (base) {
2269                 if (base->object->type == OB_CAMERA) {
2270                         if (BKE_object_movieclip_get(scene, base->object, 0) == clip) {
2271                                 camera = base->object;
2272                                 break;
2273                         }
2274                 }
2275
2276                 base = base->next;
2277         }
2278
2279         return camera;
2280 }
2281
2282 static Object *get_orientation_object(bContext *C)
2283 {
2284         Scene *scene = CTX_data_scene(C);
2285         SpaceClip *sc = CTX_wm_space_clip(C);
2286         MovieClip *clip = ED_space_clip(sc);
2287         MovieTracking *tracking = &clip->tracking;
2288         MovieTrackingObject *tracking_object = BKE_tracking_active_object(tracking);
2289         Object *object = NULL;
2290
2291         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2292                 object = get_camera_with_movieclip(scene, clip);
2293         }
2294         else {
2295                 object = OBACT;
2296         }
2297
2298         if (object && object->parent)
2299                 object = object->parent;
2300
2301         return object;
2302 }
2303
2304 static int set_orientation_poll(bContext *C)
2305 {
2306         if (ED_space_clip_tracking_size_poll(C)) {
2307                 Scene *scene = CTX_data_scene(C);
2308                 SpaceClip *sc = CTX_wm_space_clip(C);
2309                 MovieClip *clip = ED_space_clip(sc);
2310                 MovieTracking *tracking = &clip->tracking;
2311                 MovieTrackingObject *tracking_object = BKE_tracking_active_object(tracking);
2312
2313                 if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2314                         return TRUE;
2315                 }
2316                 else {
2317                         return OBACT != NULL;
2318                 }
2319         }
2320
2321         return FALSE;
2322 }
2323
2324 static int count_selected_bundles(bContext *C)
2325 {
2326         SpaceClip *sc = CTX_wm_space_clip(C);
2327         MovieClip *clip = ED_space_clip(sc);
2328         ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
2329         MovieTrackingTrack *track;
2330         int tot = 0;
2331
2332         track = tracksbase->first;
2333         while (track) {
2334                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_HAS_BUNDLE))
2335                         tot++;
2336
2337                 track = track->next;
2338         }
2339
2340         return tot;
2341 }
2342
2343 static void object_solver_inverted_matrix(Scene *scene, Object *ob, float invmat[4][4])
2344 {
2345         bConstraint *con;
2346         int found = FALSE;
2347
2348         for (con = ob->constraints.first; con; con = con->next) {
2349                 bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
2350
2351                 if (!cti)
2352                         continue;
2353
2354                 if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
2355                         bObjectSolverConstraint *data = (bObjectSolverConstraint *)con->data;
2356
2357                         if (!found) {
2358                                 Object *cam = data->camera ? data->camera : scene->camera;
2359
2360                                 BKE_object_where_is_calc_mat4(scene, cam, invmat);
2361                         }
2362
2363                         mult_m4_m4m4(invmat, invmat, data->invmat);
2364
2365                         found = TRUE;
2366                 }
2367         }
2368
2369         if (found)
2370                 invert_m4(invmat);
2371         else
2372                 unit_m4(invmat);
2373 }
2374
2375 static Object *object_solver_camera(Scene *scene, Object *ob)
2376 {
2377         bConstraint *con;
2378
2379         for (con = ob->constraints.first; con; con = con->next) {
2380                 bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
2381
2382                 if (!cti)
2383                         continue;
2384
2385                 if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
2386                         bObjectSolverConstraint *data = (bObjectSolverConstraint *)con->data;
2387
2388                         return data->camera ? data->camera : scene->camera;
2389                 }
2390         }
2391
2392         return NULL;
2393 }
2394
2395 static int set_origin_exec(bContext *C, wmOperator *op)
2396 {
2397         SpaceClip *sc = CTX_wm_space_clip(C);
2398         MovieClip *clip = ED_space_clip(sc);
2399         MovieTracking *tracking = &clip->tracking;
2400         MovieTrackingTrack *track;
2401         MovieTrackingObject *tracking_object;
2402         Scene *scene = CTX_data_scene(C);
2403         Object *object;
2404         Object *camera = get_camera_with_movieclip(scene, clip);
2405         ListBase *tracksbase;
2406         float mat[4][4], vec[3], median[3];
2407         int selected_count = count_selected_bundles(C);
2408
2409         if (selected_count == 0) {
2410                 BKE_report(op->reports, RPT_ERROR, "At least one track with bundle should be selected to define origin position");
2411
2412                 return OPERATOR_CANCELLED;
2413         }
2414
2415         object = get_orientation_object(C);
2416         if (!object) {
2417                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2418
2419                 return OPERATOR_CANCELLED;
2420         }
2421
2422         tracking_object = BKE_tracking_active_object(tracking);
2423
2424         tracksbase = BKE_tracking_object_tracks(tracking, tracking_object);
2425
2426         track = tracksbase->first;
2427         zero_v3(median);
2428         while (track) {
2429                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_HAS_BUNDLE)) {
2430                         add_v3_v3(median, track->bundle_pos);
2431                 }
2432
2433                 track = track->next;
2434         }
2435         mul_v3_fl(median, 1.0f / selected_count);
2436
2437         BKE_get_tracking_mat(scene, camera, mat);
2438
2439         mul_v3_m4v3(vec, mat, median);
2440
2441         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2442                 sub_v3_v3(object->loc, vec);
2443         }
2444         else {
2445                 object_solver_inverted_matrix(scene, object, mat);
2446                 mul_v3_m4v3(vec, mat, vec);
2447                 copy_v3_v3(object->loc, vec);
2448         }
2449
2450         DAG_id_tag_update(&clip->id, 0);
2451         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2452
2453         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2454         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2455
2456         return OPERATOR_FINISHED;
2457 }
2458
2459 void CLIP_OT_set_origin(wmOperatorType *ot)
2460 {
2461         /* identifiers */
2462         ot->name = "Set Origin";
2463         ot->description = "Set active marker as origin by moving camera (or it's parent if present) in 3D space";
2464         ot->idname = "CLIP_OT_set_origin";
2465
2466         /* api callbacks */
2467         ot->exec = set_origin_exec;
2468         ot->poll = set_orientation_poll;
2469
2470         /* flags */
2471         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2472
2473         /* properties */
2474         RNA_def_boolean(ot->srna, "use_median", 0, "Use Median", "Set origin to median point of selected bundles");
2475 }
2476
2477 /********************** set floor operator *********************/
2478
2479 static void set_axis(Scene *scene,  Object *ob, MovieClip *clip, MovieTrackingObject *tracking_object,
2480                         MovieTrackingTrack *track, char axis)
2481 {
2482         Object *camera = get_camera_with_movieclip(scene, clip);
2483         int is_camera = tracking_object->flag & TRACKING_OBJECT_CAMERA;
2484         int  flip = FALSE;
2485         float mat[4][4], vec[3], obmat[4][4], dvec[3];
2486
2487         BKE_object_to_mat4(ob, obmat);
2488
2489         BKE_get_tracking_mat(scene, camera, mat);
2490         mul_v3_m4v3(vec, mat, track->bundle_pos);
2491         copy_v3_v3(dvec, vec);
2492
2493         if (!is_camera) {
2494                 float imat[4][4];
2495
2496                 object_solver_inverted_matrix(scene, ob, imat);
2497                 mul_v3_m4v3(vec, imat, vec);
2498
2499                 invert_m4_m4(imat, obmat);
2500                 mul_v3_m4v3(dvec, imat, vec);
2501
2502                 sub_v3_v3(vec, obmat[3]);
2503         }
2504
2505         if (len_v2(vec) < 1e-3f)
2506                 return;
2507
2508         unit_m4(mat);
2509
2510         if (axis == 'X') {
2511                 if (fabsf(dvec[1]) < 1e-3f) {
2512                         flip = TRUE;
2513
2514                         mat[0][0] = -1.0f; mat[0][1] = 0.0f; mat[0][2] = 0.0f;
2515                         mat[1][0] = 0.0f; mat[1][1] = -1.0f; mat[1][2] = 0.0f;
2516                         mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2517                 }
2518                 else {
2519                         copy_v3_v3(mat[0], vec);
2520
2521                         if (is_camera || fabsf(vec[2]) < 1e-3f) {
2522                                 mat[0][2] = 0.0f;
2523                                 mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2524                                 cross_v3_v3v3(mat[1], mat[2], mat[0]);
2525                         }
2526                         else {
2527                                 vec[2] = 0.0f;
2528
2529                                 cross_v3_v3v3(mat[1], mat[0], vec);
2530                                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
2531                         }
2532                 }
2533         }
2534         else {
2535                 if (fabsf(dvec[0]) < 1e-3f) {
2536                         flip = TRUE;
2537
2538                         mat[0][0] = -1.0f; mat[0][1] = 0.0f; mat[0][2] = 0.0f;
2539                         mat[1][0] = 0.0f; mat[1][1] = -1.0f; mat[1][2] = 0.0f;
2540                         mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2541                 }
2542                 else {
2543                         copy_v3_v3(mat[1], vec);
2544
2545                         if (is_camera || fabsf(vec[2]) < 1e-3f) {
2546                                 mat[1][2] = 0.0f;
2547                                 mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2548                                 cross_v3_v3v3(mat[0], mat[1], mat[2]);
2549                         }
2550                         else {
2551                                 vec[2] = 0.0f;
2552
2553                                 cross_v3_v3v3(mat[0], vec, mat[1]);
2554                                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
2555                         }
2556                 }
2557         }
2558
2559         normalize_v3(mat[0]);
2560         normalize_v3(mat[1]);
2561         normalize_v3(mat[2]);
2562
2563         if (is_camera) {
2564                 invert_m4(mat);
2565
2566                 mult_m4_m4m4(mat, mat, obmat);
2567         }
2568         else {
2569                 if (!flip) {
2570                         float lmat[4][4], ilmat[4][4], rmat[3][3];
2571
2572                         BKE_object_rot_to_mat3(ob, rmat);
2573                         invert_m3(rmat);
2574                         mul_m4_m4m3(mat, mat, rmat);
2575
2576                         unit_m4(lmat);
2577                         copy_v3_v3(lmat[3], obmat[3]);
2578                         invert_m4_m4(ilmat, lmat);
2579
2580                         mul_serie_m4(mat, lmat, mat, ilmat, obmat, NULL, NULL, NULL, NULL);
2581                 }
2582                 else {
2583                         mult_m4_m4m4(mat, obmat, mat);
2584                 }
2585         }
2586
2587         BKE_object_apply_mat4(ob, mat, 0, 0);
2588 }
2589
2590 static int set_plane_exec(bContext *C, wmOperator *op)
2591 {
2592         SpaceClip *sc = CTX_wm_space_clip(C);
2593         MovieClip *clip = ED_space_clip(sc);
2594         Scene *scene = CTX_data_scene(C);
2595         MovieTracking *tracking = &clip->tracking;
2596         MovieTrackingObject *tracking_object;
2597         MovieTrackingTrack *track, *axis_track = NULL, *act_track;
2598         ListBase *tracksbase;
2599         Object *object;
2600         Object *camera = get_camera_with_movieclip(scene, clip);
2601         int tot = 0;
2602         float vec[3][3], mat[4][4], obmat[4][4], newmat[4][4], orig[3] = {0.0f, 0.0f, 0.0f};
2603         int plane = RNA_enum_get(op->ptr, "plane");
2604         float rot[4][4] = {{0.0f, 0.0f, -1.0f, 0.0f},
2605                            {0.0f, 1.0f, 0.0f, 0.0f},
2606                            {1.0f, 0.0f, 0.0f, 0.0f},
2607                            {0.0f, 0.0f, 0.0f, 1.0f}};   /* 90 degrees Y-axis rotation matrix */
2608
2609         if (count_selected_bundles(C) != 3) {
2610                 BKE_report(op->reports, RPT_ERROR, "Three tracks with bundles are needed to orient the floor");
2611
2612                 return OPERATOR_CANCELLED;
2613         }
2614
2615         tracking_object = BKE_tracking_active_object(tracking);
2616         tracksbase = BKE_tracking_object_tracks(tracking, tracking_object);
2617         act_track = BKE_tracking_active_track(tracking);
2618
2619         object = get_orientation_object(C);
2620         if (!object) {
2621                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2622
2623                 return OPERATOR_CANCELLED;
2624         }
2625
2626         BKE_get_tracking_mat(scene, camera, mat);
2627
2628         /* get 3 bundles to use as reference */
2629         track = tracksbase->first;
2630         while (track && tot < 3) {
2631                 if (track->flag & TRACK_HAS_BUNDLE && TRACK_VIEW_SELECTED(sc, track)) {
2632                         mul_v3_m4v3(vec[tot], mat, track->bundle_pos);
2633
2634                         if (tot == 0 || track == act_track)
2635                                 copy_v3_v3(orig, vec[tot]);
2636                         else
2637                                 axis_track = track;
2638
2639                         tot++;
2640                 }
2641
2642                 track = track->next;
2643         }
2644
2645         sub_v3_v3(vec[1], vec[0]);
2646         sub_v3_v3(vec[2], vec[0]);
2647
2648         /* construct ortho-normal basis */
2649         unit_m4(mat);
2650
2651         if (plane == 0) { /* floor */
2652                 cross_v3_v3v3(mat[0], vec[1], vec[2]);
2653                 copy_v3_v3(mat[1], vec[1]);
2654                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
2655         }
2656         else if (plane == 1) { /* wall */
2657                 cross_v3_v3v3(mat[2], vec[1], vec[2]);
2658                 copy_v3_v3(mat[1], vec[1]);
2659                 cross_v3_v3v3(mat[0], mat[1], mat[2]);
2660         }
2661
2662         normalize_v3(mat[0]);
2663         normalize_v3(mat[1]);
2664         normalize_v3(mat[2]);
2665
2666         /* move to origin point */
2667         mat[3][0] = orig[0];
2668         mat[3][1] = orig[1];
2669         mat[3][2] = orig[2];
2670
2671         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2672                 invert_m4(mat);
2673
2674                 BKE_object_to_mat4(object, obmat);
2675                 mult_m4_m4m4(mat, mat, obmat);
2676                 mult_m4_m4m4(newmat, rot, mat);
2677                 BKE_object_apply_mat4(object, newmat, 0, 0);
2678
2679                 /* make camera have positive z-coordinate */
2680                 if (object->loc[2] < 0) {
2681                         invert_m4(rot);
2682                         mult_m4_m4m4(newmat, rot, mat);
2683                         BKE_object_apply_mat4(object, newmat, 0, 0);
2684                 }
2685         }
2686         else {
2687                 BKE_object_apply_mat4(object, mat, 0, 0);
2688         }
2689
2690         BKE_object_where_is_calc(scene, object);
2691         set_axis(scene, object, clip, tracking_object, axis_track, 'X');
2692
2693         DAG_id_tag_update(&clip->id, 0);
2694         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2695
2696         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2697         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2698
2699         return OPERATOR_FINISHED;
2700 }
2701
2702 void CLIP_OT_set_plane(wmOperatorType *ot)
2703 {
2704         static EnumPropertyItem plane_items[] = {
2705                         {0, "FLOOR", 0, "Floor", "Set floor plane"},
2706                         {1, "WALL", 0, "Wall", "Set wall plane"},
2707                         {0, NULL, 0, NULL, NULL}
2708         };
2709
2710         /* identifiers */
2711         ot->name = "Set Plane";
2712         ot->description = "Set plane based on 3 selected bundles by moving camera (or it's parent if present) in 3D space";
2713         ot->idname = "CLIP_OT_set_plane";
2714
2715         /* api callbacks */
2716         ot->exec = set_plane_exec;
2717         ot->poll = set_orientation_poll;
2718
2719         /* flags */
2720         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2721
2722         /* properties */
2723         RNA_def_enum(ot->srna, "plane", plane_items, 0, "Plane", "Plane to be used for orientation");
2724 }
2725
2726 /********************** set axis operator *********************/
2727
2728 static int set_axis_exec(bContext *C, wmOperator *op)
2729 {
2730         SpaceClip *sc = CTX_wm_space_clip(C);
2731         MovieClip *clip = ED_space_clip(sc);
2732         MovieTracking *tracking = &clip->tracking;
2733         MovieTrackingObject *tracking_object = BKE_tracking_active_object(tracking);
2734         MovieTrackingTrack *track;
2735         Scene *scene = CTX_data_scene(C);
2736         Object *object;
2737         ListBase *tracksbase;
2738         int axis = RNA_enum_get(op->ptr, "axis");
2739
2740         if (count_selected_bundles(C) != 1) {
2741                 BKE_report(op->reports, RPT_ERROR, "Single track with bundle should be selected to define axis");
2742
2743                 return OPERATOR_CANCELLED;
2744         }
2745
2746         object = get_orientation_object(C);
2747         if (!object) {
2748                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2749
2750                 return OPERATOR_CANCELLED;
2751         }
2752
2753         tracksbase = BKE_tracking_object_tracks(tracking, tracking_object);
2754
2755         track = tracksbase->first;
2756         while (track) {
2757                 if (TRACK_VIEW_SELECTED(sc, track))
2758                         break;
2759
2760                 track = track->next;
2761         }
2762
2763         set_axis(scene, object, clip, tracking_object, track, axis == 0 ? 'X' : 'Y');
2764
2765         DAG_id_tag_update(&clip->id, 0);
2766         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2767
2768         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2769         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2770
2771         return OPERATOR_FINISHED;
2772 }
2773
2774 void CLIP_OT_set_axis(wmOperatorType *ot)
2775 {
2776         static EnumPropertyItem axis_actions[] = {
2777                         {0, "X", 0, "X", "Align bundle align X axis"},
2778                         {1, "Y", 0, "Y", "Align bundle align Y axis"},
2779                         {0, NULL, 0, NULL, NULL}
2780         };
2781
2782         /* identifiers */
2783         ot->name = "Set Axis";
2784         ot->description = "Set direction of scene axis rotating camera (or it's parent if present) and assuming selected track lies on real axis joining it with the origin";
2785         ot->idname = "CLIP_OT_set_axis";
2786
2787         /* api callbacks */
2788         ot->exec = set_axis_exec;
2789         ot->poll = set_orientation_poll;
2790
2791         /* flags */
2792         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2793
2794         /* properties */
2795         RNA_def_enum(ot->srna, "axis", axis_actions, 0, "Axis", "Axis to use to align bundle along");
2796 }
2797
2798 /********************** set scale operator *********************/
2799
2800 static int do_set_scale(bContext *C, wmOperator *op, int scale_solution)
2801 {
2802         SpaceClip *sc = CTX_wm_space_clip(C);
2803         MovieClip *clip = ED_space_clip(sc);
2804         MovieTracking *tracking = &clip->tracking;
2805         MovieTrackingObject *tracking_object = BKE_tracking_active_object(tracking);
2806         MovieTrackingTrack *track;
2807         Scene *scene = CTX_data_scene(C);
2808         Object *object = NULL;
2809         Object *camera = get_camera_with_movieclip(scene, clip);
2810         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
2811         int tot = 0;
2812         float vec[2][3], mat[4][4], scale;
2813         float dist = RNA_float_get(op->ptr, "distance");
2814
2815         if (count_selected_bundles(C) != 2) {
2816                 BKE_report(op->reports, RPT_ERROR, "Two tracks with bundles should be selected to set scale");
2817
2818                 return OPERATOR_CANCELLED;
2819         }
2820
2821         object = get_orientation_object(C);
2822         if (!object) {
2823                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2824
2825                 return OPERATOR_CANCELLED;
2826         }
2827
2828         BKE_get_tracking_mat(scene, camera, mat);
2829
2830         track = tracksbase->first;
2831         while (track) {
2832                 if (TRACK_VIEW_SELECTED(sc, track)) {
2833                         mul_v3_m4v3(vec[tot], mat, track->bundle_pos);
2834                         tot++;
2835                 }
2836
2837                 track = track->next;
2838         }
2839
2840         sub_v3_v3(vec[0], vec[1]);
2841
2842         if (len_v3(vec[0]) > 1e-5f) {
2843                 scale = dist / len_v3(vec[0]);
2844
2845                 if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2846                         mul_v3_fl(object->size, scale);
2847                         mul_v3_fl(object->loc, scale);
2848                 }
2849                 else if (!scale_solution) {
2850                         Object *solver_camera = object_solver_camera(scene, object);
2851
2852                         object->size[0] = object->size[1] = object->size[2] = 1.0f / scale;
2853
2854                         if (solver_camera) {
2855                                 object->size[0] /= solver_camera->size[0];
2856                                 object->size[1] /= solver_camera->size[1];
2857                                 object->size[2] /= solver_camera->size[2];
2858                         }
2859                 }
2860                 else {
2861                         tracking_object->scale = scale;
2862                 }
2863
2864                 DAG_id_tag_update(&clip->id, 0);
2865
2866                 if (object)
2867                         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2868
2869                 WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2870                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2871         }
2872
2873         return OPERATOR_FINISHED;
2874 }
2875
2876 static int set_scale_exec(bContext *C, wmOperator *op)
2877 {
2878         return do_set_scale(C, op, 0);
2879 }
2880
2881 static int set_scale_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2882 {
2883         SpaceClip *sc = CTX_wm_space_clip(C);
2884         MovieClip *clip = ED_space_clip(sc);
2885
2886         if (!RNA_struct_property_is_set(op->ptr, "distance"))
2887                 RNA_float_set(op->ptr, "distance", clip->tracking.settings.dist);
2888
2889         return set_scale_exec(C, op);
2890 }
2891
2892 void CLIP_OT_set_scale(wmOperatorType *ot)
2893 {
2894         /* identifiers */
2895         ot->name = "Set Scale";
2896         ot->description = "Set scale of scene by scaling camera (or it's parent if present)";
2897         ot->idname = "CLIP_OT_set_scale";
2898
2899         /* api callbacks */
2900         ot->exec = set_scale_exec;
2901         ot->invoke = set_scale_invoke;
2902         ot->poll = set_orientation_poll;
2903
2904         /* flags */
2905         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2906
2907         /* properties */
2908         RNA_def_float(ot->srna, "distance", 0.0f, -FLT_MAX, FLT_MAX,
2909                 "Distance", "Distance between selected tracks", -100.0f, 100.0f);
2910 }
2911
2912 /********************** set solution scale operator *********************/
2913
2914 static int set_solution_scale_poll(bContext *C)
2915 {
2916         if (ED_space_clip_tracking_size_poll(C)) {
2917                 SpaceClip *sc = CTX_wm_space_clip(C);
2918                 MovieClip *clip = ED_space_clip(sc);
2919                 MovieTracking *tracking = &clip->tracking;
2920                 MovieTrackingObject *tracking_object = BKE_tracking_active_object(tracking);
2921
2922                 return (tracking_object->flag & TRACKING_OBJECT_CAMERA) == 0;
2923         }
2924
2925         return 0;
2926 }
2927
2928 static int set_solution_scale_exec(bContext *C, wmOperator *op)
2929 {
2930         return do_set_scale(C, op, 1);
2931 }
2932
2933 static int set_solution_scale_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2934 {
2935         SpaceClip *sc = CTX_wm_space_clip(C);
2936         MovieClip *clip = ED_space_clip(sc);
2937
2938         if (!RNA_struct_property_is_set(op->ptr, "distance"))
2939                 RNA_float_set(op->ptr, "distance", clip->tracking.settings.object_distance);
2940
2941         return set_solution_scale_exec(C, op);
2942 }
2943
2944 void CLIP_OT_set_solution_scale(wmOperatorType *ot)
2945 {
2946         /* identifiers */
2947         ot->name = "Set Solution Scale";
2948         ot->description = "Set object solution scale using distance between two selected tracks";
2949         ot->idname = "CLIP_OT_set_solution_scale";
2950
2951         /* api callbacks */
2952         ot->exec = set_solution_scale_exec;
2953         ot->invoke = set_solution_scale_invoke;
2954         ot->poll = set_solution_scale_poll;
2955
2956         /* flags */
2957         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2958
2959         /* properties */
2960         RNA_def_float(ot->srna, "distance", 0.0f, -FLT_MAX, FLT_MAX,
2961                 "Distance", "Distance between selected tracks", -100.0f, 100.0f);
2962 }
2963
2964 /********************** set principal center operator *********************/
2965
2966 static int set_center_principal_exec(bContext *C, wmOperator *UNUSED(op))
2967 {
2968         SpaceClip *sc = CTX_wm_space_clip(C);
2969         MovieClip *clip = ED_space_clip(sc);
2970         int width, height;
2971
2972         BKE_movieclip_get_size(clip, &sc->user, &width, &height);
2973
2974         if (width == 0 || height == 0)
2975                 return OPERATOR_CANCELLED;
2976
2977         clip->tracking.camera.principal[0] = ((float)width) / 2.0f;
2978         clip->tracking.camera.principal[1] = ((float)height) / 2.0f;
2979
2980         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
2981
2982         return OPERATOR_FINISHED;
2983 }
2984
2985 void CLIP_OT_set_center_principal(wmOperatorType *ot)
2986 {
2987         /* identifiers */
2988         ot->name = "Set Principal to Center";
2989         ot->description = "Set optical center to center of footage";
2990         ot->idname = "CLIP_OT_set_center_principal";
2991
2992         /* api callbacks */
2993         ot->exec = set_center_principal_exec;
2994         ot->poll = ED_space_clip_tracking_poll;
2995
2996         /* flags */
2997         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2998 }
2999
3000 /********************** hide tracks operator *********************/
3001
3002 static int hide_tracks_exec(bContext *C, wmOperator *op)
3003 {
3004         SpaceClip *sc = CTX_wm_space_clip(C);
3005         MovieClip *clip = ED_space_clip(sc);
3006         MovieTrackingTrack *track;
3007         MovieTracking *tracking = &clip->tracking;
3008         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
3009         MovieTrackingTrack *act_track = BKE_tracking_active_track(tracking);
3010         int unselected;
3011
3012         unselected = RNA_boolean_get(op->ptr, "unselected");
3013
3014         track = tracksbase->first;
3015         while (track) {
3016                 if (unselected == 0 && TRACK_VIEW_SELECTED(sc, track)) {
3017                         track->flag |= TRACK_HIDDEN;
3018                 }
3019                 else if (unselected == 1 && !TRACK_VIEW_SELECTED(sc, track)) {
3020                         track->flag |= TRACK_HIDDEN;
3021                 }
3022
3023                 track = track->next;
3024         }
3025
3026         if (act_track && act_track->flag & TRACK_HIDDEN)
3027                 clip->tracking.act_track = NULL;
3028
3029         if (unselected == 0) {
3030                 /* no selection on screen now, unlock view so it can be scrolled nice again */
3031                 sc->flag &= ~SC_LOCK_SELECTION;
3032         }
3033
3034         BKE_tracking_dopesheet_tag_update(tracking);
3035
3036         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
3037
3038         return OPERATOR_FINISHED;
3039 }
3040
3041 void CLIP_OT_hide_tracks(wmOperatorType *ot)
3042 {
3043         /* identifiers */
3044         ot->name = "Hide Tracks";
3045         ot->description = "Hide selected tracks";
3046         ot->idname = "CLIP_OT_hide_tracks";
3047
3048         /* api callbacks */
3049         ot->exec = hide_tracks_exec;
3050         ot->poll = ED_space_clip_tracking_poll;
3051
3052         /* flags */
3053         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3054
3055         /* properties */
3056         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected tracks");
3057 }
3058
3059 /********************** hide tracks clear operator *********************/
3060
3061 static int hide_tracks_clear_exec(bContext *C, wmOperator *UNUSED(op))
3062 {
3063         SpaceClip *sc = CTX_wm_space_clip(C);
3064         MovieClip *clip = ED_space_clip(sc);
3065         MovieTracking *tracking = &clip->tracking;
3066         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
3067         MovieTrackingTrack *track;
3068
3069         track = tracksbase->first;
3070         while (track) {
3071                 track->flag &= ~TRACK_HIDDEN;
3072
3073                 track = track->next;
3074         }
3075
3076         BKE_tracking_dopesheet_tag_update(tracking);
3077
3078         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
3079
3080         return OPERATOR_FINISHED;
3081 }
3082
3083 void CLIP_OT_hide_tracks_clear(wmOperatorType *ot)
3084 {
3085         /* identifiers */
3086         ot->name = "Hide Tracks Clear";
3087         ot->description = "Clear hide selected tracks";
3088         ot->idname = "CLIP_OT_hide_tracks_clear";
3089
3090         /* api callbacks */
3091         ot->exec = hide_tracks_clear_exec;
3092         ot->poll = ED_space_clip_tracking_poll;
3093
3094         /* flags */
3095         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3096 }
3097
3098 /********************** detect features operator *********************/
3099
3100 static bGPDlayer *detect_get_layer(MovieClip *clip)
3101 {
3102         bGPDlayer *layer;
3103
3104         if (!clip->gpd)
3105                 return NULL;
3106
3107         layer = clip->gpd->layers.first;
3108         while (layer) {
3109                 if (layer->flag & GP_LAYER_ACTIVE)
3110                         return layer;
3111
3112                 layer = layer->next;
3113         }
3114
3115         return NULL;
3116 }
3117
3118 static int detect_features_exec(bContext *C, wmOperator *op)
3119 {
3120         SpaceClip *sc = CTX_wm_space_clip(C);
3121         MovieClip *clip = ED_space_clip(sc);
3122         int clip_flag = clip->flag & MCLIP_TIMECODE_FLAGS;
3123         ImBuf *ibuf = BKE_movieclip_get_ibuf_flag(clip, &sc->user, clip_flag, MOVIECLIP_CACHE_SKIP);
3124         MovieTracking *tracking = &clip->tracking;
3125         ListBase *tracksbase = BKE_tracking_get_tracks(tracking);
3126         MovieTrackingTrack *track = tracksbase->first;
3127         int placement = RNA_enum_get(op->ptr, "placement");
3128         int margin = RNA_int_get(op->ptr, "margin");
3129         int min_trackability = RNA_int_get(op->ptr, "min_trackability");
3130         int min_distance = RNA_int_get(op->ptr, "min_distance");
3131         int place_outside_layer = 0;
3132         bGPDlayer *layer = NULL;
3133
3134         if (placement != 0) {
3135                 layer = detect_get_layer(clip);
3136                 place_outside_layer = placement == 2;
3137         }
3138
3139         /* deselect existing tracks */
3140         while (track) {
3141                 track->flag &= ~SELECT;
3142                 track->pat_flag &= ~SELECT;
3143                 track->search_flag &= ~SELECT;
3144
3145                 track = track->next;
3146         }
3147
3148         BKE_tracking_detect_fast(tracking, tracksbase, ibuf, sc->user.framenr, margin,
3149                                 min_trackability, min_distance, layer, place_outside_layer);
3150
3151         IMB_freeImBuf(ibuf);
3152
3153         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
3154
3155         return OPERATOR_FINISHED;
3156 }
3157
3158 void CLIP_OT_detect_features(wmOperatorType *ot)
3159 {
3160         static EnumPropertyItem placement_items[] = {
3161                         {0, "FRAME",                    0, "Whole Frame",                       "Place markers across the whole frame"},
3162                         {1, "INSIDE_GPENCIL",   0, "Inside grease pencil",      "Place markers only inside areas outlined with grease pencil"},
3163                         {2, "OUTSIDE_GPENCIL",  0, "Outside grease pencil",     "Place markers only outside areas outlined with grease pencil"},
3164                         {0, NULL, 0, NULL, NULL}
3165         };
3166
3167         /* identifiers */
3168         ot->name = "Detect Features";
3169         ot->description = "Automatically detect features and place markers to track";
3170         ot->idname = "CLIP_OT_detect_features";
3171
3172         /* api callbacks */
3173         ot->exec = detect_features_exec;
3174         ot->poll = ED_space_clip_tracking_frame_poll;
3175
3176         /* flags */
3177         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3178
3179         /* properties */
3180         RNA_def_enum(ot->srna, "placement", placement_items, 0, "Placement", "Placement for detected features");
3181         RNA_def_int(ot->srna, "margin", 16, 0, INT_MAX, "Margin", "Only corners further than margin pixels from the image edges are considered", 0, 300);
3182         RNA_def_int(ot->srna, "min_trackability", 16, 0, INT_MAX, "Trackability", "Minimum trackability score to add a corner", 0, 300);
3183         RNA_def_int(ot->srna, "min_distance", 120, 0, INT_MAX, "Distance", "Minimal distance accepted between two corners", 0, 300);
3184 }
3185
3186 /********************** frame jump operator *********************/
3187
3188 static int frame_jump_exec(bContext *C, wmOperator *op)
3189 {
3190         Scene *scene = CTX_data_scene(C);
3191         SpaceClip *sc = CTX_wm_space_clip(C);
3192         MovieClip *clip = ED_space_clip(sc);
3193         MovieTrackingTrack *track;
3194         int pos = RNA_enum_get(op->ptr, "position");
3195         int delta;
3196
3197         if (pos <= 1) { /* jump to path */
3198                 track = BKE_tracking_active_track(&clip->tracking);
3199
3200                 if (!track)
3201                         return OPERATOR_CANCELLED;
3202
3203                 delta = pos == 1 ? 1 : -1;
3204
3205                 while (sc->user.framenr + delta >= SFRA && sc->user.framenr + delta <= EFRA) {
3206                         MovieTrackingMarker *marker = BKE_tracking_exact_marker(track, sc->user.framenr + delta);
3207
3208                         if (!marker || marker->flag & MARKER_DISABLED)
3209                                 break;
3210
3211                         sc->user.framenr += delta;
3212                 }
3213         }
3214         else {  /* to to failed frame */
3215                 if (clip->tracking.reconstruction.flag & TRACKING_RECONSTRUCTED) {
3216                         int a = sc->user.framenr;
3217                         MovieTracking *tracking = &clip->tracking;
3218                         MovieTrackingObject *object = BKE_tracking_active_object(tracking);
3219
3220                         delta = pos == 3 ? 1 : -1;
3221
3222                         a += delta;
3223
3224                         while (a + delta >= SFRA && a + delta <= EFRA) {
3225                                 MovieReconstructedCamera *cam;
3226
3227                                 cam = BKE_tracking_get_reconstructed_camera(tracking, object, a);
3228
3229                                 if (!cam) {
3230                                         sc->user.framenr = a;
3231
3232                                         break;
3233                                 }
3234
3235                                 a += delta;
3236                         }
3237                 }
3238         }
3239
3240         if (CFRA != sc->user.framenr) {
3241                 CFRA = sc->user.framenr;
3242                 sound_seek_scene(CTX_data_main(C), CTX_data_scene(C));
3243
3244                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
3245         }
3246
3247         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
3248
3249         return OPERATOR_FINISHED;
3250 }
3251
3252 void CLIP_OT_frame_jump(wmOperatorType *ot)
3253 {
3254         static EnumPropertyItem position_items[] = {
3255                         {0, "PATHSTART",        0, "Path Start",                "Jump to start of current path"},