Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <svg id="logoFlower" width="600px" height="600px" viewBox="0 0 600 600" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <filter id="glow">
      <fegaussianblur class="blur" result="coloredBlur" stddeviation="2"></fegaussianblur>
      <femerge>
        <femergenode in="coloredBlur"></femergenode>
        <femergenode in="coloredBlur"></femergenode>
        <femergenode in="coloredBlur"></femergenode>
        <femergenode in="SourceGraphic"></femergenode>
      </femerge>
    </filter>
    <path id="petal" d="
      M 0 0 Q 80 -50, 40 -100 T 0 -256
      M 0 0 Q -80 -50, -40 -100 T 0 -256
      M 0 -50 L 0 -100
      " stroke="#f80" stroke-width="1" fill="transparent" style="filter: url(#glow);"/>
  </defs>
  <g transform="translate(300, 300)">
    <animateTransform attributeName="transform" type="rotate" 
           values="0; 72; 0"
           dur="10s" repeatCount="indefinite" additive="sum"/>
    <use href="#petal"/>
    <use href="#petal" transform="rotate(72)"/>
    <use href="#petal" transform="rotate(144)"/>
    <use href="#petal" transform="rotate(-144)"/>
    <use href="#petal" transform="rotate(-72)"/>
  </g>
</svg>

<iframe id="player" width="61" height="85" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/956511991&color=%23ff7f00&auto_play=false&hide_related=true&show_comments=false&show_user=true&show_reposts=false&show_teaser=false"></iframe>
<script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>

<div id="checkbox" class="writing noselect">quick <div id="box"></div></div>
<div id="title" class="writing noselect">glowing<br/>warmness</div>
<!--div id="btnPlay" class="writing noselect">play &#9658;</div-->

<div id="icons" style="display: none;">
  <svg class="icon" viewBox="0 0 384 512" width="50">
    <path d="M0 352a160 160 0 0 0 160 160h64a160 160 0 0 0 160-160V224H0zM176 0h-16A160 160 0 0 0 0 160v32h176zm48 0h-16v192h176v-32A160 160 0 0 0 224 0z" stroke="#840" stroke-opacity="0.5" fill="transparent" stroke-width="10"/>
  </svg>
  <svg id="stopicon" class="icon" viewBox="0 0 512 512" width="50">
    <path d="M256 8C119.034 8 8 119.033 8 256s111.034 248 248 248 248-111.034 248-248S392.967 8 256 8zm130.108 117.892c65.448 65.448 70 165.481 20.677 235.637L150.47 105.216c70.204-49.356 170.226-44.735 235.638 20.676zM125.892 386.108c-65.448-65.448-70-165.481-20.677-235.637L361.53 406.784c-70.203 49.356-170.226 44.736-235.638-20.676z" stroke="maroon" stroke-width="10" fill="orange" fill-opacity="0.25"/>
  </svg>
</div>

