package mcmas.core.examples;
import java.nio.ByteBuffer;

import mcmas.core.MCMCommandQueue;
import mcmas.core.MCMContext;
import mcmas.core.MCMKernel;
import mcmas.core.MCMMem;
import mcmas.core.MCMProgram;

import org.jocl.Pointer;
import org.jocl.struct.Buffers;
import org.jocl.struct.SizeofStruct;



public class MCMGridMain {
	
	public static final String source =
		  "#define TOP 50                                                          \n"
		+ "kernel void test_grid(                                                  \n"
		+ "   global Grid * grid)                                                  \n"
		+ "{                                                                       \n"
		+ "   int i = get_global_id(0);                                            \n"
		+ "   int j = get_global_id(1);                                            \n"
		+ "   grid->data[i][j] = i * j;                                            \n"
		+ "}                                                                       \n";
	
	
	public static void main(String[] args) {
		System.out.println(MCMGrid.toOpenCL());
		
		MCMGrid grid = new MCMGrid(10, 12);
		System.out.println(grid);
		
		int gridSize = SizeofStruct.sizeof(grid.getClass());
		ByteBuffer gridBuffer = Buffers.allocateBuffer(grid);
		Buffers.writeToBuffer(gridBuffer, grid);
		
		MCMContext context = new MCMContext();
		//OCLMem gridMem = context.createBuffer(gridSize, OCL.MEM_RW, Pointer.to(gridBuffer));
		MCMMem gridMem = context.newBuffer().Using(gridBuffer).b();
		
		MCMCommandQueue queue = context.createCommandQueue();
		MCMProgram program = context.createProgram(MCMGrid.toOpenCL() + source);
		MCMKernel kernel = program.createKernel("test_grid");
		kernel.setArguments(gridMem);
		
		System.out.println("LAUNCH");
		
		queue.enqueueKernel(kernel, 2,
				new long[] { 0, 0 },
				new long[] { grid.height, grid.width },
				new long[] { 1           , 1 });
		
		System.out.println("READ");
		
		queue.enqueueReadBuffer(gridMem, Pointer.to(gridBuffer), 0, grid.height * grid.width * gridSize);
		
		System.out.println("COPY");
		
		gridBuffer.rewind();
		Buffers.readFromBuffer(gridBuffer, grid);
		
		System.out.println("AFTER");
		System.out.println(grid);
	}

}
