Code viewer for World: Cloned Smooth FPV Model World

// Cloned by Mathias Bazin on 14 Jun 2018 from World "Smooth FPV Model World" by Starter user 
// Please leave this clone trail here.
 



// ==== Starter World ===============================================================================================
// (c) Ancient Brain Ltd. All rights reserved.
// This code is only for use on the Ancient Brain site.
// This code may be freely copied and edited by anyone on the Ancient Brain site.
// This code may not be copied, re-published or used on any other website.
// To include a run of this code on another website, see the "Embed code" links provided on the Ancient Brain site.
// ==================================================================================================================



// "First Person View" 3d model
// Camera rotates with direction you are facing
// Best effect is with "Move with" camera

// No Mind
// Human controlled UP/LEFT/RIGHT arrows move model 

// Smooth movement
// UP moves forward in whatever angle you are at
// LEFT/RIGHT rotate by small angle

// abandons square grid blocks of other Worlds
// uses raw x,z positions



// Things to do:
// Collision detection 



  
// skeleton credit
// formerly here:
// http://tf3dm.com/3d-model/skeleton-with-organs-91102.html

// Peter Parker credit
// https://free3d.com/3d-model/spider-man-4998.html









// ===================================================================================================================
// === Start of tweaker's box ======================================================================================== 
// ===================================================================================================================

// The easiest things to modify are in this box.
// You should be able to change things in this box without being a JavaScript programmer.
// Go ahead and change some of these. What's the worst that could happen?



// These 3 have default values, so this section is optional:

AB.clockTick       = 100;    

	// Speed of run: Step every n milliseconds. Default 100.
	
AB.maxSteps        = 10000;    

	// Length of run: Maximum length of run in steps. Default 1000.

AB.screenshotStep  = 50;   
  
	// Take screenshot on this step. (All resources should have finished loading.) Default 50.



//---- global constants: -------------------------------------------------------

 const TEXTURE_WALL 	= '/uploads/starter/door.jpg' ;
 const TEXTURE_MAZE 	= '/uploads/starter/latin.jpg' ;
 const TEXTURE_SKELETON = '/uploads/starter/ghost.3.png' ;
 
// credits:
// http://commons.wikimedia.org/wiki/File:Old_door_handles.jpg
// https://commons.wikimedia.org/wiki/Category:Pac-Man_icons
// https://commons.wikimedia.org/wiki/Category:Skull_and_crossbone_icons

 const OBJ_SKELETON 	= '/uploads/starter/skelet.obj' ;
 const MUSIC_BACK  		= '/uploads/starter/SuspenseStrings.mp3' ;
 const SOUND_ALARM 		= '/uploads/starter/buzzer-soundbible.com-188422102.mp3' ;

 		// music credit
		// http://www.dl-sounds.com/royalty-free/suspense-strings/

		// /uploads/starter/slow_heartbeat-mike_koenig-1853475164.mp3


const gridsize = 35;					// number of squares along side of world	   
const squaresize = 100;					// size of square in pixels
const MAXPOS = gridsize * squaresize;		// length of one side in pixels 
	
const NOBOXES =  Math.trunc ( (gridsize * gridsize) / 40 );


const SKYCOLOR 	= 0xffffcc;				// a number, not a string 
const BLANKCOLOR 	= SKYCOLOR ;			// make objects this color until texture arrives (from asynchronous file read)

const  LIGHTCOLOR 	= 0xffffff ;


const startRadiusConst	 	= MAXPOS * 0.8 ;		// distance from centre to start the camera at
const skyboxConst			= MAXPOS * 3 ;		// where to put skybox 
const maxRadiusConst 			= MAXPOS * 5 ;		// maximum distance from camera we will render things  



//--- change threeworld defaults: -------------------------------

threehandler.MAXCAMERAPOS 	= skyboxConst / 2 ;			// keep camera inside skybox 

threehandler.GROUNDZERO		= true;						// "ground" exists at altitude zero

 
 
// --- Rotations -----------------------
 
// rotate by some amount of radians from the normal position 
// default is 0 which has the model facing DOWN (towards increasing z value) as far as the initial camera sees

