/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import{deg2rad as t}from"../../../core/mathUtils.js";import{create as o}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{distance as r,sub as a}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{webMercatorToGeographic as n}from"../../../geometry/support/webMercatorUtils.js";import{getWebMercatorScalingFactor as e,adjustHorizonAnglesVec3 as i,convertOrientationToPixelLocation as c,convertSphereVertexToOrientation as s,validatePointsToTransform as f,validateRotationMatrix as m}from"./utils.js";function l(t,o){const{cameraLocation:r,pointsToTransform:a,scalingFactor:n}=g(t,o.cameraLocation,o.rotationMatrix),e=new Array;return h(a,e,{...o,cameraLocation:r,scalingFactor:n,...b(o)}),Array.isArray(t)?e:e[0]}function u(t,o,r){return l(t?o.map(t=>n(t)):o,r).map(t=>({...t,z:1}))}function h(t,r,n){const{affineTransformations:e,cameraLocation:i,focalLengthX:c,focalLengthY:s,principalOffsetPoint:f,radialDistortionCoefficients:m,rotationMatrix:l,scalingFactor:u,tangentialDistortionCoefficients:h}=n;for(const p of t){const t=o();a(t,p,i),t[0]=t[0]/u,t[1]=t[1]/u;const n=-c*((l[0]*t[0]+l[3]*t[1]+l[6]*t[2])/(l[2]*t[0]+l[5]*t[1]+l[8]*t[2])),g=-s*((l[1]*t[0]+l[4]*t[1]+l[7]*t[2])/(l[2]*t[0]+l[5]*t[1]+l[8]*t[2])),y=n*n+g*g;let L=0,A=0,b=0,T=0,w=0,x=0,d=0;m&&(L=m[0]??0,A=m[1]??0,b=m[2]??0),h&&(T=h[0],w=h[1]),f&&(x=f[0]??0,d=f[1]??0);const z=1+L*y+A*y*y+b*y*y*y;let F=n*z+T*(y+2*n**2)+2*w*n*g,N=g*z+w*(y+2*g**2)+2*T*n*g;F+=x,N+=d;const j=Number(e[0])+Number(e[1])*F+Number(e[2])*N,M=Number(e[3])+Number(e[4])*F+Number(e[5])*N;r.push({x:j,y:M})}}function p(t,o){const{imageHeight:a,imageWidth:n,horizonPitch:f,horizonRoll:m,horizonYaw:l}=o,{cameraLocation:u,pointsToTransform:h}=y(t,o.cameraLocation),p=new Array,g=e(u[1],o.cameraLocation.spatialReference);for(const e of h){const t=r([u[0],u[1],u[2]*g],[e[0],e[1],e[2]*g]),o=[(e[0]-u[0])/t,(e[1]-u[1])/t,(e[2]-u[2])*g/t],h=i(o,[f,m,l]);p.push({...s({x:o[0],y:o[1],z:o[2]},1),...c(h[0],h[1],n,a)})}return Array.isArray(t)?p:p[0]}function g(t,o,r){const a=Array.isArray(t)||"items"in t?t:[t];f(a,o),L(a,o),m(r);const n=e(o.y,o.spatialReference);return{pointsToTransform:a.map(t=>t.toArray()),scalingFactor:n,cameraLocation:o.toArray()}}function y(t,o){const r=Array.isArray(t)||"items"in t?t:[t];return f(r,o),L(r,o),{pointsToTransform:r.map(t=>t.toArray()),cameraLocation:o.toArray()}}function L(t,o){if(t.some(t=>!t.spatialReference.equals(o.spatialReference)))throw new Error("Input points and camera location must have the same spatial reference")}function A(t){return null!=t?.focalLength}function b(o){if(A(o))return{focalLengthX:o.focalLength,focalLengthY:o.focalLength};const{imageWidth:r,imageHeight:a,horizontalFieldOfView:n,verticalFieldOfView:e}=o;return{focalLengthX:r/(2*Math.tan(t(n)/2)),focalLengthY:a/(2*Math.tan(t(e)/2))}}export{l as worldToImage,p as worldToImagePanoramic,u as worldToImageWithLTPFlag};
