VOXMesh constructor

VOXMesh(
  1. Chunk chunk
)

Implementation

factory VOXMesh(Chunk chunk){
	final data = chunk.data;
	final size = chunk.size;
	final palette = chunk.palette;

	final List<double> vertices = [];
	final List<double> colors = [];

	const nx = [ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1 ];
	const px = [ 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0 ];
	const py = [ 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1 ];
	const ny = [ 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0 ];
	const nz = [ 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0 ];
	const pz = [ 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1 ];

	final color = Color();

	void add( tile, x, y, z, r, g, b ) {
		x -= size.x / 2;
		y -= size.z / 2;
		z += size.y / 2;

		for (int i = 0; i < 18; i += 3 ) {
			color.setRGB( r, g, b, ColorSpace.srgb );

			vertices.addAll([ tile[ i + 0 ] + x, tile[ i + 1 ] + y, tile[ i + 2 ] + z ]);
			colors.addAll([ color.red, color.green, color.blue ]);
		}
	}

	// Store data in a volume for sampling

	final offsety = size.x.toInt();
	final offsetz = (size.x * size.y).toInt();

	final array = Uint8List( (size.x * size.y * size.z).toInt() );

	for (int j = 0; j < data!.length; j += 4 ) {
		final x = data[ j + 0 ];
		final y = data[ j + 1 ];
		final z = data[ j + 2 ];
		final index = (x + ( y * offsety ) + ( z * offsetz )).toInt();

		array[ index ] = 255;
	}

	// Construct geometry

	bool hasColors = false;

	for (int j = 0; j < data.length; j += 4 ) {
		final x = data[ j + 0 ];
		final y = data[ j + 1 ];
		final z = data[ j + 2 ];
		final c = data[ j + 3 ];

		final hex = palette![ c ];
		final r = ( hex >> 0 & 0xff ) / 0xff;
		final g = ( hex >> 8 & 0xff ) / 0xff;
		final b = ( hex >> 16 & 0xff ) / 0xff;

		if ( r > 0 || g > 0 || b > 0 ) hasColors = true;
		final index = (x + ( y * offsety ) + ( z * offsetz )).toInt();

		if ( array[ index + 1 ] == 0 || x == size.x - 1 ) add( px, x, z, - y, r, g, b );
		if ((index - 1 > 0 && array[ index - 1 ] == 0) || x == 0 ) add( nx, x, z, - y, r, g, b );
		if ( array[ index + offsety ] == 0 || y == size.y - 1 ) add( ny, x, z, - y, r, g, b );
		if ((index - offsety > 0 && array[ index - offsety ] == 0) || y == 0 ) add( py, x, z, - y, r, g, b );
		if ( array[ index + offsetz ] == 0 || z == size.z - 1 ) add( pz, x, z, - y, r, g, b );
		if((index - offsetz > 0 && array[ index - offsetz ] == 0) || z == 0) add( nz, x, z, - y, r, g, b );
	}

	final geometry = BufferGeometry();
	geometry.setAttributeFromString( 'position', Float32BufferAttribute.fromList( vertices, 3 ) );
	geometry.computeVertexNormals();

	final material = MeshStandardMaterial();

	if ( hasColors ) {

		geometry.setAttributeFromString( 'color', Float32BufferAttribute.fromList( colors, 3 ) );
		material.vertexColors = true;

	}

	return VOXMesh.create( geometry, material );
}