const ROTATE_AMOUNT      =  Math.PI / 20 ;      // rotate amount in radians (PI = 180 degrees)


//--- skybox: -------------------------------

// urban photographic skyboxes, credit:
// http://opengameart.org/content/urban-skyboxes

  const SKYBOX_ARRAY = [										 
                "/uploads/starter/posx.jpg",
                "/uploads/starter/negx.jpg",
                "/uploads/starter/posy.jpg",
                "/uploads/starter/negy.jpg",
                "/uploads/starter/posz.jpg",
                "/uploads/starter/negz.jpg"
                ];
				
				
// ===================================================================================================================
// === End of tweaker's box ==========================================================================================
// ===================================================================================================================


// You will need to be some sort of JavaScript programmer to change things below the tweaker's box.











// contents of a grid square

const GRID_BLANK 	= 0;
const GRID_WALL 	= 1;
const GRID_MAZE 	= 2;
 

 
// --- some useful random functions  -------------------------------------------


function randomfloatAtoB ( A, B )			 
{
 return ( A + ( Math.random() * (B-A) ) );
}

function randomintAtoB ( A, B )			 
{
 return  ( Math.round ( randomfloatAtoB ( A, B ) ) );
}
  
function randomBoolean()			 
{
 if ( Math.random() < 0.5 ) { return false; }
 else { return true; }
}


function randomPick ( a, b )
{
 if ( randomBoolean() ) 
  return a;
 else
  return b;
}






//---- start of World class -------------------------------------------------------
 
function World() { 


// most of World can be private 
// regular "var" syntax means private variables:


var GRID 	= new Array(gridsize);			// can query GRID about whether squares are occupied, will in fact be initialised as a 2D array   
var WALLS 	= new Array ( 4 * gridsize );		// need to keep handle to each wall block object so can find it later to paint it 
var MAZE 	= new Array ( NOBOXES );

var theagent, theenemy;		  

var agentRotation = 0 ; 
var enemyRotation = 0 ;    


// enemy and agent position as a square 
var ei, ej, ai, aj;

var badsteps;
var goodsteps;
var  step;

  	var self = this;						// needed for private fn to call public fn - see below  





function initGrid()
{
 for (var i = 0; i < gridsize ; i++) 
 {
  GRID[i] = new Array(gridsize);		// each element is an array 

  for (var j = 0; j < gridsize ; j++) 
  {
   GRID[i][j] = GRID_BLANK ;
  }
 }
}


function occupied ( i, j )		// is this square occupied
{
 if ( ( ei == i ) && ( ej == j ) ) return true;		// variable objects 
 if ( ( ai == i ) && ( aj == j ) ) return true;

 if ( GRID[i][j] == GRID_WALL ) return true;		// fixed objects	 
 if ( GRID[i][j] == GRID_MAZE ) return true;		 
	 
 return false;
}


 
function translate ( x ) 
{
 return ( x - ( MAXPOS/2 ) );
}





// --- asynch load textures from file ----------------------------------------
  

function loadTextures()
{
	var manager = new THREE.LoadingManager();		
	var loader = new THREE.OBJLoader( manager );
			
 loader.load( OBJ_SKELETON, buildenemy );



// load simple OBJ
//	 loader.load( "/uploads/starter/male02.obj", buildagent );


// load OBJ plus MTL (plus TGA files) 
	THREE.Loader.Handlers.add( /.tga$/i, new THREE.TGALoader() );
	var m = new THREE.MTLLoader();
	m.setTexturePath ( "/uploads/starter/" );
	m.setPath        ( "/uploads/starter/" );
	m.load( "Peter_Parker.mtl", function( materials ) {
 
		materials.preload();
		var o = new THREE.OBJLoader();
		o.setMaterials ( materials );
		o.setPath ( "/uploads/starter/" );
		o.load( "Peter_Parker.obj", function ( object ) {
			addparker ( object );
		} );
	} );


 var loader1 = new THREE.TextureLoader();
 loader1.load ( TEXTURE_WALL,		function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		paintWalls ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
	} ); 

 var loader2 = new THREE.TextureLoader();
 loader2.load ( TEXTURE_MAZE,		function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		paintMaze ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
 	} ); 

}

 
 