<script>
  let splineDataPars = `
        struct splineData {
          vec3 point;
          vec3 binormal;
          vec3 normal;
        };

        splineData getSplineData(sampler2D tex, float t){
          float step = 1. / 4.;
          float halfStep = step * 0.5;
          splineData sd;
          sd.point    = texture2D(tex, vec2(step * 0.5, t)).rgb;
          sd.normal   = texture2D(tex, vec2(step * 1.5, t)).rgb;
          sd.binormal = texture2D(tex, vec2(step * 2.5, t)).rgb;
          return sd;
        }`;
  let noise3d = `//	Simplex 3D Noise 
//	by Ian McEwan, Ashima Arts
//
vec4 permute(vec4 x){return mod(((x*34.0)+1.0)*x, 289.0);}
vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;}

float snoise(vec3 v){ 
  const vec2  C = vec2(1.0/6.0, 1.0/3.0) ;
  const vec4  D = vec4(0.0, 0.5, 1.0, 2.0);

// First corner
  vec3 i  = floor(v + dot(v, C.yyy) );
  vec3 x0 =   v - i + dot(i, C.xxx) ;

// Other corners
  vec3 g = step(x0.yzx, x0.xyz);
  vec3 l = 1.0 - g;
  vec3 i1 = min( g.xyz, l.zxy );
  vec3 i2 = max( g.xyz, l.zxy );

  //  x0 = x0 - 0. + 0.0 * C 
  vec3 x1 = x0 - i1 + 1.0 * C.xxx;
  vec3 x2 = x0 - i2 + 2.0 * C.xxx;
  vec3 x3 = x0 - 1. + 3.0 * C.xxx;

// Permutations
  i = mod(i, 289.0 ); 
  vec4 p = permute( permute( permute( 
             i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
           + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) 
           + i.x + vec4(0.0, i1.x, i2.x, 1.0 ));

// Gradients
// ( N*N points uniformly over a square, mapped onto an octahedron.)
  float n_ = 1.0/7.0; // N=7
  vec3  ns = n_ * D.wyz - D.xzx;

  vec4 j = p - 49.0 * floor(p * ns.z *ns.z);  //  mod(p,N*N)

  vec4 x_ = floor(j * ns.z);
  vec4 y_ = floor(j - 7.0 * x_ );    // mod(j,N)

  vec4 x = x_ *ns.x + ns.yyyy;
  vec4 y = y_ *ns.x + ns.yyyy;
  vec4 h = 1.0 - abs(x) - abs(y);

  vec4 b0 = vec4( x.xy, y.xy );
  vec4 b1 = vec4( x.zw, y.zw );

  vec4 s0 = floor(b0)*2.0 + 1.0;
  vec4 s1 = floor(b1)*2.0 + 1.0;
  vec4 sh = -step(h, vec4(0.0));

  vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
  vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;

  vec3 p0 = vec3(a0.xy,h.x);
  vec3 p1 = vec3(a0.zw,h.y);
  vec3 p2 = vec3(a1.xy,h.z);
  vec3 p3 = vec3(a1.zw,h.w);

//Normalise gradients
  vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
  p0 *= norm.x;
  p1 *= norm.y;
  p2 *= norm.z;
  p3 *= norm.w;

// Mix final noise value
  vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
  m = m * m;
  return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), 
                                dot(p2,x2), dot(p3,x3) ) );
}`;
  let noise = `
  //	Simplex 4D Noise 
//	by Ian McEwan, Ashima Arts
//
vec4 permute(vec4 x){return mod(((x*34.0)+1.0)*x, 289.0);}
float permute(float x){return floor(mod(((x*34.0)+1.0)*x, 289.0));}
vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;}
float taylorInvSqrt(float r){return 1.79284291400159 - 0.85373472095314 * r;}

vec4 grad4(float j, vec4 ip){
  const vec4 ones = vec4(1.0, 1.0, 1.0, -1.0);
  vec4 p,s;

  p.xyz = floor( fract (vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0;
  p.w = 1.5 - dot(abs(p.xyz), ones.xyz);
  s = vec4(lessThan(p, vec4(0.0)));
  p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www; 

  return p;
}

float snoise(vec4 v){
  const vec2  C = vec2( 0.138196601125010504,  // (5 - sqrt(5))/20  G4
                        0.309016994374947451); // (sqrt(5) - 1)/4   F4
// First corner
  vec4 i  = floor(v + dot(v, C.yyyy) );
  vec4 x0 = v -   i + dot(i, C.xxxx);

// Other corners

// Rank sorting originally contributed by Bill Licea-Kane, AMD (formerly ATI)
  vec4 i0;

  vec3 isX = step( x0.yzw, x0.xxx );
  vec3 isYZ = step( x0.zww, x0.yyz );
//  i0.x = dot( isX, vec3( 1.0 ) );
  i0.x = isX.x + isX.y + isX.z;
  i0.yzw = 1.0 - isX;

//  i0.y += dot( isYZ.xy, vec2( 1.0 ) );
  i0.y += isYZ.x + isYZ.y;
  i0.zw += 1.0 - isYZ.xy;

  i0.z += isYZ.z;
  i0.w += 1.0 - isYZ.z;

  // i0 now contains the unique values 0,1,2,3 in each channel
  vec4 i3 = clamp( i0, 0.0, 1.0 );
  vec4 i2 = clamp( i0-1.0, 0.0, 1.0 );
  vec4 i1 = clamp( i0-2.0, 0.0, 1.0 );

  //  x0 = x0 - 0.0 + 0.0 * C 
  vec4 x1 = x0 - i1 + 1.0 * C.xxxx;
  vec4 x2 = x0 - i2 + 2.0 * C.xxxx;
  vec4 x3 = x0 - i3 + 3.0 * C.xxxx;
  vec4 x4 = x0 - 1.0 + 4.0 * C.xxxx;

// Permutations
  i = mod(i, 289.0); 
  float j0 = permute( permute( permute( permute(i.w) + i.z) + i.y) + i.x);
  vec4 j1 = permute( permute( permute( permute (
             i.w + vec4(i1.w, i2.w, i3.w, 1.0 ))
           + i.z + vec4(i1.z, i2.z, i3.z, 1.0 ))
           + i.y + vec4(i1.y, i2.y, i3.y, 1.0 ))
           + i.x + vec4(i1.x, i2.x, i3.x, 1.0 ));
// Gradients
// ( 7*7*6 points uniformly over a cube, mapped onto a 4-octahedron.)
// 7*7*6 = 294, which is close to the ring size 17*17 = 289.

  vec4 ip = vec4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0) ;

  vec4 p0 = grad4(j0,   ip);
  vec4 p1 = grad4(j1.x, ip);
  vec4 p2 = grad4(j1.y, ip);
  vec4 p3 = grad4(j1.z, ip);
  vec4 p4 = grad4(j1.w, ip);

// Normalise gradients
  vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
  p0 *= norm.x;
  p1 *= norm.y;
  p2 *= norm.z;
  p3 *= norm.w;
  p4 *= taylorInvSqrt(dot(p4,p4));

// Mix contributions from the five corners
  vec3 m0 = max(0.6 - vec3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0);
  vec2 m1 = max(0.6 - vec2(dot(x3,x3), dot(x4,x4)            ), 0.0);
  m0 = m0 * m0;
  m1 = m1 * m1;
  return 49.0 * ( dot(m0*m0, vec3( dot( p0, x0 ), dot( p1, x1 ), dot( p2, x2 )))
               + dot(m1*m1, vec2( dot( p3, x3 ), dot( p4, x4 ) ) ) ) ;

}
  `;
</script>
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap');
body{ 
  overflow: hidden; 
  margin: 0; 
}
.transparent{
  opacity: 0.001;
}
#player{
  /*opacity: 0.05;*/
  position: absolute;
  bottom: 1vh;
  right: 1vh;
  border: 3px solid #f80;
  border-radius: 30px;
}
.hoverable:hover{
  opacity: 1;
}

#icons{
  position: absolute;
  margin: 10px;
  left: 0;
  top: 0;
}
#stopicon{
  display: block;
  position: absolute;
  top: 8px;
}

#logoFlower{
  position: absolute;
  left:calc(50% - 300px);
  top: calc(50% - 300px);
}

.writing{
  margin: 20px;
  font-family: 'Roboto', sans-serif;
  font-size: 4vh;
  display: block;
  color: #fa0;
  text-shadow: 0 0 0.125vh #f40, 0 0 0.125vh #f40, 0 0 0.25vh #f40, 0 0 0.5vh #f40, 0 0 0.75vh #f40;
}
#title{
  position: absolute;
  bottom: 0;
}
#btnPlay{
  position: absolute;
  bottom: 0;
  right: 0;
  opacity: 0.5;
  cursor: pointer;
}
#checkbox{
  position: absolute;
  top: 0;
  right: 0;
  display:table-cell;
  vertical-align: top;
  cursor:pointer;
}
#box{
  display: inline-table;
  width: 2vh;
  height: 2vh;
  border: 2px solid #f80;
  font-size:1.5vh;
  text-align: center;
  box-shadow: 0 0 6px 0px #f40;
}

