
#include "cuda.h"
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "sdf_gen.cuh"

#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

CUDA_SDF::SDFGenerationContext::~SDFGenerationContext()
{
	cudaFree(data);
	cudaFree(sdf_data);
	//cudaFree(out_data);
	delete[] out_data;
}

void CUDA_SDF::SDFGenerationContext::CopyImage(unsigned char* img_data)
{
	cudaFree(data);
	cudaFree(sdf_data);
	//cudaFree(out_data);
	delete[] out_data;

	size_t img_size = (size_t)width * (size_t)height * (size_t)numComponents;

	cudaMallocManaged(&data, img_size);
	cudaMallocManaged(&sdf_data, img_size * sizeof(float));
	//cudaMallocManaged(&out_data, img_size);
	out_data = new unsigned char[img_size];
	memcpy(data, img_data, img_size);
}

template <typename type>
inline __host__ __device__ type clamp(type d, type min, type max)
{
	const type t = d < min ? min : d;
	return t > max ? max : t;
}

inline __host__ __device__ float distance(int x1, int y1, int x2, int y2)
{
	float x = (float)x2 - (float)x1;
	float y = (float)y2 - (float)y1;

	return sqrt(x * x + y * y);
}

#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))

__global__ void sdf_calc(int width, int height, unsigned char* data, float* out)
{
	int x = threadIdx.x;
	int y = blockIdx.x;
	int stride = blockDim.x;

#define SAMPLE(_x, _y) data[_y * stride + _x]
#define WRITE(_x, _y, val) out[_y * stride + _x] = val

	bool isBaseSample = SAMPLE(x, y) > 0x00;

	const int maxRadius = 16;

	float dist = distance(0, 0, width, height);
	bool foundSample = false;

	for (int ringSize = 1; ringSize <= maxRadius; ringSize++)
	{
		int fromX	= clamp(x - ringSize, 0, width - 1);
		int toX		= clamp(x + ringSize, 0, width - 1);
		int fromY	= clamp(y - ringSize, 0, height - 1);
		int toY		= clamp(y + ringSize, 0, height - 1);

		// ***
		// ---
		// ---
		for (int i = fromX; i <= toX; i++)
		{
			int uv_x = i;
			int uv_y = fromY;

			unsigned char sample = SAMPLE(uv_x, uv_y);
			if (sample > 0 && !isBaseSample || sample == 0 && isBaseSample)
			{
				dist = min(dist, distance(x, y, uv_x, uv_y));
				foundSample = true;
			}
		}

		// ---
		// ---
		// ***
		for (int i = fromX; i <= toX; i++)
		{
			int uv_x = i;
			int uv_y = toY;

			unsigned char sample = SAMPLE(uv_x, uv_y);
			if (sample > 0 && !isBaseSample || sample == 0 && isBaseSample)
			{
				dist = min(dist, distance(x, y, uv_x, uv_y));
				foundSample = true;
			}
		}

		// ---
		// *--
		// ---
		for (int i = fromY + 1; i < toY; i++)
		{
			int uv_x = fromX;
			int uv_y = i;

			unsigned char sample = SAMPLE(uv_x, uv_y);
			if (sample > 0 && !isBaseSample || sample == 0 && isBaseSample)
			{
				dist = min(dist, distance(x, y, uv_x, uv_y));
				foundSample = true;
			}
		}

		// ---
		// --*
		// ---
		for (int i = fromY + 1; i < toY; i++)
		{
			int uv_x = toX;
			int uv_y = i;

			unsigned char sample = SAMPLE(uv_x, uv_y);
			if (sample > 0 && !isBaseSample || sample == 0 && isBaseSample)
			{
				dist = min(dist, distance(x, y, uv_x, uv_y));
				foundSample = true;
			}
		}

		//if (foundSample)
		//{
		//	break;
		//}
	}

	//dist = 1.0f - (dist / (float)maxRadius);
	//dist = clamp(dist, 0.0f, 1.0f);
	if (!isBaseSample)
		dist = -dist;

	WRITE(x, y, dist);

#undef SAMPLE
#undef WRITE
}