function buildenemy ( object ) 
{ 
	object.scale.multiplyScalar ( 4 );    	  // make 3d object n times bigger 
	object.traverse( paintEnemy );
	theenemy = object;
	threeworld.scene.add( theenemy ); 
	initDrawEnemy();
}

function paintEnemy ( child ) 
{
	if ( child instanceof THREE.Mesh ) 
	{
      	child.material.map = THREE.ImageUtils.loadTexture( TEXTURE_SKELETON );
	}
}



function addparker ( object )
{
	object.scale.multiplyScalar ( 70 );    	   
	theagent = object;
	threeworld.scene.add( theagent ); 
	initDrawAgent();
}





function initSkybox() 
{
  var materialArray = [
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( SKYBOX_ARRAY[0] ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( SKYBOX_ARRAY[1] ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( SKYBOX_ARRAY[2] ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( SKYBOX_ARRAY[3] ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( SKYBOX_ARRAY[4] ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( SKYBOX_ARRAY[5] ), side: THREE.BackSide } ) )
 	];

  var skyGeometry = new THREE.CubeGeometry ( skyboxConst, skyboxConst, skyboxConst );	
  var skyMaterial = new THREE.MeshFaceMaterial ( materialArray );
  var theskybox = new THREE.Mesh ( skyGeometry, skyMaterial );
  threeworld.scene.add( theskybox );						// We are inside a giant cube
}




   
 
function initLogicalWalls()		// set up logical walls in data structure 	
{
 for (var i = 0; i < gridsize ; i++) 
  for (var j = 0; j < gridsize ; j++) 
   if ( ( i==0 ) || ( i==gridsize-1 ) || ( j==0 ) || ( j==gridsize-1 ) )
   {
    	GRID[i][j] = GRID_WALL ;		 
   }
}


function initThreeWalls()		// set up blank boxes, painted later 	
{
 var t = 0;
 for (var i = 0; i < gridsize ; i++) 
  for (var j = 0; j < gridsize ; j++) 
   if ( GRID[i][j] == GRID_WALL )
   {
 	 var shape    = new THREE.BoxGeometry( squaresize, squaresize, squaresize );			 
 	 var thecube  = new THREE.Mesh( shape );
	 thecube.material.color.setHex( BLANKCOLOR  );			  
 
    	 thecube.position.x = translate ( i * squaresize );   		// translate my simple (i,j) block-numbering coordinates to three.js (x,y,z) coordinates 
    	 thecube.position.z = translate ( j * squaresize );   	
    	 thecube.position.y =  0;	
 
 	 threeworld.scene.add(thecube);
	 WALLS[t] = thecube;		// save it for later
	 t++; 
   }
}


function paintWalls ( material )		// paint blank boxes  
{
 for ( var i = 0; i < WALLS.length; i++ )
 { 
   if ( WALLS[i] )  WALLS[i].material = material;
 }
}





function initLogicalMaze()		 
{
 for ( var c=1 ; c <= NOBOXES ; c++ )
 {
  	var i = randomintAtoB(2,gridsize-3);	// inner squares are 1 to gridsize-2
  	var j = randomintAtoB(2,gridsize-3);
    	GRID[i][j] = GRID_MAZE ;		 
 }
}


function initThreeMaze()		  	
{
 var t = 0;
 for (var i = 0; i < gridsize ; i++) 
  for (var j = 0; j < gridsize ; j++) 
   if ( GRID[i][j] == GRID_MAZE )
   {
   	var shape    = new THREE.BoxGeometry( squaresize, squaresize, squaresize );			 
  	var thecube  = new THREE.Mesh( shape );
	thecube.material.color.setHex( BLANKCOLOR  );			  

  	thecube.position.x = translate ( i * squaresize );   	
  	thecube.position.z = translate ( j * squaresize );   	
  	thecube.position.y =  0;	
 
 	threeworld.scene.add(thecube);
	MAZE[t] = thecube;		// save it for later
	t++; 
   }
}


function paintMaze ( material )		 
{
 for ( var i = 0; i < MAZE.length; i++ )
 { 
   if ( MAZE[i] )  MAZE[i].material = material;
 }
}




// --- enemy functions -----------------------------------


function initLogicalEnemy()
{
// start in random location:
 var i, j;
 do
 {
  i = randomintAtoB(1,gridsize-2);
  j = randomintAtoB(1,gridsize-2);
 }
 while ( occupied(i,j) );  	  // search for empty square 

 ei = i;
 ej = j;
}

 
function initDrawEnemy()		
// given initial ei, ej, draw it 
// thereafter move by x,y,z positions not square blocks
{
  var x = translate ( ei * squaresize );   	
  var z = translate ( ej * squaresize );   	
  var y =   ( -1 * squaresize );   	

 theenemy.position.x = x;
 theenemy.position.y = y;
 theenemy.position.z = z;
}

 
 
// angle between two points (x1,y1) and (x2,y2)

function angleTwoPoints ( x1, y1, x2, y2 ) 
{
      return  Math.atan2 ( x2 - x1,  y2 - y1  );
}


function dist ( a, b  )		    // distance between them when a,b are Three vectors  
{
 return ( a.distanceTo ( b ) );
}


function moveEnemy()
{ 
 if ( theagent )
  if ( theenemy ) 
  {
    // rotate enemy to face agent
        enemyRotation =  angleTwoPoints ( theenemy.position.x, theenemy.position.z, theagent.position.x, theagent.position.z  );
        theenemy.rotation.set ( 0, enemyRotation, 0 );
  
  
    if  ( dist ( theenemy.position, theagent.position ) > squaresize )
    {
      // move along that line 
      theenemy.position.x = theenemy.position.x + ( squaresize *  Math.sin(enemyRotation) );
      theenemy.position.z = theenemy.position.z + ( squaresize *  Math.cos(enemyRotation) );
    }
    
  }
}






// --- agent functions -----------------------------------


// the key handler moves and rotates the agent
// this function updates camera on agent (follow and lookat)

function updateAgentCamera()	 
{
 // ignore enemy - look in direction we are facing
 
 // camera position
 //  move camera a little bit along line we are facing, to get it away from agent's hair
 threeworld.follow.copy ( theagent.position );		 
 threeworld.follow.x = threeworld.follow.x - ( ( squaresize * 3 ) *  Math.sin(agentRotation) );
 threeworld.follow.z = threeworld.follow.z - ( ( squaresize * 3 ) *  Math.cos(agentRotation) );

 threeworld.follow.y = ( squaresize * 2 );        // put camera higher up
 

 // camera lookat
 // look at point in distance along line we are facing
 
 threeworld.lookat.copy ( theagent.position );
 threeworld.lookat.x = threeworld.lookat.x + ( skyboxConst *  Math.sin(agentRotation) );
 threeworld.lookat.z = threeworld.lookat.z + ( skyboxConst *  Math.cos(agentRotation) );
 /*
 var enemyToAgent = new THREE.Vector3();

    enemyToAgent.subVectors(theagent.position, theenemy.position); 
    enemyToAgent.normalize();     //this vector contains the direction from fireball to the queen
    enemyToAgent.multiplyScalar(1000);
    camPos.addVectors(theagent.position, enemyToAgent);
    camPos.add(new THREE.Vector3(0,600,0));
    threeworld.follow = camPos;
    threeworld.lookat = theenemy.position;
*/
}



function initLogicalAgent()
{
// start in random location:
 var i, j;
 do
 {
  i = randomintAtoB(1,gridsize-2);
  j = randomintAtoB(1,gridsize-2);
 }
 while ( occupied(i,j) );  	  // search for empty square 

 ai = i;
 aj = j;
}


function initDrawAgent()
// get initial ai, aj
// thereafter move by x,y,z positions not square blocks
{
  var x = translate ( ai * squaresize );   	
  var z = translate ( aj * squaresize );   	
  var y =   ( -1 * squaresize );   	

 theagent.position.x = x;
 theagent.position.y = y;
 theagent.position.z = z;
}







//--- key control of agent -------------------------------------------------------------

const KEY_UP    = 38;
const KEY_LEFT  = 37;
const KEY_RIGHT = 39;


// UP moves forward in whatever angle you are at
// LEFT/RIGHT rotate by small angle



function keyHandler(e)		
// user control 
// Note that this.takeAction(a) is constantly running at same time, redrawing the screen.
{
 //   if ( ( 37 <= e.keyCode ) && ( e.keyCode <= 40 ) )
 //    console.log ( "agentRotation = " + agentRotation + " keyCode = " + e.keyCode );
    
if ( theagent )
{
    
 if ( e.keyCode == KEY_UP ) 		  	// move a bit along angle we are facing
 {
	theagent.position.x = theagent.position.x + ( squaresize *  Math.sin(agentRotation) );
	theagent.position.z = theagent.position.z + ( squaresize *  Math.cos(agentRotation) );
	e.preventDefault(); 
 }
 
 else if ( e.keyCode == KEY_LEFT )   	// rotate in place 
 {
    agentRotation = agentRotation + ROTATE_AMOUNT;
	theagent.rotation.set ( 0, agentRotation, 0 );
	e.preventDefault(); 
 }
 
 else if ( e.keyCode == KEY_RIGHT ) 
 {
    agentRotation = agentRotation - ROTATE_AMOUNT;
    theagent.rotation.set ( 0, agentRotation, 0 );
	e.preventDefault(); 
 }
 
}
}





// --- score: -----------------------------------


function badstep()			// is the enemy within one square of the agent
{
 if ( ( Math.abs(ei - ai) < 2 ) && ( Math.abs(ej - aj) < 2 ) ) return true;
 else return false;
}

 
function   updateStatus()		 
{
 var score = goodsteps;
 var status =  "   Step: " + step + " out of " + AB.maxSteps + ". Score: " + score; 

 $("#user_span1").html( status );
}







//--- public functions / interface / API ----------------------------------------------------------


	this.endCondition = false;



this.newRun = function() 
{
  badsteps = 0;		
  goodsteps = 0;
  step = 0;


  // define logical data structure for the World:

 	initGrid();
	initLogicalWalls(); 
	initLogicalMaze();

	initLogicalAgent();
	initLogicalEnemy();


	threeworld.init3d ( startRadiusConst, maxRadiusConst, SKYCOLOR  ); 


		// light
    	var ambient = new THREE.AmbientLight();
    	threeworld.scene.add( ambient );

		
	   	var thelight = new THREE.DirectionalLight ( LIGHTCOLOR, 3 );
	  	thelight.position.set ( startRadiusConst, startRadiusConst, startRadiusConst );
	   	threeworld.scene.add(thelight);
		

		initMusic();
        initSkybox();
	 //	initThreeWalls();
	    initThreeMaze();
	  	
	 
	  loadTextures();			// will return sometime later, but can go ahead and render now	
	
	  document.onkeydown = keyHandler;
};





// key handler moves and rotates agent
// this function is called every step
// can fix agent camera and move enemy


this.nextStep = function()
{
  step++;

  if ( badstep() )
   badsteps++;
  else
   goodsteps++;

   updateAgentCamera();
   moveEnemy();
   
	/*
		if  ( dist ( theenemy.position, theagent.position ) < (squaresize * 3) )
		{
			musicPause();
			soundAlarm();
		}
		else 
			musicPlay();
	*/
  
   updateStatus();
};



this.endRun = function()
{
};




}

//---- end of World class -------------------------------------------------------







// --- music and sound effects ----------------------------------------


var backmusic = new Audio ( MUSIC_BACK );
 

function initMusic()	
{
	backmusic.loop = true;                 // loop forever 
	backmusic.play();

	$("#w2m_audio1").html( " <img class=audiobutton  onclick='musicPlay();'  width=25  src='images/audio.on.1.png'  > " );	
	$("#w2m_audio2").html( " <img class=audiobutton  onclick='musicPause();' width=25  src='images/audio.off.1.png' > " );	
} 
 
	
function musicPlay()   { backmusic.play();  }
function musicPause()  { backmusic.pause(); }

											 
function soundAlarm()
{
	var alarm = new Audio ( SOUND_ALARM );
	alarm.play();							// play once, no loop 
}