<?php require_once("utils/DBHelper.php")?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Furniture</title>
    <style>

        #c {
            width: 100%;
            height: 100%;
            display: block;
        }

        html, body {
            margin: 0;
            height: 100%;
        }
        #navigation{

            vertical-align: top;
            color:black;
            text-align: center;
            font-size:smaller;


        }
        #navigation a{

            color:black;
            vertical-align: top;
            text-decoration: none;

        }
        #navigation a:hover{
            color:red;
        }

        #exporter:hover {
            cursor:pointer;
            color: red;
        }

    </style>
</head>
<?php

use f\DBHelper;
$helper = new DBHelper();

if(isset($_GET['id'])){

    $id = $_GET['id'];
}else{
    return;
}

$results = f\queryById($id);
if($results !=null || sizeof($results)>0){
    $result = $results[0];
    $root= f\getPath($result);
    $url = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else{

    return;
}



?>
<body>
<div id="navigation"><A href="index.php">返回</A>&nbsp;&nbsp;&nbsp;&nbsp;<span id="exporter">输出模型</span>
</div>
<canvas id="c"></canvas>
<script  type="importmap">{
	"imports": {
		"three": "./javascript/three.module.js",
		"three/addons/": "./javascript/jsm/"
	}
}</script><!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
</body>

<script type="module">

    import * as THREE from 'three';
    import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
    import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
    import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";


    function main() {

        const canvas = document.querySelector( '#c' );
        const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
        var exporter,link,group;

        const fov = 45;
        const aspect = 2; // the canvas default
        const near = 0.1;
        const far = 100;
        const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
        camera.position.set( 0, 10, 20 );

        const controls = new OrbitControls( camera, canvas );
        controls.target.set( 0, 5, 0 );
        controls.update();

        const scene = new THREE.Scene();
        scene.background = new THREE.Color( 'pink' );

        {

            const planeSize = 100;

            const loader = new THREE.TextureLoader();
            const texture = loader.load( 'https://threejs.org/manual/examples/resources/images/checker.png' );
            texture.wrapS = THREE.RepeatWrapping;
            texture.wrapT = THREE.RepeatWrapping;
            texture.magFilter = THREE.NearestFilter;
            texture.colorSpace = THREE.SRGBColorSpace;
            const repeats = planeSize / 2;
            texture.repeat.set( repeats, repeats );

            const planeGeo = new THREE.PlaneGeometry( planeSize, planeSize );
            const planeMat = new THREE.MeshPhongMaterial( {
                map: texture,
                side: THREE.DoubleSide,
            } );
            const mesh = new THREE.Mesh( planeGeo, planeMat );
            mesh.rotation.x = Math.PI * - .5;
            //scene.add( mesh );

            exporter = new GLTFExporter();
            link = document.createElement( 'a' );
            link.style.display = 'none';
            document.body.appendChild( link );

            document.getElementById("exporter").addEventListener("click",function () {
                exportGLTF(group);
            });

        }

        function save( blob, filename ) {

            link.href = URL.createObjectURL( blob );
            link.download = filename;
            link.click();

            // URL.revokeObjectURL( url ); breaks Firefox...

        }

        function saveString( text, filename ) {

            save( new Blob( [ text ], { type: 'text/plain' } ), filename );

        }

        function exportGLTF(input){

            const options = {
                trs: true,
                onlyVisible: true,
                truncateDrawRange: true,
                binary: true,
                forcePowerOfTwoTextures: true,
                maxTextureSize: Number( 4096 ) || Infinity // To prevent NaN value
            };

            exporter.parse(input,function(result){

                if ( result instanceof ArrayBuffer ) {

                    saveArrayBuffer( result, 'scene.glb' );

                } else {

                    const output = JSON.stringify( result, null, 2 );
                    console.log( output );
                    saveString( output, 'scene.gltf' );

                }

            },options);

        }


        {

            const skyColor = 0xB1E1FF; // light blue
            const groundColor = 0xB97A20; // brownish orange
            const intensity = 2;
            const light = new THREE.HemisphereLight( skyColor, groundColor, intensity );
            scene.add( light );

        }

        {

            const color = 0xFFFFFF;
            const intensity = 2.5;
            const light = new THREE.DirectionalLight( color, intensity );
            light.position.set( 5, 10, 2 );
            scene.add( light );
            scene.add( light.target );

        }

        function frameArea( sizeToFitOnScreen, boxSize, boxCenter, camera ) {

            const halfSizeToFitOnScreen = sizeToFitOnScreen *  5;
            const halfFovY = THREE.MathUtils.degToRad( camera.fov * 5 );
            const distance = halfSizeToFitOnScreen / Math.tan( halfFovY );
            // compute a unit vector that points in the direction the camera is now
            // in the xz plane from the center of the box
            const direction = ( new THREE.Vector3() )
                .subVectors( camera.position, boxCenter )
                .multiply( new THREE.Vector3( 1, 0, 1 ) )
                .normalize();

            // move the camera to a position distance units way from the center
            // in whatever direction the camera was from the center already
            camera.position.copy( direction.multiplyScalar( distance ).add( boxCenter ) );

            // pick some near and far values for the frustum that
            // will contain the box.
            camera.near = boxSize / 15;
            camera.far = boxSize * 15;

            camera.updateProjectionMatrix();

            // point the camera to look at the center of the box
            camera.lookAt( boxCenter.x, boxCenter.y, boxCenter.z );

        }

        {

            const gltfLoader = new GLTFLoader();
            gltfLoader.load( '<?php echo $root?>', ( gltf ) => {

                const root = gltf.scene;
                group = root;
                scene.add( root );

                // compute the box that contains all the stuff
                // from root and below
                const box = new THREE.Box3().setFromObject( root );

                const boxSize = box.getSize( new THREE.Vector3() ).length();
                const boxCenter = box.getCenter( new THREE.Vector3() );

                // set the camera to frame the box
                frameArea( boxSize , boxSize, boxCenter, camera );

                // update the Trackball controls to handle the new size
                controls.maxDistance = boxSize * 2  ;
                controls.target.copy( boxCenter );
                controls.update();

            } );

        }







        function resizeRendererToDisplaySize( renderer ) {

            const canvas = renderer.domElement;
            const width = canvas.clientWidth;
            const height = canvas.clientHeight;
            const needResize = canvas.width !== width || canvas.height !== height;
            if ( needResize ) {

                renderer.setSize( width, height, false );

            }

            return needResize;

        }

        function render() {



            if ( resizeRendererToDisplaySize( renderer ) ) {

                const canvas = renderer.domElement;
                camera.aspect = canvas.clientWidth / canvas.clientHeight;
                camera.updateProjectionMatrix();

            }



            renderer.render( scene, camera );

            requestAnimationFrame( render );

        }



        requestAnimationFrame( render );

    }

    main();

</script>

</html>