void CUDA_SDF::GenerateSDF(SDFGenerationContext& ctx)
{
	printf("Generating signed distance field.\n");

	int numThreads = ctx.width * ctx.height;
	int blockSize = ctx.width;
	int numBlocks = (numThreads + blockSize - 1) / blockSize;
	//add << <numBlocks, blockSize >> > (N, x, y);

	sdf_calc << < numBlocks, blockSize >> > (ctx.width, ctx.height, ctx.data, ctx.sdf_data);

	cudaDeviceSynchronize();

	float maxDist = distance(0, 0, ctx.width, ctx.height);
	float sdf_min = maxDist;
	float sdf_max = -sdf_min;

	for (int i = 0; i < ctx.width * ctx.height; i++)
	{
		const float& val = ctx.sdf_data[i];

		//if the value is not a max distance sample
		if (val > -maxDist && val < maxDist)
		{
			sdf_min = min(sdf_min, val);
			sdf_max = max(sdf_max, val);
		}
	}

	printf("SDF min %f max %f\n", sdf_min, sdf_max);

	float sdf_range = sdf_max - sdf_min;
	for (int i = 0; i < ctx.width * ctx.height; i++)
	{
		const float& val = ctx.sdf_data[i];
		float normalized_val = (val - sdf_min) / sdf_range;
		//float normalized_val = val / sdf_range * 0.5f + 0.5f;
		normalized_val = clamp(normalized_val, 0.0f, 1.0f);
		ctx.out_data[i] = (unsigned char)(normalized_val * 255.0f);
	}
}


	.file	"tmpxft_00344650_00000000-6_sdf_gen.cudafe1.cpp"
	.text
#APP

#NO_APP
	.type	_ZL26__cudaUnregisterBinaryUtilv, @function
_ZL26__cudaUnregisterBinaryUtilv:
.LFB2036:
	.cfi_startproc
	endbr64
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	jmp	__cudaUnregisterFatBinary@PLT
	.cfi_endproc
.LFE2036:
	.size	_ZL26__cudaUnregisterBinaryUtilv, .-_ZL26__cudaUnregisterBinaryUtilv
	.align 2
	.globl	_ZN8CUDA_SDF20SDFGenerationContextD2Ev
	.type	_ZN8CUDA_SDF20SDFGenerationContextD2Ev, @function
_ZN8CUDA_SDF20SDFGenerationContextD2Ev:
.LFB2028:
	.cfi_startproc
	.cfi_personality 0x9b,DW.ref.__gxx_personality_v0
	.cfi_lsda 0x1b,.LLSDA2028
	endbr64
	pushq	%rbx
	.cfi_def_cfa_offset 16
	.cfi_offset 3, -16
	movq	%rdi, %rbx
	movq	16(%rdi), %rdi
	call	cudaFree@PLT
	movq	24(%rbx), %rdi
	call	cudaFree@PLT
	movq	32(%rbx), %rdi
	testq	%rdi, %rdi
	je	.L2
	popq	%rbx
	.cfi_remember_state
	.cfi_def_cfa_offset 8
	jmp	_ZdaPv@PLT
.L2:
	.cfi_restore_state
	popq	%rbx
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2028:
	.globl	__gxx_personality_v0
	.section	.gcc_except_table,"a",@progbits
.LLSDA2028:
	.byte	0xff
	.byte	0xff
	.byte	0x1
	.uleb128 .LLSDACSE2028-.LLSDACSB2028
.LLSDACSB2028:
.LLSDACSE2028:
	.text
	.size	_ZN8CUDA_SDF20SDFGenerationContextD2Ev, .-_ZN8CUDA_SDF20SDFGenerationContextD2Ev
	.globl	_ZN8CUDA_SDF20SDFGenerationContextD1Ev
	.set	_ZN8CUDA_SDF20SDFGenerationContextD1Ev,_ZN8CUDA_SDF20SDFGenerationContextD2Ev
	.align 2
	.globl	_ZN8CUDA_SDF20SDFGenerationContext9CopyImageEPh
	.type	_ZN8CUDA_SDF20SDFGenerationContext9CopyImageEPh, @function