.noselect {
  -webkit-touch-callout: none;
  /* iOS Safari */
  -webkit-user-select: none;
  /* Safari */
  -khtml-user-select: none;
  /* Konqueror HTML */
  -moz-user-select: none;
  /* Firefox */
  -ms-user-select: none;
  /* Internet Explorer/Edge */
  user-select: none;
  /* Non-prefixed version, currently
  supported by Chrome and Opera */
}
              
            
!

JS

              
                import * as THREE from "https://cdn.skypack.dev/three@0.136.0";
import { OrbitControls } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/controls/OrbitControls";

import { RoundedBoxGeometry } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/geometries/RoundedBoxGeometry";

import { EffectComposer } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPass } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/postprocessing/RenderPass.js";
import { ShaderPass } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/postprocessing/ShaderPass.js";
import { UnrealBloomPass } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/postprocessing/UnrealBloomPass.js";

import { MeshSurfaceSampler } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/math/MeshSurfaceSampler";
import { ImprovedNoise } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/math/ImprovedNoise";

import { TWEEN } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/libs/tween.module.min";

//import { GUI } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/libs/lil-gui.module.min";
//import Stats from 'https://cdn.skypack.dev/three@0.136.0/examples/jsm/libs/stats.module.js';

console.clear();

// <SoundCloudWidget>
let playingStarted = 0;
let SCW = SC.Widget(player);
SCW.bind(SC.Widget.Events.READY, function () {
  /*btnPlay.style.opacity = 1;
  btnPlay.addEventListener("click", event => {
    
  })*/
  SCW.bind(SC.Widget.Events.PLAY, function () {
    if (playingStarted !== 0) return;
    
    //btnPlay.style.display = "none";
    checkbox.style.display = "none";
    logoFlower.style.display = "none";
    icons.style.display = "block";
    player.classList.add("transparent");
    player.classList.add("hoverable");
    
    //SCW.play();
    runRendering();
    runSequence();
    playingStarted = 1;
  });
});

// </SoundCloudWidget>

const perlin = new ImprovedNoise();
const isQuick = {
  value: false
}
checkbox.addEventListener("click", event => {
  isQuick.value = !isQuick.value;
  box.style.backgroundColor = isQuick.value ? "#f80" : "transparent";
  //console.log(isQuick.value);
})

class CurveDTex extends THREE.DataTexture{
  constructor(curve, segments){
    
    let data = new Float32Array(4 * segments * 4).fill(0);
    let pts = curve.getSpacedPoints(segments - 1);
    let nbt = curve.computeFrenetFrames(segments - 1);
    
    pts.forEach((p, idx) => {
      let offset = idx * 16;
      p.toArray(data, offset);
      nbt.normals[idx].toArray(data, offset + 4);
      nbt.binormals[idx].toArray(data, offset + 8);
      nbt.tangents[idx].toArray(data, offset + 12);
    });
    
    super(data, 4, segments, THREE.RGBAFormat, THREE.FloatType);
    this.needsUpdate = true;
    
  }
}

class Postprocessing {
  constructor(scene, camera, renderer) {
    const renderScene = new RenderPass(scene, camera);
    const bloomPass = new UnrealBloomPass(
      new THREE.Vector2(window.innerWidth, window.innerHeight),
      1.5,
      0,
      0
    );
    const target1 = new THREE.WebGLRenderTarget(
      window.innerWidth,
      window.innerHeight,
      {
        type: THREE.HalfFloatType,
        format: THREE.RGBAFormat,
        encoding: THREE.sRGBEncoding,
        samples: 8
      }
    );
    this.bloomComposer = new EffectComposer(renderer, target1);
    this.bloomComposer.renderToScreen = false;
    this.bloomComposer.addPass(renderScene);
    this.bloomComposer.addPass(bloomPass);
    const finalPass = new ShaderPass(
      new THREE.ShaderMaterial({
        uniforms: {
          baseTexture: { value: null },
          bloomTexture: { value: this.bloomComposer.renderTarget2.texture }
        },
        vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,
        fragmentShader: `uniform sampler2D baseTexture; uniform sampler2D bloomTexture; varying vec2 vUv; void main() { gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) ); }`,
        defines: {}
      }),
      "baseTexture"
    );
    finalPass.needsSwap = true;
    const target2 = new THREE.WebGLRenderTarget(
      window.innerWidth,
      window.innerHeight,
      {
        type: THREE.HalfFloatType,
        format: THREE.RGBAFormat,
        encoding: THREE.sRGBEncoding,
        samples: 8
      }
    );
    this.finalComposer = new EffectComposer(renderer, target2);
    this.finalComposer.addPass(renderScene);
    this.finalComposer.addPass(finalPass);
  }
}

class Background extends THREE.Mesh {
  constructor(gu, bgColor) {
    super(
      new THREE.CylinderGeometry(1, 1, 1, 72, 1, true)
        .translate(0, 0.5, 0)
        .scale(250, 150, 250),
      new THREE.MeshBasicMaterial({
        side: THREE.BackSide,
        onBeforeCompile: (shader) => {
          shader.uniforms.time = gu.time;
          shader.uniforms.globalBloom = gu.globalBloom;
          shader.uniforms.bgColor = { value: new THREE.Color(bgColor.on) };
          shader.uniforms.appearance = this.uniforms.appearance;
          shader.vertexShader = `
            varying vec3 vPos;
            ${shader.vertexShader}
          `.replace(
            `#include <begin_vertex>`,
            `#include <begin_vertex>
              vPos = position;
            `
          );
          //console.log("Background", shader.vertexShader);
          shader.fragmentShader = `
            #define ss(a, b, c) smoothstep(a, b, c)
            uniform float time;
            uniform float globalBloom;
            uniform vec3 bgColor;
            uniform float appearance;
            varying vec3 vPos;
            ${noise}
            ${shader.fragmentShader}
          `.replace(
            `#include <dithering_fragment>`,
            `#include <dithering_fragment>
            
            float t = time * 0.1;
            
            vec3 col1 = bgColor;
            vec3 col2 = col1 + mix(vec3(1, 1, 0), vec3(1, 0.25, 0), ss(25., 125., vPos.y)) * 0.2;
            
            vec3 pos = vPos;
            pos.xz = normalize(vPos.xz) * 15.;
            pos.y -= time * 25.;
            pos.y *= 0.01;
            
            float n = snoise(vec4(pos, t)) * 0.5 + 0.5;
            float f = n * (ss(0., 25., vPos.y) - ss(25., 150., vPos.y));
            f *= f;
            
            vec3 col = mix(col1, col2, f * appearance);
            gl_FragColor.rgb = mix(col, vec3(0), globalBloom);
            `
          );
          //console.log("Background", shader.fragmentShader)
        }
      })
    );
    this.uniforms = {
      appearance:
        {value: 0}
    };
  }
}

