initial with specular

This commit is contained in:
Evert Prants 2022-12-11 12:31:34 +02:00
commit 0af957094b
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
21 changed files with 1723 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"semi": true,
"singleQuote": true
}

12
index.html Normal file
View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Globe test</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

1316
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "globetest",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"devDependencies": {
"@types/three": "^0.146.0",
"typescript": "^4.6.4",
"vite": "^3.2.3",
"vite-plugin-plain-text": "^1.2.1"
},
"dependencies": {
"three": "^0.147.0"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 943 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 452 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 249 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 476 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 368 KiB

1
public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

113
src/globe.ts Normal file
View File

@ -0,0 +1,113 @@
import {
SphereGeometry,
Texture,
Mesh,
MeshPhongMaterial,
Object3D,
TextureLoader,
Color,
DirectionalLight,
Shader,
ShaderMaterial,
} from 'three';
import { plainText as vertexShader } from './shaders/earth.vert';
import { plainText as fragmentShader } from './shaders/earth.frag';
export class Globe extends Object3D {
private sphere = new SphereGeometry(1, 32, 32);
private earthMaterial?: ShaderMaterial;
public earthMesh?: Mesh;
private loader = new TextureLoader();
public async loadTexture(name: string) {
return new Promise<Texture>((resolve, reject) => {
this.loader.load(`/${name}`, resolve, undefined, reject);
});
}
public async loadArray(names: string[]) {
return Promise.all(names.map((name) => this.loadTexture(name)));
}
public async initialize(light: DirectionalLight) {
const textures = await this.loadArray([
'earth/2k_earth_daymap.jpg',
'earth/2k_earth_nightmap.jpg',
'earth/2k_earth_clouds.jpg',
'earth/2k_earth_normal_map.jpg',
'earth/2k_earth_specular_map.jpg',
]);
this.earthMaterial = new ShaderMaterial({
fragmentShader,
vertexShader,
uniforms: {
light: { value: light.position },
texture0: { value: textures[0] },
texture1: { value: textures[1] },
normalmap: { value: textures[3] },
specularMap: { value: textures[4] },
shininess: { value: 1.0 },
specular: { value: new Color('gray') },
},
});
// this.earthMaterial = new MeshPhongMaterial();
// this.earthMaterial.onBeforeCompile = (shader) => {
// let fragment = shader.fragmentShader;
// let vertex = shader.vertexShader;
// vertex = injectBefore(
// vertex,
// 'void main() {',
// `uniform vec3 lightDirection;\nvarying vec3 surfaceToLight;\n`
// );
// vertex = injectBefore(
// vertex,
// '#include <logdepthbuf_vertex>',
// 'surfaceToLight = mat3(modelViewMatrix) * lightDirection;\n'
// );
// fragment = injectBefore(
// fragment,
// 'void main() {',
// `varying vec3 surfaceToLight;\nuniform sampler2D nightmap;\n`
// );
// fragment = replaceWith(fragment, '#include <map_fragment>', '');
// fragment = injectBefore(
// fragment,
// '#include <lights_phong_fragment>',
// `
// vec4 sampledDiffuseColor = texture2D(map, vUv);
// vec4 sampledDiffuseColorNight = texture2D(nightmap, vUv);
// diffuseColor *= sampledDiffuseColor;
// `
// );
// fragment = injectBefore(
// fragment,
// '#include <output_fragment>',
// `float cosineAngleSunToNormal = dot(geometryNormal, surfaceToLight);
// cosineAngleSunToNormal = clamp( cosineAngleSunToNormal * 1.0, -1.0, 1.0);
// float mixAmount = cosineAngleSunToNormal * 0.5 + 0.5;
// outgoingLight = mix(sampledDiffuseColorNight.xyz, outgoingLight, mixAmount);
// `
// );
// console.log(fragment);
// shader.uniforms.nightmap = { value: textures[1] };
// shader.uniforms.lightDirection = {
// value: light.position.clone(),
// };
// shader.fragmentShader = fragment;
// shader.vertexShader = vertex;
// };
// this.earthMaterial.map = textures[0];
// this.earthMaterial.normalMap = textures[3];
// this.earthMaterial.specularMap = textures[4];
// this.earthMaterial.specular = new Color('grey');
this.earthMesh = new Mesh(this.sphere, this.earthMaterial);
this.add(this.earthMesh);
}
public tick() {}
}

32
src/main.ts Normal file
View File

@ -0,0 +1,32 @@
import { Globe } from './globe';
import { Renderer } from './renderer';
import { DirectionalLight } from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import './style.css';
const main = new Renderer();
const dirLight = new DirectionalLight(0xffffff, 1);
dirLight.position.set(10, 10, 10);
main.scene.add(dirLight);
const globe = new Globe();
main.resize();
globe.initialize(dirLight).catch(console.error);
main.scene.add(globe);
main.camera.position.set(0, 0, 2);
const control = new OrbitControls(main.camera, main.canvas);
function tick() {
requestAnimationFrame(tick);
control.update();
globe.rotateY(Math.PI * 0.0005);
main.render();
globe.tick();
}
window.addEventListener('resize', () => main.resize());
document.querySelector('#app')?.appendChild(main.canvas);
tick();

33
src/renderer.ts Normal file
View File

@ -0,0 +1,33 @@
import { PerspectiveCamera, Scene, WebGLRenderer } from 'three';
export class Renderer {
public width = window.innerWidth;
public height = window.innerHeight;
public renderer = new WebGLRenderer({ antialias: true });
public scene = new Scene();
public camera = new PerspectiveCamera(
90,
this.width / this.height,
0.1,
10000
);
constructor() {}
resize() {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.renderer.setSize(this.width, this.height);
this.camera.aspect = this.width / this.height;
this.camera.updateProjectionMatrix();
}
render() {
this.renderer.render(this.scene, this.camera);
}
get canvas() {
return this.renderer.domElement;
}
}

46
src/shaders/earth.frag Normal file
View File

@ -0,0 +1,46 @@
#define EARTH
varying vec3 vViewPosition;
varying vec3 vLightDirection;
varying vec2 vUv;
varying vec3 vEyeNormal;
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
uniform sampler2D texture0;
uniform sampler2D texture1;
uniform sampler2D specularMap;
#include <common>
#include <packing>
#include <normal_pars_fragment>
#include <normalmap_pars_fragment>
void main() {
vec4 sampledDiffuseColor = texture2D(texture0, vUv);
vec4 sampledDiffuseColorNight = texture2D(texture1, vUv);
vec3 N = normalize(vEyeNormal);
vec3 L = normalize(vLightDirection);
vec3 V = normalize(vViewPosition);
vec3 H = normalize(V + L);
float diffuseAngle = dot(N, L);
float specularAngle = dot(N, H);
float cosineAngleSunToNormal = clamp( diffuseAngle * 10.0, -1.0, 1.0);
float mixAmount = cosineAngleSunToNormal * 0.5 + 0.5;
vec4 texelSpecular = texture2D(specularMap, vUv);
float specularStrength = texelSpecular.r;
vec3 outgoingLight = mix(sampledDiffuseColorNight.xyz, sampledDiffuseColor.xyz, mixAmount);
float specularAmount = max(0.0, specularAngle);
specularAmount = pow(specularAmount, 32.0 * shininess) * specularStrength;
gl_FragColor = vec4( outgoingLight + specular * specularAmount, 1.0 );
}

22
src/shaders/earth.vert Normal file
View File

@ -0,0 +1,22 @@
#define EARTH
varying vec3 vViewPosition;
varying vec3 vLightDirection;
varying vec2 vUv;
varying vec3 vEyeNormal;
#include <common>
#include <normal_pars_vertex>
uniform vec3 light;
void main() {
#include <beginnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <project_vertex>
vViewPosition = - mvPosition.xyz;
vLightDirection = (viewMatrix * vec4(light, 0.)).xyz;
vec4 viewPos = modelViewMatrix * vec4(position, 1.0);
vEyeNormal = (modelViewMatrix * vec4(normal, 0.)).xyz;
vUv = uv;
}

51
src/style.css Normal file
View File

@ -0,0 +1,51 @@
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

15
src/utility.ts Normal file
View File

@ -0,0 +1,15 @@
export function injectBefore(
text: string,
before: string,
toInsert: string
): string {
return text.replace(before, `${toInsert}${before}`);
}
export function replaceWith(
text: string,
before: string,
after: string
): string {
return text.replace(before, after);
}

9
src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
/// <reference types="vite/client" />
declare module '*.vert' {
export const plainText: string;
}
declare module '*.frag' {
export const plainText: string;
}

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ESNext", "DOM"],
"moduleResolution": "Node",
"strict": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"skipLibCheck": true
},
"include": ["src"]
}

6
vite.config.js Normal file
View File

@ -0,0 +1,6 @@
import { defineConfig } from 'vite';
import plainText from 'vite-plugin-plain-text';
export default defineConfig({
plugins: [plainText.default(/\.vert|\.frag$/)],
});