Skip to content

Commit

Permalink
[ts][three] Changing material to allow light and shadow
Browse files Browse the repository at this point in the history
  • Loading branch information
davidetan committed Nov 25, 2024
1 parent 18c5924 commit 814b5b5
Show file tree
Hide file tree
Showing 4 changed files with 341 additions and 78 deletions.
244 changes: 244 additions & 0 deletions spine-ts/spine-threejs/example/shadow.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
<html>
<head>
<meta charset="UTF-8" />
<title>spine-threejs</title>

<style>
* {
margin: 0;
padding: 0;
}

body,
html {
height: 100%;
}

canvas {
position: absolute;
width: 100%;
height: 100%;
}
</style>

<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/",
"spine-threejs": "../dist/iife/spine-threejs.esm.js"
}
}
</script>
</head>

<body>
<script type="module">
import * as THREE from "three";
import * as spine from "spine-threejs";
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

let scene, camera, renderer;
let geometry, material, mesh, skeletonMesh, atlas, atlasLoader, atlas2, atlasLoader2, skeletonMesh2;
let assetManager;
let canvas;
let controls;
let lastFrameTime = Date.now() / 1000;

let baseUrl = "assets/";
let skeletonFile = "raptor-pro.json";
let atlasFile = "raptor.atlas";
let animation = "walk";

let skeletonFile2 = "celestial-circus-pro.json";
let atlasFile2 = "celestial-circus.atlas";
let animation2 = "swing";


function init() {
// create the THREE.JS camera, scene and renderer (WebGL)
let width = window.innerWidth,
height = window.innerHeight;
camera = new THREE.PerspectiveCamera(75, width / height, 1, 3000);
camera.position.y = 700;
camera.position.z = 300;
camera.lookAt(new THREE.Vector3(0, 0, 0))
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
renderer.shadowMap.enabled = true

document.body.appendChild(renderer.domElement);
canvas = renderer.domElement;
controls = new OrbitControls(camera, renderer.domElement);

// LIGHTS - Ambient
const ambientLight = new THREE.AmbientLight(0xffffff, 1.0)
scene.add(ambientLight)

// LIGHTS - spotLight
const spotLight = new THREE.SpotLight(0xffffff, 10, 1200, Math.PI / 4, 0, 0)
spotLight.position.set(0, 1000, 0)
spotLight.castShadow = true
spotLight.shadow.mapSize.set(8192, 8192)
spotLight.shadow.bias = -0.00001;

scene.add(spotLight)

const spotLightHepler = new THREE.SpotLightHelper(spotLight)
scene.add(spotLightHepler)

// BOX
const boxGeometry = new THREE.BoxGeometry(400, 10, 100)
const boxMaterial = new THREE.MeshStandardMaterial({
transparent: true,
metalness: 0.5,
roughness: 1,
opacity: 1,
})
const box = new THREE.Mesh(boxGeometry, boxMaterial)
box.position.set(0, 300, -200)
box.castShadow = true
box.receiveShadow = true
scene.add(box)

// PLANE
const planeGeometry = new THREE.PlaneGeometry(2000, 2000)
const planeMaterial = new THREE.MeshStandardMaterial({ color: 0x213573 })
const plane = new THREE.Mesh(planeGeometry, planeMaterial)
plane.rotation.x = -Math.PI / 2
plane.material.side = THREE.DoubleSide
plane.receiveShadow = true
scene.add(plane)

// load the assets required to display the Raptor model
assetManager = new spine.AssetManager(baseUrl);
assetManager.loadText(skeletonFile);
assetManager.loadTextureAtlas(atlasFile);

assetManager.loadText(skeletonFile2);
assetManager.loadTextureAtlas(atlasFile2);

requestAnimationFrame(load);
}