class AncientCube extends THREE.Mesh {
  constructor(gu) {
    super(
      new RoundedBoxGeometry(3.5, 3.5, 3.5, 5, 0.375)
        .rotateY(Math.PI / 4)
        .rotateZ(THREE.MathUtils.degToRad(90 - 35.5))
        .rotateY(Math.PI / 6)
        .translate(0, Math.sqrt(3) * 2, 0),
      new THREE.MeshLambertMaterial({
        color: new THREE.Color(0.075, 0, 0),
        onBeforeCompile: (shader) => {
          shader.uniforms.time = gu.time;
          shader.uniforms.globalBloom = gu.globalBloom;
          shader.vertexShader = `
            varying vec3 vPos;
            ${shader.vertexShader}
          `.replace(
            `#include <begin_vertex>`,
            `#include <begin_vertex>
              vPos = position;
            `
          );
          //console.log(shader.vertexShader);
          shader.fragmentShader = `
            uniform float time;
            uniform float globalBloom;
            varying vec3 vPos;
            ${noise}
            ${shader.fragmentShader}
          `.replace(
            `#include <dithering_fragment>`,
            `#include <dithering_fragment>
              float n = snoise(vec4(vPos * 0.25, time * 0.05));
              n = sin(n * PI2 * 4.) * 0.5 + 0.5;
              float fw = fwidth(n); 
              float e = fw * 3.;
              float f = smoothstep(e, 0., abs(n - 0.5));
              vec3 colorBloomNone = mix(gl_FragColor.rgb, mix(vec3(0.5, 0, 1) * 1., vec3(1, 1, 0.5), 0.875) * 0.75, f);
              vec3 colorBloom = mix(vec3(0), vec3(1, 0, 0) * 0.5, f);
              gl_FragColor.rgb = mix(colorBloomNone, colorBloom, globalBloom);
            `
          );
          //console.log(shader.fragmentShader);
        }
      })
    );
    this.light = new THREE.PointLight(0xff0088, 2, 10, 2);
    this.add(this.light);
  }
}

class Ground extends THREE.Mesh {
  constructor(gu, bgColor) {
    let g = new THREE.PlaneGeometry(20, 20, 40, 40);
    let pos = g.attributes.position;
    let uv = g.attributes.uv;
    for (let i = 0; i < pos.count; i++) {
      pos.setZ(i, perlin.noise(uv.getX(i) * 5, uv.getY(i) * 5, 0.1)) * 1;
    }
    g.computeVertexNormals();
    super(
      g.rotateX(Math.PI * -0.5).translate(0, -0.3, 0),
      new THREE.MeshLambertMaterial({
        color: 0x440000,
        onBeforeCompile: (shader) => {
          shader.uniforms.globalBloom = gu.globalBloom;
          shader.uniforms.bgColor = { value: new THREE.Color(bgColor.on) };
          shader.vertexShader = `
            varying vec3 vPos;
            ${shader.vertexShader}
          `.replace(
            `#include <begin_vertex>`,
            `#include <begin_vertex>
              vPos = position;
            `
          );
          shader.fragmentShader = `
            uniform float globalBloom;
            uniform vec3 bgColor;
            varying vec3 vPos;
            ${shader.fragmentShader}
          `.replace(
            `#include <dithering_fragment>`,
            `#include <dithering_fragment>
              gl_FragColor.rgb = mix(gl_FragColor.rgb, bgColor, smoothstep(0.25, 0.5, length(vUv - 0.5)));
              gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0), globalBloom);
            `
          );
        }
      })
    );
    this.material.defines = { USE_UV: "" };
  }
}

