// xs_begin
// arg : { var = 'm_top' name = 'color_top' value = '1'   range = '1 255'    step = '1'	precision = '0' }
// arg : { var = 'm_mid' name = 'color_mid' value = '1'   range = '1 255'    step = '1'	precision = '0' }
// xs_end

//===== built-in args =====
// uniform vec3		i_volume_size;		// volume size [1-256]
// uniform float	i_color_index;		// current color index [0-255]
// uniform int		i_num_color_sels;	// number of color selections [1-255]

//===== built-in functions ===== 
// float voxel( vec3 v );				// get voxel color index
// float color_sel( float k );			// get kth selected color index
// vec4 palette( float index );			// get palette color

float noise(int x, int y){
  x %= 25;
  y %= 25;
  int n = x + y * 57;
  n = (n<<13) ^ n;
  float o=1.0f-(float((n*(n*n*int(iArgs[0]) + 789221 ) + 1376312589 ) & 0xFFFFFFFF)/1073741824.0f);
  return o;
}

float snoise(int x, int y){
  float co = (noise(x-1,y-1)+noise(x+1,y-1)+noise(x-1,y+1)+noise(x+1,y+1))/16.0f;
  float si = (noise(x-1,y)+noise(x+1,y)+noise(x,y-1)+noise(x,y+1))/8.0f;
  float ce = noise(x,y)/4.0f;
  return co+si+ce;
}

float cosini(float a, float b, float x){
  float f=(1-cos(x*3.1415927))*0.5f;
  return a*(1-f)+b*f;
}

float inno(float x, float y){
  int intX=int(x);
  float fraX=x-intX;
  int intY=int(y);
  float fraY=y-intY;
  float i1=cosini(snoise(intX,intY),snoise(intX+1,intY),fraX);
  float i2=cosini(snoise(intX,intY+1),snoise(intX+1,intY+1),fraX);
  return cosini(i1,i2,fraY);
}

float pernoi(float x, float y){
  float total=0.;
  for(int i=0;i<=20;i++){
    float freq=pow(float(2),i);
    total+=inno(x*freq,y*freq)*pow(0.45f,i);
  }
  return total;
}

float map( vec3 v ) {
    float col = voxel(v);
    if(col==0){
        return 0;
    }
    float cellSize = 1f/iVolumeSize.z;
    float col_up = voxel( vec3( v.xy, v.z+ 1));
    if(col_up==0){
        return 188+pernoi(0.1f*v.x,0.1f*v.y);
    }
    return 98+pernoi(0.1f*v.x,0.1f*v.y);
}