%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Manipulace s objekty rukou
% hand.pl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init_hand :-
  retractall(hand_move(_, _, _, _)),
  (   test_mode([offline, half_realtime])
  ->  write_begin('generating head_move'),
      begin(B),
      end(E),
      step(S),
      ignore(generate_all_hand_move_step(B, E, S)),
      write_done
  ;   true
  ).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% základní fakta
hand(Time, Camera, Object, Person) :-
	hand(Time, Camera, Object, _, _, _, _, _, _, Person).
hand(Time, Camera, Object, Person, CenterX, CenterY) :-
	hand(Time, Camera, Object, CenterX, CenterY, _, _, _, _, Person).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% vzdálenost mezi dvěma pozicemi stejného objektu
get_hand_move(Time, Step, Camera, Person, Move) :-
  hand(Time, Camera, Object, Person, CenterX, CenterY),
  Time2 is Time + Step,
  hand(Time2, Camera, Object, Person, CenterX2, CenterY2),
  Move is sqrt((CenterX2 - CenterX) ** 2 + (CenterY2 - CenterY) ** 2).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% generování pomocných faktů
generate_all_hand_move_step(Time, End, Step) :-
  (   Time =< End
  ->  ignore(generate_all_hand_move(Time, Step)),
      T is Time + Step,
      generate_all_hand_move_step(T, End, Step)
  ).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
generate_all_hand_move(Time, Step) :-
  forall((bagof(Move, get_hand_move(Time, -Step, Camera, Person, Move), Moves),
	  averlist(Moves, Aver)),
	 assert(hand_move(Time, Camera, Person, Aver))).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% posuny objektů v časovém okně
hand_moves(Time, Step, Window, Camera, Person, Moves):-
  (Window =< 0) -> Moves = [];
  (T is Time + Step,
   W is Window - abs(Step),
   hand_moves(T, Step, W, Camera, Person, M),
   (hand_move(Time, Camera, Person, Move) -> Moves = [Move|M]; Moves = M)
  ).