class Flower extends THREE.Mesh {
  constructor(gu) {
    
    let colors = {
      base: 0x641600,
      back: 0x320000
    }
    
    // core
    let g = new THREE.SphereGeometry(0.15, 63, 32)
      .translate(0, 0.15, 0)
      .scale(1, 4, 1);
    let m = new THREE.MeshBasicMaterial({ color: colors.base });
    super(g, m);
    this.position.set(0, 7.75, 0);

    // petals
    const petalSegments = 100;
    let gPetal = new THREE.BoxGeometry(1, 0.0375, 1, 1, 1, petalSegments).translate(0, 0, 0.5);
    let curveShape = new THREE.CatmullRomCurve3(
      [
        [0, 0],
        [0.5, 0.25],
        [0.25, 0.5],
        [0.375, 0.75],
        [0, 1]
      ].map((p) => {
        return new THREE.Vector3(p[0], p[1], 0);
      })
    );
    let curveBend = new THREE.CatmullRomCurve3(
      [
        [0, 0],
        [0.125, -0.125],
        [1, 0.5],
        [1.5, 0.25]
      ].map((p) => {
        return new THREE.Vector3(0, p[1], p[0]);
      })
    );
    
    let texShape = new CurveDTex(curveShape, petalSegments + 1);
    let texBend = new CurveDTex(curveBend, petalSegments + 1);
    
    let gPetals = new THREE.InstancedBufferGeometry().copy(gPetal);
    gPetals.setAttribute("instID", new THREE.InstancedBufferAttribute(new Float32Array([0, 1, 2, 3, 4]), 1));
    gPetals.instanceCount = Infinity;
    let mPetals = new THREE.MeshBasicMaterial({
      color: colors.base,
      onBeforeCompile: shader => {
        shader.uniforms.time = gu.time;
        shader.uniforms.globalBloom = gu.globalBloom;
        shader.uniforms.texShape = {value: texShape};
        shader.uniforms.texBend = {value: texBend};
        shader.uniforms.colorBack = {value: new THREE.Color(colors.back)};
        shader.uniforms.appearance = this.petals.uniforms.appearance;
        shader.vertexShader = `
          #define ss(a, b, c) smoothstep(a, b, c)
          uniform sampler2D texShape;
          uniform sampler2D texBend;
          uniform float appearance;
          attribute float instID;
          ${splineDataPars}
          ${shader.vertexShader}
        `.replace(
          `#include <begin_vertex>`,
          `#include <begin_vertex>
          
          float shapeX = getSplineData(texShape, position.z).point.x;
          
          splineData bend = getSplineData(texBend, position.z);
          vec3 P = bend.point;
          vec3 B = bend.binormal;
          vec3 N = bend.normal;
          
          vec2 profile = position.xy;
          float aprn = -1. + (appearance * 2.);   // smooth
          aprn = ss(aprn + 1., aprn, position.z); // appearance
          profile.x *= (shapeX * 1.25)  * aprn;
          profile.y *= (sin(position.z * PI) * 0.5 + 0.5) * aprn;
          
          vec3 pos = P + (N * profile.x) + (B * profile.y);
          float angle = PI * 2. / 5. * instID;
          float c = cos(angle);
          float s = sin(angle);
          pos.xz *= mat2(c, s, -s, c);
          
          transformed = pos;
          `
        );
        //console.log("mPetals", shader.vertexShader);
        shader.fragmentShader = `
          uniform float time;
          uniform float globalBloom;
          uniform vec3 colorBack;
          
          float uvOutline(vec2 uv){
            // https://madebyevan.com/shaders/grid/
            vec2 coord = uv;
            vec2 grid = abs(fract(coord - 0.5) - 0.5) / fwidth(coord) / 2.;
            float line = min(grid.x, grid.y);
            return 1.0 - min(line, 1.0);
          }
          ${shader.fragmentShader}
        `.replace(
          `#include <dithering_fragment>`,
          `#include <dithering_fragment>
          vec2 oUv = vUv * vec2(2., 1.);
          float outline = uvOutline(oUv);
          
          vec3 colorBloom = mix(gl_FragColor.rgb * 0.875, vec3(0), outline);
          vec3 colorBloomNone = mix(vec3(0), colorBack, outline);
          
          gl_FragColor.rgb = mix(colorBloomNone, colorBloom, globalBloom);
          `
        );
        //console.log(shader.fragmentShader)
      }
    });
    mPetals.defines = {"USE_UV": ""};
        
    let petals = new THREE.Mesh(gPetals, mPetals);
    petals.uniforms = {
      appearance: {
        value: 0
      }
    }
    this.petals = petals;
    this.add(this.petals);
    
  }
}

class Plant extends THREE.Mesh {
  constructor(gu, box) {
    box.updateMatrixWorld();
    super();
    this.uniforms = {
      growth: { value: 0 }
    };
    // base curve
    let curvePts = [/*new THREE.Vector3(0, -0.5, 0)*/];

    let raycaster = new THREE.Raycaster();
    let ori = new THREE.Vector3(),
      dir = new THREE.Vector3();
    let interPoint = new THREE.Vector3();
    let intersect;

    const amount = 120;
    new Array(amount + 1).fill().forEach((p, idx) => {
      ori.setFromSphericalCoords(
        4,
        Math.PI - idx * (Math.PI / amount),
        Math.PI - idx * ((Math.PI * 2) / amount) * 4
      );
      dir.copy(ori).normalize().negate();
      ori.y += Math.sqrt(3) * 2;
      raycaster.set(ori, dir);
      intersect = raycaster.intersectObject(box);
      let io = intersect[0];
      //console.log(intersect);
      interPoint.copy(io.point).addScaledVector(io.face.normal, 0.75);
      curvePts.push(interPoint.clone());
    });
    curvePts.push(new THREE.Vector3(0, 7.5, 0), new THREE.Vector3(0, 8, 0));

    let curve = new THREE.CatmullRomCurve3(curvePts);

    let dt = new CurveDTex(curve, 1024);
    dt.needsUpdate = true;

    let g = new THREE.CylinderGeometry(1, 1, 1, 64, 1023, true)
      .translate(0, 0.5, 0)
      .rotateX(-Math.PI * 0.5);
    let m = new THREE.MeshLambertMaterial({
      color: new THREE.Color(0x321608).multiplyScalar(0.5),
      onBeforeCompile: (shader) => {
        shader.uniforms.time = gu.time;
        shader.uniforms.globalBloom = gu.globalBloom;
        shader.uniforms.spatialTex = { value: dt };
        shader.uniforms.growth = this.uniforms.growth;
        shader.vertexShader = `
          #define ss(a, b, c) smoothstep(a, b, c)
          uniform float time;
          uniform sampler2D spatialTex;
          uniform float growth;
          
          varying float vNoiseVal;
          
          ${splineDataPars}
          ${noise}
          ${shader.vertexShader}
        `
          .replace(
            `#include <beginnormal_vertex>`,
            `#include <beginnormal_vertex>
          
          splineData spline = getSplineData(spatialTex, 1. - uv.y);
          vec3 P = spline.point;
          vec3 B = spline.binormal;
          vec3 N = spline.normal;
          
          float radiusNoise = snoise(vec4(position.xy, (uv.y + time * 0.00625) * 40., time * 0.5));
          vNoiseVal = radiusNoise * 0.5 + 0.5;
          
          float growthVal = (1. - growth) * (1. - 0.015);
          
          float radius = (0.05 * growth + 0.075 * uv.y) + radiusNoise * 0.1;
          
          radius *=  ss(growthVal, growthVal + 0.015, uv.y) - ss(1. - 0.015, 1., uv.y); // top tip - bottom tip
          vec2 profile = position.xy * radius;
          
          vec3 pos = P + (N * profile.x) + (B * profile.y);
          objectNormal = normalize(pos - P);
          
          `
          )
          .replace(
            `#include <begin_vertex>`,
            `#include <begin_vertex>
            transformed = pos;
          `
          );
        //console.log(shader.vertexShader);
        shader.fragmentShader = `
          #define ss(a, b, c) smoothstep(a, b, c)
          uniform float globalBloom;
          varying float vNoiseVal;
          ${shader.fragmentShader}
        `.replace(
          `#include <dithering_fragment>`,
          `#include <dithering_fragment>
            float noiseVal = ss(0.5, 0.75, vNoiseVal);
            vec3 colBloomNone = mix(gl_FragColor.rgb, vec3(0.5), noiseVal);
            vec3 colBloom = mix(vec3(0), vec3(1, 0.25, 0), noiseVal);
            gl_FragColor.rgb = mix(colBloomNone, colBloom, globalBloom);
          `
        );
        //console.log(shader.fragmentShader);
      }
    });
    m.defines = { USE_UV: "" };
    this.geometry = g;
    this.material = m;

    this.flower = new Flower(gu);
    this.add(this.flower);

  }
}

