/******************************************************************************
 * The MIT License (MIT)
 * 
 * Copyright (c) 2014 Baldur Karlsson
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

// compute shaders that figure out the min/max values or histogram in a texture heirarchically
// note that we have to conditionally compile this shader for float/uint/sint as doing that
// dynamically produces a shader with too many temp registers unfortunately.

#extension GL_ARB_compute_shader : require
#extension GL_ARB_shader_storage_buffer_object : require

#if RENDERDOC_TileMinMaxCS

layout(binding=0) writeonly buffer minmaxtiledest
{
#if UINT_TEX
	uvec4 tiles[];
#elif SINT_TEX
	ivec4 tiles[];
#else
	vec4 tiles[];
#endif
} dest;

layout (local_size_x = HGRAM_TILES_PER_BLOCK, local_size_y = HGRAM_TILES_PER_BLOCK) in;

void main()
{
	uvec3 tid = gl_LocalInvocationID;
	uvec3 gid = gl_WorkGroupID;

	int texType = SHADER_RESTYPE;

	uvec3 texDim = uvec3(HistogramTextureResolution);

	uint blocksX = uint(ceil(float(texDim.x)/float(HGRAM_PIXELS_PER_TILE*HGRAM_TILES_PER_BLOCK)));

	uvec2 topleft = (gid.xy*HGRAM_TILES_PER_BLOCK + tid.xy)*HGRAM_PIXELS_PER_TILE;

	uint outIdx = (tid.y*HGRAM_TILES_PER_BLOCK + tid.x) + (gid.y*blocksX + gid.x)*(HGRAM_TILES_PER_BLOCK*HGRAM_TILES_PER_BLOCK);

	int i=0;

#if UINT_TEX
	{
		uvec4 minval = uvec4(0,0,0,0);
		uvec4 maxval = uvec4(0,0,0,0);

		for(uint y=topleft.y; y < min(texDim.y, topleft.y + HGRAM_PIXELS_PER_TILE); y++)
		{
			for(uint x=topleft.x; x < min(texDim.x, topleft.x + HGRAM_PIXELS_PER_TILE); x++)
			{
				uvec4 data = SampleTextureUInt4(vec2(x, y), texType, false,
												HistogramMip, HistogramSlice, HistogramSample);

				if(i == 0)
				{
					minval = maxval = data;
				}
				else
				{
					minval = min(minval, data);
					maxval = max(maxval, data);
				}

				i++;
			}
		}

		dest.tiles[outIdx*2+0] = minval;
		dest.tiles[outIdx*2+1] = maxval;
	}
#elif SINT_TEX
	{
		ivec4 minval = ivec4(0,0,0,0);
		ivec4 maxval = ivec4(0,0,0,0);

		for(uint y=topleft.y; y < min(texDim.y, topleft.y + HGRAM_PIXELS_PER_TILE); y++)
		{
			for(uint x=topleft.x; x < min(texDim.x, topleft.x + HGRAM_PIXELS_PER_TILE); x++)
			{
				ivec4 data = SampleTextureSInt4(vec2(x, y), texType, false,
												HistogramMip, HistogramSlice, HistogramSample);

				if(i == 0)
				{
					minval = maxval = data;
				}
				else
				{
					minval = min(minval, data);
					maxval = max(maxval, data);
				}

				i++;
			}
		}

		dest.tiles[outIdx*2+0] = minval;
		dest.tiles[outIdx*2+1] = maxval;
	}
#else
	{
		vec4 minval = vec4(0,0,0,0);
		vec4 maxval = vec4(0,0,0,0);

		for(uint y=topleft.y; y < min(texDim.y, topleft.y + HGRAM_PIXELS_PER_TILE); y++)
		{
			for(uint x=topleft.x; x < min(texDim.x, topleft.x + HGRAM_PIXELS_PER_TILE); x++)
			{
				vec4 data = SampleTextureFloat4(vec2(x, y), texType, false,
												HistogramMip, HistogramSlice, HistogramSample, HistogramNumSamples);

				if(i == 0)
				{
					minval = maxval = data;
				}
				else
				{
					minval = min(minval, data);
					maxval = max(maxval, data);
				}

				i++;
			}
		}

		dest.tiles[outIdx*2+0] = minval;
		dest.tiles[outIdx*2+1] = maxval;
	}
#endif
}

#endif // #if RENDERDOC_TileMinMaxCS


#if RENDERDOC_ResultMinMaxCS

layout(binding=0) writeonly buffer minmaxresultdest
{
#if UINT_TEX
	uvec4 result[2];
#elif SINT_TEX
	ivec4 result[2];
#else
	vec4 result[2];
#endif
} dest;

layout(binding=1) readonly buffer minmaxtilesrc
{
#if UINT_TEX
	uvec4 tiles[];
#elif SINT_TEX
	ivec4 tiles[];
#else
	vec4 tiles[];
#endif
} src;

layout (local_size_x = 1) in;

void main()
{
	uvec3 texDim = uvec3(HistogramTextureResolution);

	uint blocksX = uint(ceil(float(texDim.x)/float(HGRAM_PIXELS_PER_TILE*HGRAM_TILES_PER_BLOCK)));
	uint blocksY = uint(ceil(float(texDim.y)/float(HGRAM_PIXELS_PER_TILE*HGRAM_TILES_PER_BLOCK)));

#if UINT_TEX
	uvec4 minvalU = src.tiles[0];
	uvec4 maxvalU = src.tiles[1];
#elif SINT_TEX
	ivec4 minvalI = src.tiles[0];
	ivec4 maxvalI = src.tiles[1];
#else
	vec4 minvalF = src.tiles[0];
	vec4 maxvalF = src.tiles[1];
#endif
	
	// i is the tile we're looking at
	for(uint i=1; i < blocksX*blocksY*HGRAM_TILES_PER_BLOCK*HGRAM_TILES_PER_BLOCK; i++)
	{
		uint blockIdx = i/(HGRAM_TILES_PER_BLOCK*HGRAM_TILES_PER_BLOCK);
		uint tileIdx = i%(HGRAM_TILES_PER_BLOCK*HGRAM_TILES_PER_BLOCK);

		// which block and tile is this in
		uvec2 blockXY = uvec2(blockIdx % blocksX, blockIdx / blocksX);
		uvec2 tileXY = uvec2(tileIdx % HGRAM_TILES_PER_BLOCK, tileIdx / HGRAM_TILES_PER_BLOCK);

		// if this is at least partially within the texture, include it.
		if(blockXY.x*(HGRAM_TILES_PER_BLOCK*HGRAM_TILES_PER_BLOCK) + tileXY.x*HGRAM_PIXELS_PER_TILE < texDim.x &&
		   blockXY.y*(HGRAM_TILES_PER_BLOCK*HGRAM_TILES_PER_BLOCK) + tileXY.y*HGRAM_PIXELS_PER_TILE < texDim.y)
		{
#if UINT_TEX
			minvalU = min(minvalU, src.tiles[i*2 + 0]);
			maxvalU = max(maxvalU, src.tiles[i*2 + 1]);
#elif SINT_TEX
			minvalI = min(minvalI, src.tiles[i*2 + 0]);
			maxvalI = max(maxvalI, src.tiles[i*2 + 1]);
#else
			minvalF = min(minvalF, src.tiles[i*2 + 0]);
			maxvalF = max(maxvalF, src.tiles[i*2 + 1]);
#endif
		}
	}
	
#if UINT_TEX
	dest.result[0] = minvalU;
	dest.result[1] = maxvalU;
#elif SINT_TEX
	dest.result[0] = minvalI;
	dest.result[1] = maxvalI;
#else
	dest.result[0] = minvalF;
	dest.result[1] = maxvalF;
#endif
}

#endif // #if RENDERDOC_ResultMinMaxCS

#if RENDERDOC_HistogramCS

layout(binding=0) writeonly buffer minmaxresultdest
{
	uint result[HGRAM_NUM_BUCKETS];
} dest;

layout (local_size_x = HGRAM_TILES_PER_BLOCK, local_size_y = HGRAM_TILES_PER_BLOCK) in;

void main()
{
	uvec3 tid = gl_LocalInvocationID;
	uvec3 gid = gl_WorkGroupID;

	int texType = SHADER_RESTYPE;

	uvec3 texDim = uvec3(HistogramTextureResolution);

	uint blocksX = uint(ceil(float(texDim.x)/float(HGRAM_PIXELS_PER_TILE*HGRAM_TILES_PER_BLOCK)));

	uvec2 topleft = (gid.xy*HGRAM_TILES_PER_BLOCK + tid.xy)*HGRAM_PIXELS_PER_TILE;

	int i=0;

	for(uint y=topleft.y; y < min(texDim.y, topleft.y + HGRAM_PIXELS_PER_TILE); y++)
	{
		for(uint x=topleft.x; x < min(texDim.x, topleft.x + HGRAM_PIXELS_PER_TILE); x++)
		{
			uint bucketIdx = HGRAM_NUM_BUCKETS+1;

#if UINT_TEX
			{
				uvec4 data = SampleTextureUInt4(vec2(x, y), texType, false,
												HistogramMip, HistogramSlice, HistogramSample);

				float divisor = 0.0f;
				uint sum = 0;
				if((HistogramChannels & 0x1) > 0)
				{
					sum += data.x;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x2) > 0)
				{
					sum += data.y;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x4) > 0)
				{
					sum += data.z;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x8) > 0)
				{
					sum += data.w;
					divisor += 1.0f;
				}

				if(divisor > 0.0f)
				{
					float val = float(sum)/divisor;

					float normalisedVal = (val - HistogramMin)/(HistogramMax - HistogramMin);

					if(normalisedVal < 0.0f)
						normalisedVal = 2.0f;

					bucketIdx = uint(floor(normalisedVal*HGRAM_NUM_BUCKETS));
				}
			}
#elif SINT_TEX
			{
				ivec4 data = SampleTextureSInt4(vec2(x, y), texType, false,
												HistogramMip, HistogramSlice, HistogramSample);

				float divisor = 0.0f;
				int sum = 0;
				if((HistogramChannels & 0x1) > 0)
				{
					sum += data.x;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x2) > 0)
				{
					sum += data.y;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x4) > 0)
				{
					sum += data.z;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x8) > 0)
				{
					sum += data.w;
					divisor += 1.0f;
				}

				if(divisor > 0.0f)
				{
					float val = float(sum)/divisor;

					float normalisedVal = (val - HistogramMin)/(HistogramMax - HistogramMin);

					if(normalisedVal < 0.0f)
						normalisedVal = 2.0f;

					bucketIdx = uint(floor(normalisedVal*HGRAM_NUM_BUCKETS));
				}
			}
#else
			{
				vec4 data = SampleTextureFloat4(vec2(x, y), texType, false,
												HistogramMip, HistogramSlice, HistogramSample, HistogramNumSamples);

				float divisor = 0.0f;
				float sum = 0.0f;
				if((HistogramChannels & 0x1) > 0)
				{
					sum += data.x;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x2) > 0)
				{
					sum += data.y;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x4) > 0)
				{
					sum += data.z;
					divisor += 1.0f;
				}
				if((HistogramChannels & 0x8) > 0)
				{
					sum += data.w;
					divisor += 1.0f;
				}

				if(divisor > 0.0f)
				{
					float val = sum/divisor;

					float normalisedVal = (val - HistogramMin)/(HistogramMax - HistogramMin);

					if(normalisedVal < 0.0f)
						normalisedVal = 2.0f;

					bucketIdx = uint(floor(normalisedVal*HGRAM_NUM_BUCKETS));
				}
			}
#endif

			if(bucketIdx >= 0 && bucketIdx < HGRAM_NUM_BUCKETS)
				atomicAdd(dest.result[bucketIdx], 1U);
		}
	}
}

#endif //#if RENDERDOC_HistogramCS
