File size: 1,885 Bytes
2b7aae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping } from '../../constants.js';
import { WebGLCubeRenderTarget } from '../WebGLCubeRenderTarget.js';

function WebGLCubeMaps(renderer) {
	let cubemaps = new WeakMap();

	function mapTextureMapping(texture, mapping) {
		if (mapping === EquirectangularReflectionMapping) {
			texture.mapping = CubeReflectionMapping;
		} else if (mapping === EquirectangularRefractionMapping) {
			texture.mapping = CubeRefractionMapping;
		}

		return texture;
	}

	function get(texture) {
		if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
			const mapping = texture.mapping;

			if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
				if (cubemaps.has(texture)) {
					const cubemap = cubemaps.get(texture).texture;
					return mapTextureMapping(cubemap, texture.mapping);
				} else {
					const image = texture.image;

					if (image && image.height > 0) {
						const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
						renderTarget.fromEquirectangularTexture(renderer, texture);
						cubemaps.set(texture, renderTarget);

						texture.addEventListener('dispose', onTextureDispose);

						return mapTextureMapping(renderTarget.texture, texture.mapping);
					} else {
						// image not yet ready. try the conversion next frame

						return null;
					}
				}
			}
		}

		return texture;
	}

	function onTextureDispose(event) {
		const texture = event.target;

		texture.removeEventListener('dispose', onTextureDispose);

		const cubemap = cubemaps.get(texture);

		if (cubemap !== undefined) {
			cubemaps.delete(texture);
			cubemap.dispose();
		}
	}

	function dispose() {
		cubemaps = new WeakMap();
	}

	return {
		get: get,
		dispose: dispose,
	};
}

export { WebGLCubeMaps };