Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas id="canvas"></canvas>
<img id="imgSave"></img>
              
            
!

CSS

              
                html{background:#ccc;}

#imgSave{
  -moz-box-shadow:    1px 2px 3px 1px #000;
  -webkit-box-shadow: 1px 2px 3px 1px #000;
  box-shadow:         1px 2px 3px 1px #000;
}

canvas{display:none;}
              
            
!

JS

              
                window.onload = terrainGeneration;

class HeightMap {
    constructor(mapDimension = 256, unitSize = 1, roughness = 8, tile = false) {
        this.mapDimension = mapDimension;
        this.unitSize = unitSize;
        this.roughness = roughness;
        this.tile = true;

        this.map = Array(mapDimension + 1).fill(0).map(el => new Array(mapDimension + 1).fill(0).map(el => 0));
        this.startDisplacement();
    }

    get mapData() {
        return this.map;
    }

    // Starts off the map generation, seeds the first 4 corners
    startDisplacement = () => {
        const {map, mapDimension, tile} = this;

        // top left
        map[0][0] = Math.random();

        // bottom left
        map[0][mapDimension] = Math.random();

        // top right
        map[mapDimension][0] = Math.random();

        // bottom right
        map[mapDimension][mapDimension] = Math.random();

        // Center
        map[mapDimension / 2][mapDimension / 2] = map[0][0] + map[0][mapDimension] + map[mapDimension][0] + map[mapDimension][mapDimension] / 4;
        map[mapDimension / 2][mapDimension / 2] = this.normalize(map[mapDimension / 2][mapDimension / 2]);

        this.midpointDisplacment(mapDimension);
    }

    midpointDisplacment = (plot) => {
        const {map, mapDimension, unitSize} = this;

        const subPlot = plot / 2;

        if (subPlot > unitSize){
            for (let i = subPlot; i <= mapDimension; i += subPlot) {
                for (let j = subPlot; j <= mapDimension; j += subPlot) {
                    const x = i - (subPlot / 2);
                    const y = j - (subPlot / 2);

                    const topLeft = map[i - subPlot][j - subPlot];
                    const topRight = map[i][j - subPlot];
                    const bottomLeft = map[i - subPlot][j];
                    const bottomRight = map[i][j];

                    // Center
                    map[x][y] = (topLeft + topRight + bottomLeft + bottomRight) / 4 + this.displace(plot);
                    map[x][y] = this.normalize(map[x][y]);

                    const center = map[x][y];

                    // Top
                    const top = topLeft + topRight + center;

                    if (j > subPlot) {
                        map[x][j - subPlot] = (top + map[x][j - plot + (subPlot / 2)]) / 4 + this.displace(plot);
                    } else {
                        map[x][j - subPlot] = top / 3 + this.displace(plot);
                    }

                    map[x][j - subPlot] = this.normalize(map[x][j - subPlot]);

                    // Bottom
                    const bottom = bottomLeft + bottomRight + center;

                    if (j < mapDimension) {
                        map[x][j] = (bottom + map[x][j + (subPlot / 2)]) / 4 + this.displace(plot);
                    } else {
                        map[x][j] = bottom / 3 + this.displace(plot);
                    }

                    map[x][j] = this.normalize(map[x][j]);

                    //Right
                    const right = topRight + bottomRight + center;

                    if(i < mapDimension){
                        map[i][y] = (right + map[i + (subPlot / 2)][y]) / 4 + this.displace(plot);
                    } else {
                        map[i][y] = right / 3 + this.displace(plot);
                    }

                    map[i][y] = this.normalize(map[i][y]);

                    // Left
                    const left = topLeft + bottomLeft + center;

                    if(i > subPlot){
                        map[i - subPlot][y] = (left + map[i - plot + (subPlot / 2)][y]) / 4 + this.displace(plot);
                    } else {
                        map[i - subPlot][y] = left / 3 + this.displace(plot);
                    }

                    map[i - subPlot][y] = this.normalize(map[i - subPlot][y]);
                }
            }

            this.midpointDisplacment(subPlot);
        }
    }

    // Random function to offset the center
    displace = (amount) => {
        const { mapDimension, roughness } = this;
        const max = amount / ( mapDimension * 2 ) * roughness;
        return (Math.random() - 0.5) * max;
    }

    // Normalize the value to make sure its within bounds
    normalize = (value) => {
        return Math.max(Math.min(value, 1), 0);
    }
}


var mapCanvas = document.getElementById('canvas'),
    imgSave = document.getElementById('imgSave'),
    settings = {
      roughness : 8,
      mapDimension : 256,
      unitSize : 1,
      mapType : 1,
      genShadows : false,
      sunX : 1000,
      sunY : 1000,
      sunZ : 4,
      render : function(){
        terrainGeneration();
      }
    };

