2050.earth 代碼分析-——第七部分結束(years)


/*
██╗   ██╗███████╗ █████╗ ██████╗ ███████╗
╚██╗ ██╔╝██╔════╝██╔══██╗██╔══██╗██╔════╝
 ╚████╔╝ █████╗  ███████║██████╔╝███████╗
  ╚██╔╝  ██╔══╝  ██╔══██║██╔══██╗╚════██║
   ██║   ███████╗██║  ██║██║  ██║███████║
   ╚═╝   ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝
*/

Planet.prototype.showYear = function ( _year, onReady ) {
    
    var scope = this;
    // console.log(">>>! ", this.main.controls.autoRotate );

    if( PlanetData.YEAR_ID ){
        this.hidePlanet(  _year, onReady );
        return;
    }

    PlanetData.YEAR_ID = _year;
    PlanetData.YEAR = PlanetData.years[ _year ];

    if( PlanetData.YEAR.earth_image ){

        show();

    }else{

        PlanetData.YEAR.earth_image = this.projectiveImage = new ProjectiveImage( PlanetData.YEAR.earth_url, show );
    }
    
    $(".timeline").css( "pointer-events", "none" );

    function show () {
		
        var t = 2.25;
		scope.main.animateIn( t, function(){
			scope.state = scope.IDLE;
            scope.commentToggle( true );
            $(".timeline").css( "pointer-events", "auto" );
		});

        t = t/3*2;
		scope.planetLocations.show( _year, t );
		scope.planetPointed.show( _year, t );
		scope.planetContour.show( _year, t );

		if( onReady ) onReady();

        // show commentary tip
        if( scope._PlanetCommentPopup ) scope._PlanetCommentPopup.showRandom();
	}

}