_ZN8CUDA_SDF20SDFGenerationContext9CopyImageEPh:
.LFB2030:
	.cfi_startproc
	endbr64
	pushq	%r12
	.cfi_def_cfa_offset 16
	.cfi_offset 12, -16
	movq	%rsi, %r12
	pushq	%rbp
	.cfi_def_cfa_offset 24
	.cfi_offset 6, -24
	pushq	%rbx
	.cfi_def_cfa_offset 32
	.cfi_offset 3, -32
	movq	%rdi, %rbx
	movq	16(%rdi), %rdi
	call	cudaFree@PLT
	movq	24(%rbx), %rdi
	call	cudaFree@PLT
	movq	32(%rbx), %rdi
	testq	%rdi, %rdi
	je	.L7
	call	_ZdaPv@PLT
.L7:
	movslq	4(%rbx), %rax
	movslq	(%rbx), %rbp
	leaq	16(%rbx), %rdi
	movl	$1, %edx
	imulq	%rax, %rbp
	movslq	8(%rbx), %rax
	imulq	%rax, %rbp
	movq	%rbp, %rsi
	call	cudaMallocManaged@PLT
	leaq	24(%rbx), %rdi
	movl	$1, %edx
	leaq	0(,%rbp,4), %rsi
	call	cudaMallocManaged@PLT
	movq	%rbp, %rdi
	call	_Znam@PLT
	movq	16(%rbx), %rdi
	movq	%r12, %rsi
	movq	%rbp, %rcx
	movq	%rax, 32(%rbx)
	rep movsb
	popq	%rbx
	.cfi_def_cfa_offset 24
	popq	%rbp
	.cfi_def_cfa_offset 16
	popq	%r12
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2030:
	.size	_ZN8CUDA_SDF20SDFGenerationContext9CopyImageEPh, .-_ZN8CUDA_SDF20SDFGenerationContext9CopyImageEPh
	.globl	_Z31__device_stub__Z8sdf_calciiPhPfiiPhPf
	.type	_Z31__device_stub__Z8sdf_calciiPhPfiiPhPf, @function
_Z31__device_stub__Z8sdf_calciiPhPfiiPhPf:
.LFB2058:
	.cfi_startproc
	endbr64
	subq	$152, %rsp
	.cfi_def_cfa_offset 160
	movl	%edi, 28(%rsp)
	leaq	56(%rsp), %rdi
	movl	%esi, 24(%rsp)
	leaq	68(%rsp), %rsi
	movq	%rdx, 16(%rsp)
	leaq	40(%rsp), %rdx
	movq	%rcx, 8(%rsp)
	leaq	48(%rsp), %rcx
	movq	%fs:40, %rax
	movq	%rax, 136(%rsp)
	xorl	%eax, %eax
	leaq	28(%rsp), %rax
	movl	$1, 64(%rsp)
	movq	%rax, 104(%rsp)
	leaq	24(%rsp), %rax
	movq	%rax, 112(%rsp)
	leaq	16(%rsp), %rax
	movq	%rax, 120(%rsp)
	leaq	8(%rsp), %rax
	movq	%rax, 128(%rsp)
	movabsq	$4294967297, %rax
	movq	%rax, 56(%rsp)
	movq	%rax, 68(%rsp)
	movl	$1, 76(%rsp)
	call	__cudaPopCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L12
	pushq	48(%rsp)
	.cfi_def_cfa_offset 168
	leaq	_Z8sdf_calciiPhPf(%rip), %rdi
	pushq	48(%rsp)
	.cfi_def_cfa_offset 176
	movq	84(%rsp), %rcx
	movl	92(%rsp), %r8d
	movq	72(%rsp), %rsi
	movl	80(%rsp), %edx
	leaq	120(%rsp), %r9
	call	cudaLaunchKernel@PLT
	popq	%rax
	.cfi_def_cfa_offset 168
	popq	%rdx
	.cfi_def_cfa_offset 160