function terrainGeneration(){
  "use strict";
  // Set these variables to adjust how the map is generated
  var mapDimension,
      unitSize, // Power of 2
      roughness,
      genPerspective,
      genShadows, 
      sunX = settings.sunX, sunY = settings.sunY, sunZ = settings.sunZ,
      mapType,
      map,
      mapCanvas = document.getElementById('canvas'),
      mapCtx = mapCanvas.getContext("2d"),
      voxCanvas = document.getElementById('voxelview');
  
  // init
  roughness = parseInt(settings.roughness, 10);
  mapDimension = parseInt(settings.mapDimension, 10);
  unitSize = parseInt(settings.unitSize, 10);
  mapType = parseInt(settings.mapType, 10);
  
  genShadows = settings.genShadows;
  
  if(genShadows){
    sunX = parseInt(settings.sunX, 10);
    sunY = parseInt(settings.sunY, 10);
    sunZ = parseInt(settings.sunZ, 10);
  }
  
  mapCanvas.width = mapDimension;
  mapCanvas.height = mapDimension;
  
  map = new HeightMap(mapDimension, unitSize, roughness).mapData;
  
  // Draw everything after the terrain vals are generated
  drawMap(mapDimension, "canvas", map, mapType);
  
  if(genShadows){
    drawShadowMap(mapDimension, sunX, sunY, sunZ);
  }
  
  
  // Round to nearest pixel
  function round(n)
  {
    if (n-(parseInt(n, 10)) >= 0.5){
      return parseInt(n, 10)+1;
    }else{
      return parseInt(n, 10);
    }
  }
  
  //Create Shadowmap
  function drawShadowMap(size, sunPosX, sunPosY, sunHeight){
    var shadowCanvas = document.createElement("canvas"),
        sCtx = shadowCanvas.getContext("2d"),
        x = 0, y = 0,
        idx,
        colorFill = {r : 0, g : 0, b : 0, a : 0},
        sunX, sunY, sunZ,
        pX, pY, pZ,
        mag, dX, dY, dZ;
    
    shadowCanvas.width = shadowCanvas.height = mapDimension;
    
    var img = sCtx.createImageData(shadowCanvas.width, shadowCanvas.height),
        imgData = img.data;
    
    // Suns position
    sunX = sunPosX;
    sunY = sunPosY;
    sunZ = sunHeight;
    
    for(x = 0; x < mapDimension; x += unitSize){
      for(y = 0; y < mapDimension; y += unitSize){
        dX = sunX - x;
        dY = sunY - y;
        dZ = sunZ - map[x][y];
        
        mag = Math.sqrt(dX * dX + dY * dY + dZ * dZ);
        
        dX = (dX / mag);
        dY = (dY / mag);
        dZ = (dZ / mag);
        
        pX = x;
        pY = y;
        pZ = map[x][y];
        
        while(pX > 0 && pX < mapDimension && pY > 0 && pY < mapDimension && pZ < sunZ){
          
          if((map[round(pX)][round(pY)]) > pZ){
            colorFill = {r : 0, g : 0, b : 0, a : 180};
            
            for (var w = 0; w < unitSize; w++) {
              for (var h = 0; h < unitSize; h++) {
                var pData = (~~ (x+w) + (~~ (y+h) * canvas.width)) * 4;
                
                imgData[pData] = colorFill.r;
                imgData[pData + 1] = colorFill.g;
                imgData[pData + 2] = colorFill.b;
                imgData[pData + 3] += colorFill.a;
              }
            }
            break;
          }
          
          pX += (dX * unitSize);
          pY += (dY * unitSize);
          pZ += (dZ * unitSize);
        }
      }
    }
    
    sCtx.putImageData(img, 0, 0);
    mapCtx.drawImage(shadowCanvas, 0, 0);
    
    var strDataURI = mapCanvas.toDataURL();
    imgSave.src = strDataURI;
  }
  
  // Draw the map
  function drawMap(size, canvasId, mapData, mapType){
    var canvas = document.getElementById(canvasId),
        ctx = canvas.getContext("2d"),
        x = 0,
        y = 0,
        r = 0, g = 0, b = 0, gamma = 500,
        colorFill = 0,
        img = ctx.createImageData(canvas.height, canvas.width),
        imgData = img.data;
    
    
    // colormap colors
    var waterStart={r:39,g:50,b:63},
        waterEnd={r:10,g:20,b:40},
        sandStart={r:98,g:105,b:83},
        sandEnd={r:189,g:189,b:144},
        grassStart={r:67,g:100,b:18},
        grassEnd={r:22,g:38,b:3},
        mtnEnd={r:67,g:80,b:18},
        mtnStart={r:60,g:56,b:31},
        rockStart={r:130,g:130,b:130},
        rockEnd={r:90,g:90,b:90},
        snowStart={r:200,g:200,b:200},
        snowEnd={r:255,g:255,b:255};
    
    
    for(x = 0; x <= size; x += unitSize){
      for(y = 0; y <= size; y += unitSize){
        colorFill = {r : 0, g : 0, b : 0};
        
        switch(mapType){
          case 1: // Color map
            var  data = mapData[x][y];
            if (data >= 0 && data <= 0.3) {
              colorFill = fade(waterStart, waterEnd, 30, parseInt(data * 100, 10));
            } else if (data > 0.3 && data <= 0.8) {
              colorFill = fade(grassStart, grassEnd, 45, parseInt(data * 100, 10) - 35);
            } else if (data > 0.8 && data <= 0.95) {
              colorFill = fade(mtnStart, mtnEnd, 15, parseInt(data * 100, 10) - 80);
            } else if (data > 0.95 && data <= 1) {
              colorFill = fade(rockStart, rockEnd, 5, parseInt(data * 100, 10) - 98);
            }
              break;
          case 2: // Standard
            var standardShade = Math.floor(map[x][y] * 250);
            colorFill = {r : standardShade, g : standardShade, b : standardShade};
            break;
          case 3: // 10 shades
            var greyShade = Math.round(~~(mapData[x][y]*100)/25)*25;
            colorFill = {r : greyShade, g : greyShade, b : greyShade};
            break;
          case 4: // 2 shades
            if(mapData[x][y] <= 0.5){
              mapData[x][y] = 0;
            }else if(mapData[x][y] > 0.5){
              mapData[x][y] = 220;
            }
              
              var grey = mapData[x][y];
            colorFill = { r :  grey, g : grey, b : grey};
            break;
          case 5:
            // Section of code modified from http://www.hyper-metrix.com/processing-js/docs/index.php?page=Plasma%20Fractals
            if (mapData[x][y] < 0.5) {
              r = mapData[x][y] * gamma;
            } else {
              r = (1.0 - mapData[x][y]) * gamma;
            }
            
            if (mapData[x][y] >= 0.3 && mapData[x][y] < 0.8) {
              g = (mapData[x][y] - 0.3) * gamma;
            } else if (mapData[x][y] < 0.3) {
              g = (0.3 - mapData[x][y]) * gamma;
            } else {
              g = (1.3 - mapData[x][y]) * gamma;
            }
            
            if (mapData[x][y] >= 0.5) {
              b = (mapData[x][y] - 0.5) * gamma;
            } else {
              b = (0.5 - mapData[x][y]) * gamma;
            }
            colorFill = { r :  ~~r, g : ~~g, b : ~~b};
            break;
        }
        
        for (var w = 0; w <= unitSize; w++) {
          for (var h = 0; h <= unitSize; h++) {
            var pData = (~~ (x+w) + (~~ (y+h) * canvas.width)) * 4;
            
            imgData[pData] = colorFill.r;
            imgData[pData + 1] = colorFill.g;
            imgData[pData + 2] = colorFill.b;
            imgData[pData + 3] = 255;
          }
        }
      }
    }
    
    ctx.putImageData(img, 0, 0);
    
    // Add to an image so its easier to save
    var strDataURI = mapCanvas.toDataURL();
    imgSave.src = strDataURI;
    
    // utility for color interpolation
    function fade(colorStart, colorEnd, totalSteps, step) {
      var rStart = colorStart.r,
          rEnd = colorEnd.r,
          gStart = colorStart.g,
          gEnd = colorEnd.g,
          bStart = colorStart.b,
          bEnd = colorEnd.b,
          r = rEnd + (~~ ((rStart - rEnd) / totalSteps) * step),
          g = gEnd + (~~ ((gStart - gEnd) / totalSteps) * step),
          b = bEnd + (~~ ((bStart - bEnd) / totalSteps) * step);
      
      return {
        r: r,
        g: g,
        b: b
      };
    }
  }
}



var gui = new dat.GUI();

gui.add(settings, 'roughness');
gui.add(settings, 'mapDimension', [64,128,256,512,1024]);
gui.add(settings, 'unitSize', [1,2,4] );
gui.add(settings, 'mapType', {'Color Map' : 1, 'Gray Scale' : 2, '10 Shades' : 3, '2 Shades' : 4, 'Plasma' : 5});

var shadowSection = gui.addFolder('Shadow Map');
shadowSection.add(settings, 'genShadows');
shadowSection.add(settings, 'sunX');
shadowSection.add(settings, 'sunY');
shadowSection.add(settings, 'sunZ');

gui.add(settings, 'render');
              
            
!
999px

Console