import torch


def fwd_homography(K_ref, K_tgt, R_tr, t_tr, n_hat, d):
	"""Computes inverse homography matrix between two cameras via a plane.
	Args:
	  K_ref: intrinsics for ref cameras, [..., 3, 3] matrices
	  K_tgt: intrinsics for target cameras, [..., 3, 3] matrices
	  rot: relative rotations from reference to target, [..., 3, 3] matrices
	  t: [..., 3, 1], translations from reference to target camera. Mapping a 3D
		point p from reference to target is accomplished via rot * p + t.
	  n_hat: [..., 1, 3], plane normal w.r.t reference camera frame
	  a: [..., 1, 1], plane equation displacement
	Returns:
	  homography: [..., 3, 3] inverse homography matrices (homographies mapping
		pixel coordinates from target to ref).
	"""
	# print('K_tgt ', K_tgt, K_tgt.size())
	K_tgt_inv = torch.inverse(K_tgt)

	H = R_tr + 1./d * torch.bmm(t_tr, n_hat)

	fwd_h = torch.bmm(torch.bmm(K_ref, H), K_tgt_inv)

	return fwd_h