function load(name, scale) {
if (assetManager.isLoadingComplete()) {

// Load the texture atlas using name.atlas and name.png from the AssetManager.
// The function passed to TextureAtlas is used to resolve relative paths.
atlas = assetManager.require(atlasFile);
atlas2 = assetManager.require(atlasFile2);

// Create a AtlasAttachmentLoader that resolves region, mesh, boundingbox and path attachments
atlasLoader = new spine.AtlasAttachmentLoader(atlas);
atlasLoader2 = new spine.AtlasAttachmentLoader(atlas2);

// Create a SkeletonJson instance for parsing the .json file.
let skeletonJson = new spine.SkeletonJson(atlasLoader);
let skeletonJson2 = new spine.SkeletonJson(atlasLoader2);

// Set the scale to apply during parsing, parse the file, and create a new skeleton.
skeletonJson.scale = 0.4;
let skeletonData = skeletonJson.readSkeletonData(
assetManager.require(skeletonFile)
);
skeletonJson2.scale = 0.4;
let skeletonData2 = skeletonJson2.readSkeletonData(
assetManager.require(skeletonFile2)
);

// Create a SkeletonMesh from the data and attach it to the scene
skeletonMesh = new spine.SkeletonMesh({
skeletonData,
materialFactory: param => {
param.alphaTest = 0.001;
return new THREE.MeshStandardMaterial(param);
}
});
skeletonMesh.state.setAnimation(0, animation, true);
scene.add(skeletonMesh);
skeletonMesh.update(0)

skeletonMesh.rotation.set(-Math.PI / 2, 0, 0);
skeletonMesh.position.set(0, 100, 100);

skeletonMesh.castShadow = true;
skeletonMesh.receiveShadow = true;


// Create a SkeletonMesh from the data and attach it to the scene
// skeletonMesh2 = new spine.SkeletonMesh(
// skeletonData2,
// (parameters) => {
// // parameters.depthTest = true;
// // parameters.depthWrite = true;
// // parameters.alphaTest = 0.001;
// // parameters.vertexColors = false;
// }
// );

skeletonMesh2 = new spine.SkeletonMesh({
skeletonData: skeletonData2,
materialFactory: param => {
param.alphaTest = 0.001;
return new THREE.MeshStandardMaterial(param);
}
});

skeletonMesh2.state.setAnimation(0, animation2, true);
scene.add(skeletonMesh2);
skeletonMesh2.update(0)

skeletonMesh2.rotation.set(-Math.PI / 2.4, 0, 0);
skeletonMesh2.position.set(0, 150, 100);

skeletonMesh2.castShadow = true;
skeletonMesh2.receiveShadow = true;

requestAnimationFrame(render);
} else requestAnimationFrame(load);
}

let lastTime = Date.now();
function render() {
// calculate delta time for animation purposes
let now = Date.now() / 1000;
let delta = now - lastFrameTime;
lastFrameTime = now;

// resize canvas to use full page, adjust camera/renderer
resize();

// Update orbital controls
controls.update();

// update the animation
skeletonMesh.update(delta);
skeletonMesh2.update(delta);

// render the scene
renderer.render(scene, camera);

requestAnimationFrame(render);
}

function resize() {
let w = window.innerWidth;
let h = window.innerHeight;
if (canvas.width != w || canvas.height != h) {
canvas.width = w;
canvas.height = h;
}

camera.aspect = w / h;
camera.updateProjectionMatrix();

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(w, h);
}

init();
</script>
</body>
</html>
39 changes: 24 additions & 15 deletions spine-ts/spine-threejs/src/MeshBatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,16 @@
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/

import { SkeletonMeshMaterial, SkeletonMeshMaterialParametersCustomizer } from "./SkeletonMesh.js";
import * as THREE from "three"

import { ThreeJsTexture, ThreeBlendOptions } from "./ThreeJsTexture.js";
import { BlendMode } from "@esotericsoftware/spine-core";
import { SkeletonMesh } from "./SkeletonMesh.js";