.L12:
	movq	136(%rsp), %rax
	subq	%fs:40, %rax
	je	.L14
	call	__stack_chk_fail@PLT
.L14:
	addq	$152, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2058:
	.size	_Z31__device_stub__Z8sdf_calciiPhPfiiPhPf, .-_Z31__device_stub__Z8sdf_calciiPhPfiiPhPf
	.globl	_Z8sdf_calciiPhPf
	.type	_Z8sdf_calciiPhPf, @function
_Z8sdf_calciiPhPf:
.LFB2059:
	.cfi_startproc
	endbr64
	jmp	_Z31__device_stub__Z8sdf_calciiPhPfiiPhPf
	.cfi_endproc
.LFE2059:
	.size	_Z8sdf_calciiPhPf, .-_Z8sdf_calciiPhPf
	.section	.rodata.str1.1,"aMS",@progbits,1
.LC2:
	.string	"Generating signed distance field.\n"
.LC4:
	.string	"SDF min %f max %f\n"
	.text
	.globl	_ZN8CUDA_SDF11GenerateSDFERNS_20SDFGenerationContextE
	.type	_ZN8CUDA_SDF11GenerateSDFERNS_20SDFGenerationContextE, @function
_ZN8CUDA_SDF11GenerateSDFERNS_20SDFGenerationContextE:
.LFB2033:
	.cfi_startproc
	endbr64
	pushq	%r12
	.cfi_def_cfa_offset 16
	.cfi_offset 12, -16
	leaq	.LC2(%rip), %rsi
	xorl	%eax, %eax
	pushq	%rbp
	.cfi_def_cfa_offset 24
	.cfi_offset 6, -24
	pushq	%rbx
	.cfi_def_cfa_offset 32
	.cfi_offset 3, -32
	movq	%rdi, %rbx
	movl	$2, %edi
	subq	$48, %rsp
	.cfi_def_cfa_offset 80
	call	__printf_chk@PLT
	movl	(%rbx), %ecx
	movl	4(%rbx), %eax
	xorl	%r9d, %r9d
	xorl	%r8d, %r8d
	imull	%ecx, %eax
	movl	%ecx, 36(%rsp)
	leal	-1(%rcx,%rax), %eax
	cltd
	idivl	%ecx
	movabsq	$4294967297, %rdx
	movq	%rdx, 28(%rsp)
	movl	32(%rsp), %esi
	movq	%rdx, 40(%rsp)
	movl	44(%rsp), %ecx
	movq	36(%rsp), %rdx
	movl	%eax, 24(%rsp)
	movq	24(%rsp), %rdi
	call	__cudaPushCallConfiguration@PLT
	testl	%eax, %eax
	je	.L18
.L20:
	call	cudaDeviceSynchronize@PLT
	movl	4(%rbx), %ebp
	movl	(%rbx), %r12d
	cvtsi2ssl	%ebp, %xmm1
	cvtsi2ssl	%r12d, %xmm0
	imull	%r12d, %ebp
	mulss	%xmm1, %xmm1
	mulss	%xmm0, %xmm0
	addss	%xmm1, %xmm0
	call	sqrtf@PLT
	xorl	%eax, %eax
	movaps	%xmm0, %xmm4
	xorps	.LC3(%rip), %xmm4
	movaps	%xmm0, %xmm3
	movaps	%xmm4, %xmm2
	jmp	.L19
.L18:
	movq	24(%rbx), %rcx
	movq	16(%rbx), %rdx
	movl	4(%rbx), %esi
	movl	(%rbx), %edi
	call	_Z31__device_stub__Z8sdf_calciiPhPfiiPhPf
	jmp	.L20