Planet.prototype.hidePlanet = function ( _year, onReady, t ) {


    this.state = this.ANIMATED;
    var scope = this;
    // console.log("hidePlanet");
    this.deactivateHexagon();
    
    $(".timeline").css( "pointer-events", "none" );
    scope.commentToggle( false );
    
    if( t===undefined ) t = 1.5;

    this.main.animateOut( t, function(){
        PlanetData.YEAR_ID = undefined;
        scope.showYear( _year, onReady );
        // $(".timeline").css( "pointer-events", "auto" );
    });

    scope.planetLocations.hide( t/2 );
    scope.planetPointed.hide( t/2 );
    scope.planetContour.hide( t/2 );

    if( this._PlanetCommentPopup ) this._PlanetCommentPopup.hide();

}
THREE.Text = function ( params ) {
	
	// params.text
	// params.font_propotion
	// params.font
	// params.width
	// params.height
	// params.transparent
	// params.offset_x
	// params.offset_y
	// params.multiplier
	// params.fillStyle
	// params.debug

    var scope = this;
    scope.offset_x = params.offset_x || 0;
    scope.border_x = params.border_x || 0;
    scope.offset_y = params.offset_y || 0;
    scope.font = params.font || "Arial";
    scope.font_propotion = params.font_propotion || 20;
    // scope.multiplier = params.multiplier || 1;
    scope.fillStyle = params.fillStyle || "rgba(255,0,0, 0.95)";
    scope.fontStyle = params.fontStyle || "";

    // scope.pow_coef_x = 1;

	var canvas = scope.canvas = document.createElement('canvas');
	var context = scope.context = canvas.getContext('2d');
	if( params.debug ){
		document.body.appendChild( canvas );
		// $(canvas).css({ position: "absolute", top: 0, left: 0 });
		canvas.style.position = "absolute";
		canvas.style.top = 0;
		canvas.style.left = 0;
	}
    
	var texture = new THREE.Texture(canvas) 
	texture.needsUpdate = true;
    texture.generateMipmaps = false;
	texture.magFilter = THREE.LinearFilter;
	texture.minFilter = THREE.LinearFilter;
	texture.wrapS = THREE.ClampToEdgeWrapping;
	// texture.repeat.x = - 1;
	texture.needsUpdate = true;

    var material = new THREE.MeshBasicMaterial( { map: texture } );
    material.transparent = params.transparent || false;
    material.side = params.side==undefined ? THREE.DoubleSide : params.side;
    material.depthWrite = !true;
    // material.wireframe = true;

    var g = new THREE.PlaneGeometry( 1, 1 );
    var m = new THREE.Matrix4();
    m.setPosition( new THREE.Vector3( .5, .5, 0 ) );
    g.applyMatrix(m);

    // var material_test = new THREE.MeshBasicMaterial( { color: 0xff0000 } );

    var mesh = scope.mesh = new THREE.Mesh( g, material );
    mesh.matrixAutoUpdate = false;
    mesh.visible = false;
    
    mesh.setSize = function ( width, height) {
        // console.log("setSize: ", width);

        mesh.width = width;
    	mesh.height = height;

        var w = mesh.canvas_vis_width = Math.floor( width * 100 );
        var h = mesh.canvas_vis_height = Math.floor( height * 100 );
        var wc = Utils.nearestPow2( w );
        var hc = Utils.nearestPow2( h );
        canvas.width = wc;
    	canvas.height = hc;
        texture.repeat.x = mesh.pow_coef_x = w / wc;
        texture.repeat.y = mesh.pow_coef_y = h / hc;
        texture.offset.y = ( 1 - texture.repeat.y );
        // console.log( "setSize>> W:", width, w, wc, mesh.pow_coef_x );
        // console.log( "setSize>> H:", height, h, hc, mesh.pow_coef_y );
    	mesh.scale.set( width, height, 1 );
        mesh.updateMatrix();
    }

    mesh.setWidth = function ( text ) {
        var w;
        if( typeof text == "string" ){// get width from text
            setupText();
            w = ( context.measureText( text ).width + scope.offset_x + scope.border_x ) / 100;
            // console.log("setWidth: ", text, w );
            // console.log(">: ", scope.offset_x, scope.border_x );
        }else w = text;

        mesh.setSize( w, params.height );

        return w;

    }

    mesh.setText = function ( text, width ) {
        // console.log("\n");
    	// console.log("setText: ", scope.offset_x );

        mesh.setWidth( width || text );
        
        context.clearRect( 0, 0, canvas.width, canvas.height );
        
        if( mesh.prefill ) mesh.prefill.apply( scope );
        
        // console.log( ">>> ", context.font );

        // debug !!!
        // context.fillStyle = "#FF0000";
        // // context.fillRect( 0, 0, mesh.canvas_vis_width, mesh.canvas_vis_height );
        // context.fillRect( 0, 0, canvas.width, canvas.height );
        // debug !!!

        
        setupText();
        // context.fillStyle = "#000000";
        context.fillText( text, scope.offset_x, mesh.canvas_vis_height / 2 );

   		texture.needsUpdate = true;
    }

    function setupText () {
        scope.font_height = scope.font_propotion * mesh.canvas_vis_height;
        context.font = scope.fontStyle +" "+ ( scope.font_height ) + 'px '+scope.font;//"Bold 40px Arial";
        context.fillStyle = scope.fillStyle;
        context.textBaseline = "middle";
    }
    // mesh.setText( "init" );


    mesh.show = function( _delay ){
        mesh.scale.x = .001;
        mesh.matrixAutoUpdate = true;
        TweenLite.killTweensOf( mesh.scale );
        TweenLite.to( mesh.scale, .2, {
            delay: _delay,
            x: Math.floor( mesh.width ),
            ease: Sine.easeOut,
            onStart: function() {
                mesh.visible = true;
            },
            onComplete: function() {
                mesh.updateMatrix();
                mesh.matrixAutoUpdate = false;
            }
        });
    }

    mesh.hide = function( _delay ){
        if( !mesh.visible ) return;
        mesh.scale.x = 0;
        mesh.matrixAutoUpdate = true;
        TweenLite.killTweensOf( mesh.scale );
        TweenLite.to( mesh.scale, .2, {
            delay: _delay,
            x: .001,
            ease: Sine.easeIn,
            onComplete: function() {
                mesh.visible = false;
                mesh.updateMatrix();
                mesh.matrixAutoUpdate = false;
            }
        });
    }

    return mesh;
}
// IMAGE
function ProjectiveImage(_img_url, _onload) {

	var projectionContext;

    var img = document.createElement("img");
    img.src = _img_url;
    img.onload = function(){
    	var projectionCanvas = document.createElement('canvas');
	    projectionContext = projectionCanvas.getContext('2d');
	    projectionCanvas.width = img.width;
	    projectionCanvas.height = img.height;
	    projectionContext.drawImage(img, 0, 0, img.width, img.height);
	    if(_onload) _onload();
    }

    var pixelData = null;

    var maxLat = -100;
    var maxLon = 0;
    var minLat = 0;
    var minLon = 0;

    this.isLand = function (lat, lon) {

	    var x = parseInt(img.width * ( lon + 180 ) / 360);
	    var y = parseInt(img.height * ( lat + 90 ) / 180);
	    
	    if(pixelData == null){
	        pixelData = projectionContext.getImageData(0,0,img.width, img.height);
	    }
	    return pixelData.data[(y * pixelData.width + x) * 4] === 0;
	};

	this.isLandByUV = function (u, v) {	    
	    if(pixelData == null){
	        pixelData = projectionContext.getImageData(0,0,img.width, img.height);
	    }
	    var x = parseInt(img.width * u );
	    var y = parseInt(img.height * v );
	   	return pixelData.data[(y * pixelData.width + x) * 4] === 0;
	};

	this.getUV = function ( lat, lon ) {
		return {
			x: ( lon + 180 ) / 360,
	    	y: ( lat + 90 ) / 180
	    }
	}

	this.getUVOfPI = function ( lat, lon ) {
		return {
			x: ( lon + Math.PI ) / Utils.PI2,
	    	y: ( lat + Utils.PIh ) / Math.PI
	    }
	}
}

