From 19d9630aedf9a1817d2d20fc337111a757e830ac Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Tue, 12 Mar 2019 16:59:19 +0100 Subject: [PATCH] Implement basic lighting. --- src/open.js | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/src/open.js b/src/open.js index ea1c606..3de49db 100644 --- a/src/open.js +++ b/src/open.js @@ -4,15 +4,21 @@ const STAR_POINTS = 5; let scene, camera, renderer; let group; +let lights = {}; function addStar() { let geometry = new THREE.BufferGeometry(); let vertices = starCoordinates(2, 3, 0); + geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3)); geometry.setIndex(filledStarIndices()); - let material = new THREE.MeshBasicMaterial({color: 0x00ff00}); - material.side = THREE.DoubleSide; + geometry.computeVertexNormals(); + let material = new THREE.MeshStandardMaterial({ + side: THREE.DoubleSide, + color: 0x00ff00, + }); let star = new THREE.Mesh(geometry, material); + star.receiveShadow = true; group.add(star); } @@ -23,16 +29,35 @@ function startOpenAnimation() { renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); + renderer.shadowMap.enabled = true; + renderer.shadowMap.autoUpdate = true; document.body.appendChild(renderer.domElement); group = new THREE.Group(); scene.add(group); + + initLighting(); addStar(); loadFont(); requestAnimationFrame(animate) } +function initLighting() { + let spotLight = new THREE.PointLight(0xffffff); + spotLight.position.set(10, 10, 10); + spotLight.castShadow = true; + spotLight.shadow.mapSize.width = 1024; // default + spotLight.shadow.mapSize.height = 1024; // default + scene.add(spotLight); + + let ambient = new THREE.AmbientLight(0x404040); + scene.add(ambient); + + lights.spotLight = spotLight; + lights.ambient = ambient; +} + function loadFont() { import('three/examples/fonts/helvetiker_bold.typeface').then(function (data) { let font = new THREE.Font(data); @@ -42,12 +67,15 @@ function loadFont() { height: 0.3, curveSegments: 12 }).center(); + geometry.computeFaceNormals(); - let textMaterial = new THREE.MeshBasicMaterial({ + let textMaterial = new THREE.MeshStandardMaterial({ color: 0xff00ff }); let mesh = new THREE.Mesh(geometry, textMaterial); + mesh.castShadow = true; + mesh.receiveShadow = true; group.add(mesh); }); } @@ -93,7 +121,7 @@ function starCoordinates(innerRadius, outerRadius, z) { for (let i = 0; i < STAR_POINTS; ++i) { const offset = 3 * 2 * i; - buf[offset + 0] = Math.sin(STAR_SLICE * i) * outerRadius; + buf[offset] = Math.sin(STAR_SLICE * i) * outerRadius; buf[offset + 1] = Math.cos(STAR_SLICE * i) * outerRadius; buf[offset + 3] = Math.sin(STAR_SLICE * (i + 0.5)) * innerRadius; buf[offset + 4] = Math.cos(STAR_SLICE * (i + 0.5)) * innerRadius;