/*******************************************************************************
*
* McXtrace, x-ray tracing package
*         Copyright, All rights reserved
*         DTU Physics, Kgs. Lyngby, Denmark
*         Synchrotron SOLEIL, Saint-Aubin, France
*
* Component: Bragg_crystal_simple
*
* %Identification
*
* Written by: Jose I. Robledo
* Date: February 2016
* Version: $Revision$
* Release: McXtrace 1.2
* Origin: FaMAF - UNC, Argentina
*
* Perfect Bragg reflecting slab
*
* %Description
*
* Rectangle of matter perfectly reflecting the incident X-ray beam
* that fulfills Bragg's law for a set of scattering vectors in the
* vicinity of the theoretical Q given a d-spacing.
* The rectangle is in the x-y plane.
*
* Example: Bragg_crystal_simple( yheight=0.05, xwidth=0.02, DM=3.1356, err_Q= 0.000075, r0=1.0)
*
* %Parameters
* Input parameters:
* xwidth: [m]    Width in the x direction
* yheight: [m]   Height in the y direction
* r0: [ ]        Maximum reflectivity
* DM: [AA⁻1]     d-spacing of the crystal
* err_Q: [ ]     dQ/Q relative error of the modulus of Q vector. Approximates the Darwin width of the crystal.
*
* %End
*******************************************************************************/

DEFINE COMPONENT Bragg_crystal_simple

SETTING PARAMETERS (xmin=1.0,xmax=1.0,ymin=1.0,ymax=1.0,xwidth=0.0,yheight=0.0,r0=1,DM=0,err_Q=0.0001)

/* X-ray parameters: (x,y,z,kx,ky,kz,phi,t,Ex,Ey,Ez,p) */

DECLARE %{
  double Q;
  double dQ;
%}

INITIALIZE %{
  if (DM != 0) {
    Q=2*PI/DM; dQ=Q*err_Q;
  }else{
    fprintf(stderr,"WARNING: Bragg_crystal_simple (%s) d-spacing==0, crystal will ABSORB all X-rays.\n",NAME_CURRENT_COMP);
  }

  if (xwidth>0)  { xmax = xwidth/2;  xmin=-xmax; }
  if (yheight>0) { ymax = yheight/2; ymin=-ymax; }

  if (xmin==xmax || ymin==ymax)
    exit(fprintf(stderr, "Bragg_crystal_simple (%s) : Surface is null (xmin,xmax,ymin,ymax)\n", NAME_CURRENT_COMP));
  %}
TRACE
%{
  double k,e,theta_bragg;

  k=sqrt(kx*kx+ky*ky+kz*kz);
  e=K2E*k*1E-3;
  theta_bragg=atan(kz/ky);

  PROP_Z0; //MOVING TOWARDS THE CRYSTAL.
  if (inside_rectangle(x, y, xwidth, yheight))
  {if (Q>(2*k*sin(theta_bragg)-dQ) && Q<(2*k*sin(theta_bragg)+dQ))
    {kz=-kz;
      SCATTER;
    }else{
      ABSORB;
    }
  }

%}

MCDISPLAY
%{
  /* A bit ugly; hard-coded dimensions. */
  magnify("");
  line(-xwidth/2,-yheight/2,0,xwidth/2,-yheight/2,0);
  line(-xwidth/2,yheight/2,0,xwidth/2,yheight/2,0);
  line(-xwidth/2,-yheight/2,0,-xwidth/2,yheight/2,0);
  line(xwidth/2,-yheight/2,0,xwidth/2,yheight/2,0);

%}

END