.L27:
	movq	24(%rbx), %rdx
	movss	(%rdx,%rax,4), %xmm1
	comiss	%xmm4, %xmm1
	ja	.L39
.L21:
	incq	%rax
.L19:
	cmpl	%eax, %ebp
	jg	.L27
	jmp	.L40
.L39:
	comiss	%xmm1, %xmm0
	jbe	.L21
	minss	%xmm1, %xmm3
	maxss	%xmm1, %xmm2
	jmp	.L21
.L40:
	movl	$2, %edi
	movb	$2, %al
	cvtss2sd	%xmm2, %xmm1
	leaq	.LC4(%rip), %rsi
	movss	%xmm3, 12(%rsp)
	cvtss2sd	%xmm3, %xmm0
	movss	%xmm2, 8(%rsp)
	call	__printf_chk@PLT
	movss	8(%rsp), %xmm2
	xorl	%eax, %eax
	xorps	%xmm1, %xmm1
	movss	12(%rsp), %xmm3
	movss	.LC0(%rip), %xmm4
	movss	.LC5(%rip), %xmm5
	subss	%xmm3, %xmm2
.L28:
	movl	(%rbx), %edx
	imull	4(%rbx), %edx
	cmpl	%eax, %edx
	jle	.L41
	movq	24(%rbx), %rdx
	movss	(%rdx,%rax,4), %xmm0
	subss	%xmm3, %xmm0
	divss	%xmm2, %xmm0
	comiss	%xmm0, %xmm1
	ja	.L34
	movaps	%xmm4, %xmm6
	minss	%xmm0, %xmm6
	movaps	%xmm6, %xmm0
	jmp	.L29
.L34:
	xorps	%xmm0, %xmm0
.L29:
	mulss	%xmm5, %xmm0
	movq	32(%rbx), %rdx
	cvttss2sil	%xmm0, %ecx
	movb	%cl, (%rdx,%rax)
	incq	%rax
	jmp	.L28
.L41:
	addq	$48, %rsp
	.cfi_def_cfa_offset 32
	popq	%rbx
	.cfi_def_cfa_offset 24
	popq	%rbp
	.cfi_def_cfa_offset 16
	popq	%r12
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2033:
	.size	_ZN8CUDA_SDF11GenerateSDFERNS_20SDFGenerationContextE, .-_ZN8CUDA_SDF11GenerateSDFERNS_20SDFGenerationContextE
	.section	.rodata.str1.1
.LC6:
	.string	"_Z8sdf_calciiPhPf"
	.section	.text.startup,"ax",@progbits
	.type	_ZL24__sti____cudaRegisterAllv, @function
_ZL24__sti____cudaRegisterAllv:
.LFB2061:
	.cfi_startproc
	endbr64
	pushq	%rax
	.cfi_def_cfa_offset 16
	leaq	_ZL15__fatDeviceText(%rip), %rdi
	call	__cudaRegisterFatBinary@PLT
	pushq	$0
	.cfi_def_cfa_offset 24
	xorl	%r9d, %r9d
	orl	$-1, %r8d
	pushq	$0
	.cfi_def_cfa_offset 32
	leaq	.LC6(%rip), %rdx
	movq	%rax, %rdi
	leaq	_Z8sdf_calciiPhPf(%rip), %rsi
	pushq	$0
	.cfi_def_cfa_offset 40
	movq	%rdx, %rcx
	pushq	$0
	.cfi_def_cfa_offset 48
	movq	%rax, _ZL20__cudaFatCubinHandle(%rip)
	call	__cudaRegisterFunction@PLT
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	addq	$32, %rsp
	.cfi_def_cfa_offset 16
	call	__cudaRegisterFatBinaryEnd@PLT
	leaq	_ZL26__cudaUnregisterBinaryUtilv(%rip), %rdi
	popq	%rdx
	.cfi_def_cfa_offset 8
	jmp	atexit@PLT
	.cfi_endproc