class Fireflies extends THREE.Points {
  constructor(gu) {
    let shift = [];
    let g = new THREE.BufferGeometry().setFromPoints(
      new Array(1000).fill().map((_) => {
        let R = 8;
        let r = 5;
        let rand = Math.random();
        let radius = Math.sqrt(R * R * rand + (1 - rand) * r * r);
        let v = new THREE.Vector3().randomDirection().setLength(radius);
        v.y += Math.sqrt(3) * 2;
        shift.push(
          Math.random() * Math.PI,
          Math.random() * Math.PI * 2,
          (Math.random() * 0.9 + 0.1) * Math.PI * 0.1,
          Math.random() * 3 + 1
        );
        return v;
      })
    );
    g.setAttribute("shift", new THREE.Float32BufferAttribute(shift, 4));
    let m = new THREE.PointsMaterial({
      color: "orange",
      size: 0.1125,
      transparent: true,
      opacity: 0,
      onBeforeCompile: (shader) => {
        shader.uniforms.time = gu.time;
        shader.uniforms.globalBloom = gu.globalBloom;
        shader.vertexShader = `
          uniform float time;
          attribute vec4 shift;
          varying float vActive;
          ${shader.vertexShader}
        `
          .replace(
            `#include <begin_vertex>`,
            `#include <begin_vertex>
            float t = time;
            float moveT = mod(shift.x + shift.z * t, PI2);
            float moveS = mod(shift.y + shift.z * t, PI2);
            transformed += vec3(cos(moveS) * sin(moveT), cos(moveT), sin(moveS) * sin(moveT)) * shift.w;
            
            float a = sin(mod((time * 0.1 + shift.w) * PI2, PI2)) * 0.5 + 0.5;
            a *= a*a*a*a;
            vActive = a * step(0., transformed.y);
          `
          )
          .replace(`gl_PointSize = size;`, `gl_PointSize = size * vActive;`);
        //console.log(shader.vertexShader);
        shader.fragmentShader = `
          #define ss(a, b, c) smoothstep(a, b, c)
          uniform float time;
          uniform float globalBloom;
          varying float vActive;
          ${shader.fragmentShader}
        `
          .replace(
            `#include <clipping_planes_fragment>`,
            `#include <clipping_planes_fragment>
              float d = length(gl_PointCoord.xy - 0.5);
              if (d > 0.5) discard;
            `
          )
          .replace(
            `vec4 diffuseColor = vec4( diffuse, opacity );`,
            `vec4 diffuseColor = vec4( diffuse, opacity );
            diffuseColor.a *= 0.75 * ss(0.5, 0., d) * vActive;
            `
          )
          .replace(
            `#include <premultiplied_alpha_fragment>`,
            `#include <premultiplied_alpha_fragment>
            vec3 colBloomNone = mix(gl_FragColor.rgb, vec3(1, 0.5, 0.25), vActive);
            vec3 colBloom = mix(vec3(0), gl_FragColor.rgb, vActive);
            gl_FragColor.rgb = mix(colBloomNone, colBloom, globalBloom);
          `
          );
        //console.log(shader.fragmentShader);
      }
    });
    super(g, m);
  }
}