var Utils = new function(){

	this.getHalfPoint = function (p1, p2){
        var p1 = new THREE.Vector3(p1.x,p1.y,p1.z);
        var p2 = new THREE.Vector3(p2.x,p2.y,p2.z);
        var b2 = p2.sub(p1).divideScalar(2).add(p1);
        return b2;
    }

    this.getRandSides = function (value) {
    	return Math.random()*value*2-value;
    }

    this.PIh = Math.PI/2;
    this.PI2 = Math.PI*2;

    THREE.Vector3.ZERO = new THREE.Vector3();

    this.createHexagon = function ( h, orient, material, ring_width ) {
        var g = ring_width ? new THREE.RingGeometry( h, h + ring_width, 32, 1 ) : new THREE.CircleGeometry( h, 32 );
        if( orient ){
            var m = new THREE.Matrix4();
            m.identity().makeRotationX( Math.PI/2 ); g.applyMatrix(m);
            m.identity().makeRotationY( Utils.PI2/6/2 ); g.applyMatrix(m);
        }

        if(!material) var material = new THREE.MeshBasicMaterial( { color: 0xffffff } );
        
        material.side = THREE.BackSide;
        var mesh = new THREE.Mesh( g, material );
        mesh.matrixAutoUpdate = false;

        return mesh;
    }

    this.orientHexagon = function( mesh, t, look_at_corner ) {
        var up_coef = 10;
        mesh.position.copy( t.centerPoint );
        // mesh.scale.set( t.width, t.width, t.width );
        // mesh.scale.set( .001, .001, .001 );
        mesh.up.set( t.centerPoint.x*up_coef, t.centerPoint.y*up_coef, t.centerPoint.z*up_coef );
        if( look_at_corner ) mesh.lookAt( t.boundary[0] );
        // mesh.updateMatrix();
    }

    this.nearestPow2 = function( aSize ){
        return Math.pow( 2, Math.ceil( Math.log( aSize ) / Math.log( 2 ) ) ); 
    }

    this.setFromSpherical = function ( radius, u, v, vec3 ) {
        var spherical = new THREE.Spherical();
        spherical.radius = radius;
        spherical.theta = u * Math.PI *2 - Math.PI/2;
        spherical.phi = v * Math.PI;
        if( !vec3 ) vec3 = new THREE.Vector3();
        vec3.setFromSpherical( spherical );
        return vec3;
    }

}


Utils.getEventCursorPosition = function( e, mouse_obj ){
  var pos;
  var touches = e.originalEvent.touches;
  if(touches) pos = touches.length ? touches[0] : e.originalEvent.changedTouches[0];
    else pos = e;
  
  if( mouse_obj ){
    mouse_obj.x = pos.clientX;
    mouse_obj.y = pos.clientY;
    return;
  }

  return { x : pos.clientX, y : pos.clientY} ;
}

Utils.getEventCursorPositionOrientation = function( e, mouse_obj ){
  Util.getEventCursorPosition( e, mouse_obj );
  mouse_obj.x = ( mouse_obj.x / window.innerWidth ) * 2 - 1;
  mouse_obj.y = - ( mouse_obj.y / window.innerHeight ) * 2 + 1;
}

Utils.get2dPosition = function( position, camera, dom_element ){
    var v = position.clone().project( camera );
    v.x = (v.x + 1) / 2 * dom_element.innerWidth;
    v.y = -(v.y - 1) / 2 * dom_element.innerHeight;// - window.innerHeight * .08;
    return v;
}



Utils.drawFunction = function( start, end, foo, step, amplitude ){
    
    console.log( '====================================' );
    
    start = start==undefined ? -Math.PI : start;
    end = end==undefined ? Math.PI : end;
    step = step==undefined ? .1 : step;
    amplitude = amplitude==undefined ? 30 : amplitude;
    foo = foo==undefined ? function( v ){ return Math.cos(v) } : foo;

    var count = 0;

    for (var y = start ; y < end; y+= step ) {
        var str = '';
        for (var i = 0; i < amplitude*2; i++) {
            str += i==amplitude ? ':' : "-";
        };
        var p = foo( y );
        var x = Math.round( p * amplitude ) + amplitude;
        str = str.substr(0, x) + "*" + str.substr(x+1);
        console.log( count+" |"+ str, x );
        count++; if(count>=10) count = 0;
    }       
    console.log( '====================================' );
}












// FAKE EXTERNAL METHODS
/*
var kaspersky = kaspersky || {};

(function(){
    
    var $DOMElement = $("<div id='active_hexagon' style='\
        position:fixed;\
        top: 0;\
        left: 0;\
        width: 100px;\
        height: 100px;\
        background: red;\
        display: none;\
    '>").appendTo( $("html") );

    if( !kaspersky.getHexaspherePopup ) kaspersky.getHexaspherePopup = function( data, onClick ){

        console.log( "getHexaspherePopup> ", data );
        $DOMElement.show();

        $DOMElement.off().click( function(){
            onClick( data[0] );
        });
        
        return {
            "element": $DOMElement[0],
            "close": function(){
                $DOMElement.hide();
                console.log( "The active hexagon close!" );
            } //закрытие окна
        }

    }

})();
*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章