.LFE2061:
	.size	_ZL24__sti____cudaRegisterAllv, .-_ZL24__sti____cudaRegisterAllv
	.section	.init_array,"aw"
	.align 8
	.quad	_ZL24__sti____cudaRegisterAllv
	.section	.nvFatBinSegment,"aw"
	.align 8
	.type	_ZL15__fatDeviceText, @object
	.size	_ZL15__fatDeviceText, 24
_ZL15__fatDeviceText:
	.long	1180844977
	.long	1
	.quad	fatbinData
	.quad	0
	.local	_ZL20__cudaFatCubinHandle
	.comm	_ZL20__cudaFatCubinHandle,8,8
	.section	.rodata.cst4,"aM",@progbits,4
	.align 4
.LC0:
	.long	1065353216
	.section	.rodata.cst16,"aM",@progbits,16
	.align 16
.LC3:
	.long	-2147483648
	.long	0
	.long	0
	.long	0
	.section	.rodata.cst4
	.align 4
.LC5:
	.long	1132396544
	.hidden	DW.ref.__gxx_personality_v0
	.weak	DW.ref.__gxx_personality_v0
	.section	.data.rel.local.DW.ref.__gxx_personality_v0,"awG",@progbits,DW.ref.__gxx_personality_v0,comdat
	.align 8
	.type	DW.ref.__gxx_personality_v0, @object
	.size	DW.ref.__gxx_personality_v0, 8
DW.ref.__gxx_personality_v0:
	.quad	__gxx_personality_v0
	.ident	"GCC: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0"
	.section	.note.GNU-stack,"",@progbits
	.section	.note.gnu.property,"a"
	.align 8
	.long	1f - 0f
	.long	4f - 1f
	.long	5
0:
	.string	"GNU"
1:
	.align 8
	.long	0xc0000002
	.long	3f - 2f
2:
	.long	0x3
3:
	.align 8
4:


#include <stdio.h>


#ifndef _SDF_GEN_H_
#define _SDF_GEN_H_
#pragma once
#include <hip/hip_runtime.h>


namespace CUDA_SDF
{
	struct SDFGenerationContext
	{
		int width = 0;
		int height = 0;
		int numComponents = 1;

		unsigned char* data = nullptr;
		float* sdf_data = nullptr;
		unsigned char* out_data = nullptr;

		~SDFGenerationContext();


		void CopyImage(unsigned char* img_data);
	};

	void GenerateSDF(SDFGenerationContext& ctx);
}

#endif
	.text
	.file	"sdf_gen.hip"
	.type	__hip_cuid_,@object             # @__hip_cuid_
	.bss
	.globl	__hip_cuid_
__hip_cuid_:
	.byte	0                               # 0x0
	.size	__hip_cuid_, 1

	.ident	"AMD clang version 18.0.0git (https://github.com/RadeonOpenCompute/llvm-project roc-6.3.2 25012 e5bf7e55c91490b07c49d8960fa7983d864936c4)"
	.section	".note.GNU-stack","",@progbits
	.addrsig
	.addrsig_sym __hip_cuid_

	.text
	.p2alignl 7, 3214868480
	.fill 96, 4, 3214868480
	.type	__hip_cuid_,@object             ; @__hip_cuid_
	.section	.bss,"aw",@nobits
	.globl	__hip_cuid_
__hip_cuid_:
	.byte	0                               ; 0x0
	.size	__hip_cuid_, 1

	.ident	"AMD clang version 18.0.0git (https://github.com/RadeonOpenCompute/llvm-project roc-6.3.2 25012 e5bf7e55c91490b07c49d8960fa7983d864936c4)"
	.section	".note.GNU-stack","",@progbits
	.addrsig
	.addrsig_sym __hip_cuid_
	.amdgcn_target "amdgcn-amd-amdhsa--gfx1100"
	.amdgpu_metadata
---
amdhsa.kernels:  []
amdhsa.target:   amdgcn-amd-amdhsa--gfx1100
amdhsa.version:
  - 1
  - 2
...

	.end_amdgpu_metadata