class Tetrahedra extends THREE.InstancedMesh{
  constructor(gu, circles = 3, itemsPerCircle = 100){
    let totalCount = circles * itemsPerCircle;
    let g = new THREE.TetrahedronGeometry(0.5);
    g.setAttribute("timings", new THREE.InstancedBufferAttribute(new Float32Array(totalCount).fill(-100), 1));
    let m = new THREE.MeshBasicMaterial({
      color: new THREE.Color(1, 0.125, 0), 
      wireframe: true, 
      transparent: true, 
      opacity: 1,
      onBeforeCompile: shader => {
        shader.uniforms.time = gu.time;
        shader.uniforms.globalBloom = gu.globalBloom;
        shader.uniforms.appearance = this.uniforms.appearance;
        shader.vertexShader = `
          attribute float timings;
          varying float vTimings;
          ${shader.vertexShader}
        `.replace(
          `#include <begin_vertex>`,
          `#include <begin_vertex>
            vTimings = timings;
          `
        );
        shader.fragmentShader = `
          #define S(a, b, t) smoothstep(a, b, t)
          uniform float time;
          uniform float globalBloom;
          uniform float appearance;
          varying float vTimings;
          ${shader.fragmentShader}
        `.replace(
          `#include <color_fragment>`,
          `#include <color_fragment>
            float aVal = time - vTimings;
            float peak = 0.1;
            float end = 1.;
            float showVal = S(0., peak, aVal) - S(peak, end, aVal);
            showVal *= appearance;
            diffuseColor.a = 0.125 + (0.875 * showVal);
            
            vec3 colorBloom = mix(vec3(0), diffuseColor.rgb, showVal);
            vec3 colorBloomNone = mix(diffuseColor.rgb, vec3(0.5), showVal);
            diffuseColor.rgb = mix(colorBloomNone, colorBloom, globalBloom);
          `
        );
        //console.log(shader.vertexShader, shader.fragmentShader);
      }
    });
    super(g, m, totalCount);
    this.proxy = new Array(totalCount).fill().map( (_, idx) => {
      let o = new THREE.Object3D();
      o.scale.setScalar(Math.random() * 0.5 + 1);
      let cIdx = Math.floor(idx / 100)
      o.userData = {
        cIdx: cIdx,
        rotDir: cIdx == 0 ? 1 : cIdx == 1 ? -1 : 0,
        radius: 20 + 10 * cIdx,
        angle: Math.PI * 2 / itemsPerCircle * (idx % itemsPerCircle),
        rotInit: new THREE.Vector3().random().multiplyScalar(2 * Math.PI),
        rotSpeed: new THREE.Vector3().random().multiplyScalar(2 * Math.PI * 0.1)
      }
      return o;
    });
    setInterval(()=>{
      for(let i = 0; i < 5; i++){
        this.geometry.attributes.timings.setX(THREE.MathUtils.randInt(0, totalCount - 1), gu.time.value);
      }
      this.geometry.attributes.timings.needsUpdate = true;
    }, 100);
    //console.log(this);
    this.uniforms = {
      appearance: {value: 0}
    }
    this.params = {
      heightRatio: 1
    }
    this.update = (t) => {
      this.proxy.forEach((proxy, idx) => {
        let ud = proxy.userData;
        let cIdx = ud.cIdx;
        let rotDir = ud.rotDir;
        let r = ud.radius;
        let a = ud.angle + (t * Math.PI * 0.05 * rotDir);
        proxy.position.set(
          Math.cos(a) * r,
          cIdx * 2 * this.params.heightRatio,
          Math.sin(a) * r
        );
        let ri = ud.rotInit;
        let rs = ud.rotSpeed;
        proxy.rotation.set(ri.x + rs.x * t, ri.y + rs.y * t, ri.z + rs.z * t);
        proxy.updateMatrix();
        this.setMatrixAt(idx, proxy.matrix);
      });
      this.instanceMatrix.needsUpdate = true;
    }
  }
}

class Grass extends THREE.Mesh{
  constructor(gu, ground){
    let mss = new MeshSurfaceSampler(ground).build();
    let instPos = [];
    let counter = 0;
    let v3 = new THREE.Vector3();
    while(counter < 1000){
      mss.sample(v3);
      if(Math.hypot(v3.x, v3.z) < 10){
        instPos.push(v3.x, v3.y, v3.z);
        counter++;
      }
    }
    
    let pts = [
      [0, 0],
      [0.5, 0.5],
      [0.75, 1], 
      [0.5, 1.5],
      [0, 3]
    ].map(p => {return new THREE.Vector3(p[0], p[1], 0).multiplyScalar(0.1)});

    let g = new THREE.LatheGeometry(new THREE.CatmullRomCurve3(pts).getPoints(20));
    let gi = new THREE.InstancedBufferGeometry().copy(g);
    gi.setAttribute("instPos", new THREE.InstancedBufferAttribute(new Float32Array(instPos), 3));
    //console.log(gi)
    gi.instanceCount = Infinity;
    let m = new THREE.MeshBasicMaterial({
      color: new THREE.Color(1, 0.25, 0).multiplyScalar(0.125),
      onBeforeCompile: shader => {
        shader.uniforms.time = gu.time;
        shader.uniforms.globalBloom = gu.globalBloom;
        shader.uniforms.appearance = this.uniforms.appearance;
        shader.vertexShader = `
          #define S(a, b, t) smoothstep(a, b, t)
          uniform float time;
          uniform float appearance;
          attribute vec3 instPos;
          varying float vNoise;
          ${noise}
          ${shader.vertexShader}
        `.replace(
          `#include <begin_vertex>`,
          `#include <begin_vertex>
            vec3 pos = position;
            
            float appVal =  S((appearance + 0.1) * 10., appearance * 10., length(instPos.xz));
            
            float n = snoise(vec4(instPos * 0.25, time * 0.5));
            n = n * 0.5 + 0.5;
            n *= n * appVal;
            vNoise = n;
            vec3 iPos = pos * n + instPos;
            
            transformed = iPos;
          `
        );
        //console.log("grass VS", shader.vertexShader);
        shader.fragmentShader = `
          varying float vNoise;
          ${shader.fragmentShader}
        `.replace(
          `#include <color_fragment>`,
          `#include <color_fragment>
            
            diffuseColor.rgb += vec3(0.05) * vNoise;
          `
        );
        //console.log("grass FS", shader.fragmentShader);
      }
    });
    super(gi, m);
    this.uniforms = {
      appearance: {value: 0.25}
    };
    this.visible = false;
  }
}

let bgColor = {
  on: 0x240012,
  off: 0x000000
};
let scene = new THREE.Scene();
scene.background = new THREE.Color(bgColor.on);
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.setFromCylindricalCoords( 7, Math.PI * 1.35 - Math.PI / 2, 0.25 );
let renderer = new THREE.WebGLRenderer({ antialias: false });
renderer.toneMapping = THREE.ReinhardToneMapping;
renderer.setSize(innerWidth, innerHeight);
renderer.render(scene, camera);
document.body.appendChild(renderer.domElement);
let postprocessing = new Postprocessing(scene, camera, renderer);
window.addEventListener("resize", (event) => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
  postprocessing.bloomComposer.setSize(innerWidth, innerHeight);
  postprocessing.finalComposer.setSize(innerWidth, innerHeight);
});

let controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, Math.sqrt(3) * 2, 0);
controls.enabled = false;
//fullControls();

let gu = {
  time: { value: 0 },
  globalBloom: { value: 0 }
}; // global uniforms

let light = new THREE.DirectionalLight(0xffffff, 0.5);
let lightAmb = new THREE.AmbientLight(0xffffff, 0.5);
light.position.set(0.5, 0.25, 1);
scene.add(light, lightAmb);

//scene.add(new THREE.GridHelper());

