IndexBuffer TerrainTessellator::createPatchIndexBuffer(const GraphicsDevice& device, unsigned levelOfDetail)
{
	// distance between two neighbor vertices
	int delta = MathHelper::pow2(levelOfDetail);

	// size of grid in current lod (e.g. lod 0: 64, lod 1: 32)
	int lodSize = size / delta;

	// main indices + skirt indices
	int numIndices = lodSize * lodSize * 6;

	IndexCollection indices(numIndices);

	int count = 0;

	unsigned interval = min(stripeSize * delta, size);

	// init main indices
	for (unsigned i = 0; i < size / interval; ++i)
		for (unsigned row = 0; row < size; row += delta)
			for (unsigned col = i * interval; col < (i+1) * interval; col += delta)
				initQuadIndices(row, col, delta, delta, &indices, &count);

	IndexBuffer indexBuffer = device.createIndexBuffer(sizeof(TerrainIndex) * numIndices, indexFormat, D3DUSAGE_WRITEONLY);

	indexBuffer.setData(indices);

	return indexBuffer;
}
IndexBuffer TerrainTessellator::createSkirtIndexBuffer(const GraphicsDevice& device, unsigned levelOfDetail)
{
	// distance between two neighbor vertices
	int delta = MathHelper::pow2(levelOfDetail);

	// size of grid in current lod (e.g. lod 0: 64, lod 1: 32)
	int lodSize = size / delta;

	// main indices + skirt indices
	int numIndices = lodSize * 4 * 6;

	IndexCollection indices(numIndices);

	int count = 0;

	int interval = min(stripeSize * delta, size);

	// init skirt indices
	for (int i = 0; i < 2; ++i)
		for (int j = 0; j < 2; ++j)
			for (unsigned row = 0; row < (i ? size : 1); row += delta)
				for (unsigned col = 0; col < (i ? 1 : size); col += delta)
				{
					int r = i ? row : -1 + j * (size + 1);
					int c = i ? -1 + j * (size + 1) : col;

					int deltaCol = i ? 1 : delta;
					int deltaRow = i ? delta : 1;

					initQuadIndices(r, c, deltaRow, deltaCol, &indices, &count);
				}

	IndexBuffer indexBuffer = device.createIndexBuffer(sizeof(TerrainIndex) * numIndices, indexFormat, D3DUSAGE_WRITEONLY);

	indexBuffer.setData(indices);

	return indexBuffer;
}