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