let background = new Background(gu, bgColor);
let ancientCube = new AncientCube(gu);
let ground = new Ground(gu, bgColor);
let plant = new Plant(gu, ancientCube);
let fireflies = new Fireflies(gu);
let tetrahedra = new Tetrahedra(gu);
let grass = new Grass(gu, ground);

let updatables = [tetrahedra];

scene.add(background, ancientCube, ground, plant, fireflies, tetrahedra, grass);

/*let gui = new GUI();
gui.add(plant.flower.petals.uniforms.appearance, "value", 0, 1);*/
/*let stats = new Stats();
document.body.appendChild( stats.dom );*/

let clock = new THREE.Clock(false);

function runRendering() {
  clock.start();
  renderer.setAnimationLoop(() => {
    TWEEN.update();
    controls.update();

    let t = clock.getElapsedTime();
    gu.time.value = t;

    ancientCube.light.position.setFromSphericalCoords(1, t, t);
    ancientCube.light.position.y += Math.sqrt(3);
    
    updatables.forEach(u => {u.update(t)});

    gu.globalBloom.value = 1;
    scene.background.set(bgColor.off);
    postprocessing.bloomComposer.render();

    gu.globalBloom.value = 0;
    scene.background.set(bgColor.on);
    postprocessing.finalComposer.render();
    
    //renderer.render(scene, camera);
    //stats.update();
  });
}

function runSequence() {
  light.intensity = 0;
  ancientCube.scale.setScalar(0.0001);
  plant.uniforms.growth.value = 0;
  plant.flower.scale.setScalar(0.0001);
  plant.flower.petals.uniforms.appearance.value = 0;
  background.uniforms.appearance.value = 0;
  fireflies.material.opacity = 0;
  tetrahedra.scale.setScalar(0.00001);
  tetrahedra.uniforms.appearance.value = 0;
  tetrahedra.params.heightRatio = 1;
  grass.uniforms.appearance.value = 0;
    
  //let isQuick = true;
  let quickSpeed = 10;
  function quick(val){
    return val / (isQuick.value ? quickSpeed : 1);
  }  
  
  let tLights = new TWEEN.Tween({val: 0}).to({val: 1}, quick(25000)) // 0:00 - 0:25
    .onUpdate(function(val){
      light.intesity = 0.5 * val.val;
      lightAmb.intensity = 0.5 * val.val;
      ancientCube.light.intensity = 2 * val.val;
    });
  let tBackground = new TWEEN.Tween(background.uniforms.appearance).to({value: 1}, quick(25000)); // 0:25 - 0:50
  let tCube = new TWEEN.Tween({val: 0}).to({val: 1}, quick(27000)) // 0:50 - 1:17
    .onUpdate(function(val){
      ancientCube.scale.setScalar(0.0001 + 0.9999 * val.val);
    });
  let tPlant = new TWEEN.Tween({ val: 0 }).to({ val: 1 }, quick(86000)) // 1:17 - 2:43
    .easing(TWEEN.Easing.Sinusoidal.InOut)
    .onUpdate(function (val) {
        plant.uniforms.growth.value = val.val;
        camera.position.setFromCylindricalCoords(
          7 + 3 * val.val,
          Math.PI * 1.35 - Math.PI / 2 + Math.PI * 2 * 2 * val.val,
          0.25 + (Math.sqrt(3) * 2 - 0.25) * val.val
        );
      });
  let tFlower = new TWEEN.Tween({val: 0}).to({val: 1}, quick(13000)) // 2:43 - 2:56
    .onUpdate(function(val){
      plant.flower.scale.setScalar(0.0001 + 0.9999 * val.val);
    });
  let tPetals = new TWEEN.Tween(plant.flower.petals.uniforms.appearance).to({value: 1}, quick(13000)); // 2:56 - 3:09
  let tFireflies = new TWEEN.Tween(fireflies.material).to({opacity: 1}, quick(13000)) // 3:09 - 3:22
  let tStopIconOff = new TWEEN.Tween({val: 0}).to({val: 1}, quick(2000))// 3:22 - 3:24
    .onUpdate(function(val){
    stopicon.style.opacity = 1 - val.val;
    controls.autoRotateSpeed = val.val * 0.125;
  })
    .onComplete(function () {
      fullControls();
    });
  let tTetrahedra = new TWEEN.Tween({val: 0}).to({val: 1}, quick(1000))
    .delay(quick(35000)) //3:59 - 4:00
    .easing(TWEEN.Easing.Sinusoidal.InOut)
    .onUpdate(function(val){
    tetrahedra.scale.setScalar(val.val)
  });
  let tTetrahedraBlink = new TWEEN.Tween(tetrahedra.uniforms.appearance).to({value: 1}, quick(10000));
  let tTetrahedraRise = new TWEEN.Tween(tetrahedra.params).to({heightRatio: 3}, quick(37000))
    .delay(quick(39000)); // from tTetrahedra
  let tTetrahedraFall = new TWEEN.Tween(tetrahedra.params).to({heightRatio: 1}, quick(1000)); // after tTetrahedraRise
  let tGrass = new TWEEN.Tween(grass.uniforms.appearance).to({value: 1}, quick(5000)) // 5:55 - end
    .delay(quick(115000)) // from tTetrahedra
    .onStart(function(){grass.visible = true;})
    .easing(TWEEN.Easing.Quintic.Out)
  
  tLights.chain(tBackground);
  tBackground.chain(tCube);
  tCube.chain(tPlant);
  tPlant.chain(tFlower);
  tFlower.chain(tPetals);
  tPetals.chain(tFireflies);
  tFireflies.chain(tStopIconOff);
  tStopIconOff.chain(tTetrahedra);
  tTetrahedraRise.chain(tTetrahedraFall);
  tTetrahedra.chain(tTetrahedraBlink, tTetrahedraRise, tGrass);
  
  tLights.start();
}

function fullControls() {
  controls.enableDamping = true;
  controls.enablePan = false;
  controls.autoRotate = true;
  controls.minDistance = 6;
  controls.maxDistance = 12;
  controls.minPolarAngle = Math.PI * 0.1;
  controls.maxPolarAngle = Math.PI * 0.5;
  controls.enabled = true;
}

              
            
!
999px

Console