package speiger.src.coreengine.platform.graphics.api.buffer;

public class GrowableVertexBuffer
{
	VertexBuffer buffer;
	final int bytesPerIndex;
	final int limit;
	final int startSize;
	int currentCapacity;
	
	public GrowableVertexBuffer(VertexBuffer buffer, int bytesPerIndex, int limit, int startSize)
	{
		this.buffer = buffer;
		this.bytesPerIndex = bytesPerIndex;
		this.limit = limit;
		this.startSize = startSize;
		currentCapacity = startSize;
		buffer.bind().allocate(startSize * bytesPerIndex).unbind();
	}
	
	public VertexBuffer ensureSize(int capacity)
	{
		if(capacity > currentCapacity)
		{
			if(currentCapacity == limit)
			{
				throw new RuntimeException("THIS SHOULD NEVER HAPPEN!: "+currentCapacity+":"+limit);
			}
			currentCapacity = Math.min(Math.max(currentCapacity + (currentCapacity / 2), capacity), limit);
			buffer.bind().grow(currentCapacity * bytesPerIndex).unbind();
		}
		else if(capacity < currentCapacity / 2 && currentCapacity != 10)
		{
			currentCapacity = Math.max(10, capacity);
			buffer.bind().shrink(currentCapacity * bytesPerIndex).unbind();
		}
		return buffer;
	}
}
