Draw patterns inside shapes

:question: Have I hidden it too well.

The code is on Grid Collection and
grids
and here now.

function createHexagonGrid( radius, rings ) {
	
	// outer grid radius, rings of hexagons around the central hexagon
	radius = radius !== undefined ? radius : 50;
	rings = rings !== undefined ? rings : 20;
	
	var x, y;
	var r = 2 * radius / ( 2 * rings + 1 ) / Math.sqrt( 3 );	// radius of corner points, size of a single hexagon
	var ri = r * Math.sqrt( 3 ) / 2;							// inner radius of a single hexagon
	var pi6 = Math.PI / 6;
	var hexagonGrid = new THREE.Object3D( );
	var hexagons = [ ];
	
	//var hexagonCount = 3 * rings * rings + 3 * rings + 1;
	
	var geometryHexagon	 = [ ];
	var positions = [ ];
	var uvs = [ ];
	
	var h = 0;
	
	for ( var sg = -1; sg < 2; sg ++ ) {
		
		var rg0 = sg === 0 ? rings : 0;
		
		for( var i = 1, k = 2 * rings + 1 - Math.abs( sg ); k > rings + rg0; i ++, k -- ) {
			
			x = ri * ( 1 - k );
			y = sg * 1.5 * r * i;
			
			for( var j = 0 ; j < k; j ++ ) {
				
				geometryHexagon[ h ] = new THREE.BufferGeometry();
				positions[ h ] = new Float32Array( 18 );
				uvs[ h ] = new Float32Array( 12 );
				geometryHexagon[ h ].addAttribute( 'position', new THREE.BufferAttribute( positions[ h ], 3 ) );
				geometryHexagon[ h ].addAttribute( 'uv', new THREE.BufferAttribute( uvs[ h ], 2 ) );
				
				for( var ip = 0; ip < 6; ip ++ ) {
					
					positions[ h ][ ip * 3 ] = r * Math.cos( ( 2 * ip + 1 ) * pi6 );
					positions[ h ][ ip * 3 + 1 ] = r * Math.sin( ( 2 * ip + 1 ) * pi6 );
					positions[ h ][ ip * 3 + 2 ] = 0;
					
				}
				
				hexagons[ h ] = new THREE.LineLoop( geometryHexagon[ h ], material ); // material is not wireframe - still a grid
				
				for( var iuv = 0; iuv < 6; iuv ++ ) {
					
					hexagons[ h ].geometry.getAttribute( 'uv' ).array[ iuv * 2 ] =  0.5 * ( 1 + ( x + r * Math.cos( ( 2 * iuv + 1 ) * pi6 ) ) / radius ); 
					hexagons[ h ].geometry.getAttribute( 'uv' ).array[ iuv * 2 + 1 ] =  0.5  * ( 1 + ( y + r * Math.cos( ( 2 * iuv + 1 ) * pi6 ) ) / radius );
					
				}
				
				x += ri * 2;
				
				hexagons[ h ].position.set( x, y, 0 );
				hexagonGrid.add( hexagons[ h ] );
				
				h ++;
				
			}
			
		}
		
	}
	
	return hexagonGrid;
	
}

Note - in newer revisions setAttribute instead of addAttribute

3 Likes