import { RenderPass }	from "../framework/RenderPass.js";

import Shader			from "../framework/WebGpu.js";

import Matrix4			from "../framework/Matrix4.js";


export class SkySpherePass extends RenderPass {

	async create( ) {

		this.shader					= new Shader( this.device );

		this.shader.topology		= "triangle-list";

		this.shader.setCanvas( this.pipeline.canvas );

		this._configureCanvasContext();

		await this.shader.setup( "shaders/sky_sphere.wgsl" );

		this.shader.setAttribute( "position", this.pipeline.memory.skyPositions );

		this.shader.setAttribute( "normal", this.pipeline.memory.skyNormals );

		this.shader.setIndices( this.pipeline.memory.skyIndices );

	}


	async bindBuffers( ) {

		const viewMatrixData		= this.pipeline.camera.getViewMatrix();

		const projectionMatrixData	= Matrix4.createProjectionMatrix( this.pipeline.camera, this.pipeline.canvas );

		const viewProjectionMatrix	= Matrix4.multiply( projectionMatrixData, viewMatrixData );

		const cameraWorldMatrix		= Matrix4.invert( viewMatrixData );

		const cameraPosition		= Matrix4.getColumn( cameraWorldMatrix, 3 );

		this.shader.setVariable( "viewProjectionMatrix", viewProjectionMatrix );

		this.shader.setVariable( "cameraPosition", cameraPosition );

		this.shader.createBindGroups();

	}


	async execute( ) {

		// Rendered through the scene / RenderSystem; execute uses the mesh instead.

	}


	_configureCanvasContext( ) {

		if ( this.pipeline.canvasConfigured ) {

			return;

		}

		const context	= this.pipeline.canvas.getContext( "webgpu" );

		const format	= navigator.gpu.getPreferredCanvasFormat();

		context.configure( {

			device: this.device,

			format: format,

			alphaMode: "opaque"

		} );

		this.pipeline.canvasConfigured = true;

	}


}
