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