type MaterialWithMap = THREE.Material & { map: THREE.Texture | null };
export class MeshBatcher extends THREE.Mesh {
public static MAX_VERTICES = 10920;

private static VERTEX_SIZE = 9;
private vertexBuffer: THREE.InterleavedBuffer;
private vertices: Float32Array;
Expand All @@ -41,9 +45,9 @@ export class MeshBatcher extends THREE.Mesh {
private indicesLength = 0;
private materialGroups: [number, number, number][] = [];

constructor (maxVertices: number = 10920, private materialCustomizer: SkeletonMeshMaterialParametersCustomizer = (parameters) => { }) {
constructor (maxVertices: number = MeshBatcher.MAX_VERTICES, private materialFactory: (parameters: THREE.MaterialParameters) => THREE.Material) {
super();
if (maxVertices > 10920) throw new Error("Can't have more than 10920 triangles per batch: " + maxVertices);
if (maxVertices > MeshBatcher.MAX_VERTICES) throw new Error("Can't have more than 10920 triangles per batch: " + maxVertices);
let vertices = this.vertices = new Float32Array(maxVertices * MeshBatcher.VERTEX_SIZE);
let indices = this.indices = new Uint16Array(maxVertices * 3);
let geo = new THREE.BufferGeometry();
Expand All @@ -57,7 +61,7 @@ export class MeshBatcher extends THREE.Mesh {
geo.drawRange.start = 0;
geo.drawRange.count = 0;
this.geometry = geo;
this.material = [new SkeletonMeshMaterial(materialCustomizer)];
this.material = [];
}

dispose () {
Expand All @@ -80,13 +84,13 @@ export class MeshBatcher extends THREE.Mesh {
geo.clearGroups();
this.materialGroups = [];
if (this.material instanceof THREE.Material) {
const meshMaterial = this.material as SkeletonMeshMaterial;
meshMaterial.uniforms.map.value = null;
const meshMaterial = this.material as MaterialWithMap;
meshMaterial.map = null;
meshMaterial.blending = THREE.NormalBlending;
} else if (Array.isArray(this.material)) {
for (let i = 0; i < this.material.length; i++) {
const meshMaterial = this.material[i] as SkeletonMeshMaterial;
meshMaterial.uniforms.map.value = null;
const meshMaterial = this.material[i] as MaterialWithMap;
meshMaterial.map = null;
meshMaterial.blending = THREE.NormalBlending;
}
}
Expand Down Expand Up @@ -167,14 +171,14 @@ export class MeshBatcher extends THREE.Mesh {

if (Array.isArray(this.material)) {
for (let i = 0; i < this.material.length; i++) {
const meshMaterial = this.material[i] as SkeletonMeshMaterial;
const meshMaterial = this.material[i] as MaterialWithMap;

if (!meshMaterial.uniforms.map.value) {
if (!meshMaterial.map) {
updateMeshMaterial(meshMaterial, slotTexture, blendingObject);
return i;
}

if (meshMaterial.uniforms.map.value === slotTexture
if (meshMaterial.map === slotTexture
&& blendingObject.blending === meshMaterial.blending
&& (blendingObject.blendSrc === undefined || blendingObject.blendSrc === meshMaterial.blendSrc)
&& (blendingObject.blendDst === undefined || blendingObject.blendDst === meshMaterial.blendDst)
Expand All @@ -185,8 +189,13 @@ export class MeshBatcher extends THREE.Mesh {
}
}

const meshMaterial = new SkeletonMeshMaterial(this.materialCustomizer);
updateMeshMaterial(meshMaterial, slotTexture, blendingObject);
const meshMaterial = this.materialFactory(SkeletonMesh.DEFAULT_MATERIAL_PARAMETERS);

if (!('map' in meshMaterial)) {
throw new Error("The material factory must return a material having the map property for the texture.");
}

updateMeshMaterial(meshMaterial as MaterialWithMap, slotTexture, blendingObject);
this.material.push(meshMaterial);
group = this.material.length - 1;
} else {
Expand All @@ -197,8 +206,8 @@ export class MeshBatcher extends THREE.Mesh {
}
}

function updateMeshMaterial (meshMaterial: SkeletonMeshMaterial, slotTexture: THREE.Texture, blending: ThreeBlendOptions) {
meshMaterial.uniforms.map.value = slotTexture;
function updateMeshMaterial (meshMaterial: MaterialWithMap, slotTexture: THREE.Texture, blending: ThreeBlendOptions) {
meshMaterial.map = slotTexture;
Object.assign(meshMaterial, blending);
meshMaterial.needsUpdate = true;
}
Loading

0 comments on commit 814b5b5

Please sign in to comment.