//------------------------------------------------------------------------------
// Lamp : Open source game middleware
// Copyright (C) 2004  Junpei Ohtani ( Email : junpee@users.sourceforge.jp )
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//------------------------------------------------------------------------------

/** @file
 * 運動会実装
 * @author Junpee
 */

#include "stdafx.h"
#include "SportsMeeting.h"
#include "Core/Utility/StringTokenizer.h"
#include "Core/InputOutput/FilePath.h"
#include "Graphics/Camera/Camera.h"
#include "Graphics/SceneNode/SceneNodeManager.h"
#include "Graphics/Enumeration/GraphicsDeviceEnumeration.h"
#include "Animation/System/AnimationManager.h"
#include "Animation/System/AnimationSet.h"

//------------------------------------------------------------------------------
// プログラムエントリポイント
int WINAPI WinMain(
	HINSTANCE instance, HINSTANCE previousInstance, LPSTR command, int show){
	SportsMeeting sceneViewer;
	return sceneViewer.execute(instance);
}
//------------------------------------------------------------------------------
// コンストラクタ
SportsMeeting::SportsMeeting() : SceneFramework("運動会"),
	tenkyuu_(NULL), loopTimer_(0.f), score_(0), lastScore_(0), timeScale_(100){
	// ウィンドウ作成パラメータ変更
	createWindowParameter_.createWidth_ = 1024;
	createWindowParameter_.createHeight_ = 768;
	GraphicsDeviceEnumeration* enumeration =
		GraphicsDeviceEnumeration::getInstance();
	enumeration->setMinimumDepthBits(24);
	enumeration->setMinimumBackBufferAlphaChannelBits(8);
}
//------------------------------------------------------------------------------
// 初期化
bool SportsMeeting::initialize(){
	// コマンドライン引数解析
	String command(GetCommandLine());
	StringTokenizer tokenizer(command);
	String sceneName("SportsMeeting.bsn");
	while(tokenizer.hasMoreTokens()){
		String token = tokenizer.getNextToken();
		if(token == "-scene"){
			// シーン名の読み込み
			if(!tokenizer.hasMoreTokens()){ return false; }
			sceneName = tokenizer.getNextToken();
//		}else if(token == "-information"){
			// インフォメーションレベル指定
//			if(!tokenizer.hasMoreTokens()){ return false; }
//			if(!tokenizer.getNextToken().parseInt(&drawInformationMode_)){
//				return false;
//			}
//			tokenizer.getNextToken();///////////////////
		}
	}
	if(!loadScene(sceneName)){ return false; }
	return true;
}
//------------------------------------------------------------------------------
// シーンのロード
bool SportsMeeting::loadScene(const String& sceneName){
	if(!SceneFramework::loadScene(sceneName)){ return false; }
	// ファークリップを2500にする
	camera_->setFarClip(2500.f);
	// 天球の取得
	tenkyuu_ = scene_->getSceneNodeManager()->search("koutei:Tenkyuu");
	// シーケンス設定
	sequenceSetup();
	// BGMを鳴らす
	FilePath bgmFilePath("SportsMeeting.wav");
	if(!bgmFilePath.existFile()){ return true; }
	PlaySound(NULL, NULL, 0);
	PlaySound(bgmFilePath.getPath().getBytes(),
		NULL, SND_ASYNC | SND_FILENAME | SND_LOOP);
	// デフォルト速度を85%にする
	timeScale_ = 85;
	loopTimer_ = 0.f;
	score_ = 0;
	return true;
}
//------------------------------------------------------------------------------
// シーケンスの設定
void SportsMeeting::sequenceSetup(){
	// シーケンス0を指定するキャラ数
	const int sequenceChangeCount = 32 + 1;
	// シーケンス1以降の数
	const int sequenceWidth = 3;
	// ランナーセット構築
	for(int i = 0; i < runnerSetCount_; i++){
		runnerSet_[i] = animationManager_->createAnimationSet("runnerSet" + i);
	}
	// ランナーパス構築
	runnerPath_ = animationManager_->createAnimationSet("runnerPath");
	Animation* rootAnimation = animationManager_->search("SportsMeeting");
	if(rootAnimation == NULL){ return; }
	AnimationSet* animationSet = rootAnimation->castAnimationSet();
	if(animationSet == NULL){ return; }
	int animationCount = animationSet->getAnimationCount();
	int countL, countM, countS, countSS;
	countL = countM = countS = countSS = 0;
	Random random(254);
	for(int i = 0; i < animationCount; i++){
		Animation* animation = animationSet->getAnimation(i);
		const String& name = animation->getName();
		if(name.startsWith("makoto:MakotoLShape")){
			random.setSeed(countL);
			// シーケンスの変更
			if(countL < sequenceChangeCount){
				runnerSetup(animation, countL);
			}else{
				animation->setSequence((random.get() % sequenceWidth) + 1);
			}
			// タイマのランダム化
			animation->setTime(
				animation->getLength() * random.getUnsignedFloat());
			countL++;
		}else if(name.startsWith("makoto:MakotoMShape")){
			random.setSeed(countM);
			// シーケンスの変更
			if(countM < sequenceChangeCount){
				runnerSetup(animation, countM);
			}else{
				animation->setSequence((random.get() % sequenceWidth) + 1);
			}
			// タイマのランダム化
			animation->setTime(
				animation->getLength() * random.getUnsignedFloat());
			countM++;
		}else if(name.startsWith("makoto:MakotoSShape")){
			random.setSeed(countS);
			// シーケンスの変更
			if(countS < sequenceChangeCount){
				runnerSetup(animation, countS);
			}else{
				animation->setSequence((random.get() % sequenceWidth) + 1);
			}
			// タイマのランダム化
			animation->setTime(
				animation->getLength() * random.getUnsignedFloat());
			countS++;
		}else if(name.startsWith("makoto:MakotoSSShape")){
			random.setSeed(countSS);
			// シーケンスの変更
			if(countSS < sequenceChangeCount){
				runnerSetup(animation, countSS);
			}else{
				animation->setSequence((random.get() % sequenceWidth) + 1);
			}
			// タイマのランダム化
			animation->setTime(
				animation->getLength() * random.getUnsignedFloat());
			countSS++;
		}else if(name.startsWith("Makoto")){
			// タイマのランダム化
			animation->setTime(
				animation->getLength() * random.getUnsignedFloat());
			runnerPath_->addAnimation(animation);
		}
	}
	// ルートからはがす
	for(int i = 0; i < runnerSetCount_; i++){
		int setCount = runnerSet_[i]->getAnimationCount();
		for(int j = 0; j < setCount; j++){
			animationSet->removeAnimation(runnerSet_[i]->getAnimation(j));
		}
	}
	int pathCount = runnerPath_->getAnimationCount();
	for(int i = 0; i < pathCount; i++){
		animationSet->removeAnimation(runnerPath_->getAnimation(i));
	}
}
//------------------------------------------------------------------------------
// ランナーセットアップ
void SportsMeeting::runnerSetup(Animation* animation, int count){
	animation->setSequence(0);
	if(count == 0){ return; }
	count--;
	if(count < 6){
		runnerSet_[0]->addAnimation(animation);
	}else if(count < 12){
		runnerSet_[1]->addAnimation(animation);
	}else if(count < 17){
		runnerSet_[2]->addAnimation(animation);
	}else if(count < 22){
		runnerSet_[3]->addAnimation(animation);
	}else if(count < 27){
		runnerSet_[4]->addAnimation(animation);
	}else{
		runnerSet_[5]->addAnimation(animation);
	}
}
//------------------------------------------------------------------------------
// 実行
void SportsMeeting::run(){
	loopTimer_ += timeScale_ * 0.01f;
	// ループ処理
	if(loopTimer_ > 1307.f){
		loopTimer_ = 0.f;
		lastScore_ = score_;
		score_ = 0;
	}
}
//------------------------------------------------------------------------------
// レンダリング準備
void SportsMeeting::renderSetup(){
	if(tenkyuu_ != NULL){ tenkyuu_->setTranslation(camera_->getPosition()); }
	Animation* rootAnimation = animationManager_->search("SportsMeeting");
	if(rootAnimation == NULL){ return; }
	float animationTime = (float)timeScale_ * 0.01f * (float)runCount_;
	// ランナーパスアニメーション
	runnerPath_->animate(animationTime, Animation::maskPreCulling);
	// スコア加算
	score_++;
	// TimeScaleがSceneFrameworkから消えたので一周ごとにずれていく
//	float animationTime = timeScale_ * 0.01f * runCount_;
	runnerSet_[0]->animate(animationTime * 2.25f, Animation::maskPostCulling);
	runnerSet_[1]->animate(animationTime * 2.25f, Animation::maskPostCulling);
	runnerSet_[2]->animate(animationTime * 2.125f, Animation::maskPostCulling);
	runnerSet_[3]->animate(animationTime * 2.f, Animation::maskPostCulling);
	runnerSet_[4]->animate(animationTime * 1.75f, Animation::maskPostCulling);
	runnerSet_[5]->animate(animationTime * 1.75f, Animation::maskPostCulling);
}
//------------------------------------------------------------------------------
// 情報描画
void SportsMeeting::drawInformation(){
	SceneFramework::drawInformation();
	String scoreString;
	scoreString.format("Score %d LastScore %d", score_, lastScore_);
	drawInformationString(scoreString, Color4c(0, 0, 0), true, false);
}
//------------------------------------------------------------------------------
