
;+
; NAME:
;        sb_3d2pix
; PURPOSE:
;        transforms heliographic or carrington coord. to pixel coord.
; CATEGORY:
;        image processing
; CALLING SEQUENCE:
;        pix = sb_3d2pix(rval,wcs)
; INPUTS:
;        rval = fltarr(3,n). heliographic coordinates [lon,lat,rad]
;               lon,lat: Stonyhurst (earth centered) or Carrington (if /carr).
;               rad: in units of solar radius
;               Can use multiple coord (n gt 1)
;        wcs  = single WCS structure (single structure applied to all pts)
; KEYWORDS (INPUT):
;        /carr  : input is carrington coord. instead of Stonyhurst
; OUTPUTS:
;        pix : fltarr(2,n). Pixel coordinates
; KEYWORDS (OUTPUT):
;        vis : intarr(n).  1 if visible, 0 if hidden behind solar disk
; COMMON BLOCKS:
; SIDE EFFECTS:
; RESTRICTIONS:
; PROCEDURE:
; MODIFICATION HISTORY:
;        JPW, 10/26/2007
;-

FUNCTION sb_3d2pix,rval,wcs,carr=carr,visible=vis

srval = size(rval)
if srval[1] ne 3 || n_elements(wcs) ne 1 then return,-1   ; error
if srval[0] gt 1 then srval=srval[2] else srval=1L

; transform lon,lat,rad to heliocentric-cartesian, in solrad, z towards obs.
d0 = sb_hg2hc(rval[0:1,*],pos=wcs.position,carr=carr,/earth)
for j=0,2 do d0[j,*]=d0[j,*]*rval[2,*]

; check if point visible
vis = intarr(srval)
ww = where(d0[2,*] ge 0.0 or d0[1,*]*d0[1,*]+d0[2,*]*d0[2,*] ge 1.0,nww)
if nww gt 0 then vis[ww]=1

; image pixel coordinates
dsun_solrad = wcs.position.dsun_obs/6.9599d8     ; dist/solrad[m]=dist[solrad]
s2a = (1.8d2*3.6d3/!dpi)/(dsun_solrad - d0[2,*]) ; solrad->arcsec f/each pixel
d0  = [d0[0,*]*s2a,d0[1,*]*s2a]                  ; projected coord in arcsec
pxy = wcs_get_pixel(wcs,d0)                      ; pixel coord

return,pxy

end
