#include "stdafx.h"
#include "math.h"
#include "BemRaw.h"

#include "geom.h"
#include "BemRawDoc.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CBemRawDoc-function for integration

/*---------------------------------------------------------*/
/*  INVEL - analytical integration of velocity             */
/*---------------------------------------------------------*/
void CBemRawDoc::InVel (double xp,double yp,double x1,double y1,double x2,double y2,double& hx,double& hy,double& gx,double& gy,double tt)
{
 	double ra,rb,r,la,lb,nx,ny,d,xob,ko,eo,a2,b2,c2,fa,fb,
   		yoa,yob,dx1,dx2,dy2,dy1,s2,pi=3.14159265,pi2;
 	pi2=pi*0.5;
 	dx1=x1-x2;dy1=y1-y2;
 	c2=dx1*dx1+dy1*dy1;
 	dx1=x1-xp;dx2=x2-xp;dy1=y1-yp;dy2=y2-yp;
 	a2=dx1*dx1+dy1*dy1;
 	b2=dx2*dx2+dy2*dy2;
 	ra=sqrt(a2);rb=sqrt(b2);r=sqrt(c2);
 	la=log(ra);lb=log(rb);
 	ny=(x1-x2)/r;nx=(y2-y1)/r;
 	xob=x2*nx+y2*ny;ko=xp*nx+yp*ny;
 	d=xob-ko;
 	yoa=-ny*x1+nx*y1;
 	yob=-ny*x2+nx*y2;eo=-ny*xp+nx*yp;
 	if (fabs(d)<1e-10)
	{
		rb=yob-eo;ra=yoa-eo;
  		gx=(lb-la)*ny;
  		gy=-nx*(lb-la);
  		hx=hy=0.0;
 		gx*=tt;gy*=tt;
	}
	else
	{
 		fb=atan2 (yob-eo,d);fa=atan2 (yoa-eo,d);
 		if (fabs(fa)==pi2||fabs(fb)==pi2)
		{
			rb=yob-eo;ra=yoa-eo;
  			gx=(lb-la)*ny;
  			gy=-nx*(lb-la);
  			hx=hy=0.0;
 			gx*=tt;gy*=tt;
		}
		else
		{
 			s2=fa-fb;
 			gx=nx*s2+ny*(lb-la);
 			gy=ny*s2-nx*(lb-la);
 			hx=dy2/b2-dy1/a2;
 			hy=-dx2/b2+dx1/a2;
 			hx*=tt;hy*=tt;
 			gx*=tt;gy*=tt;
		}
	}
}

void CBemRawDoc::Veloc (double& vx,double& vy,float xb,float yb)
{
	int j,i1,i2;
	float x1,y1,x2,y2,qq,sx,sy,dx,dy,rb,ra,ybb;
	double ax,ay,bx,by;
	ybb=yb*txy;
	vx=vy=0.0;
	for (j=0;j<nel;j++)
    {
     	CElement* el=GetElement(j);
		i1=el->nod1;i2=el->nod2;
		CNode* nd1=GetNode(i1);CNode* nd2=GetNode(i2);
		x1=nd1->xb;y1=nd1->yb*txy;
		x2=nd2->xb;y2=nd2->yb*txy;
     	InVel (xb,ybb,x1,y1,x2,y2,ax,ay,bx,by,tt);
     	vx+=el->der*bx-el->pot*ax;
     	vy+=el->der*by-el->pot*ay;
    }
    if (nwl>0)
    {
    	sx=sy=0.0;
     	for (j=0;j<nwl;j++)
     	{             
			CWell* wl=GetWell(j);
      		dx=xb-wl->xz;dy=ybb-wl->yz*txy;
      		rb=dx*dx+dy*dy;
       		qq=-wl->yield/tx;
      		ra=1.0f/(float)sqrt(rb);
      		sx+=qq*dx/rb;sy+=qq*dy/rb;
     	}
     	vx+=sx;vy+=sy;
    }
   	vx*=tp*kx;vy*=tp*ky*txy;
}
