SlideShare a Scribd company logo
1 of 22
SMC – State Machine Compiler jeddli@gmail.com 아꿈사. 이동현
FSM? 상태기계를 이용하면 프로그램이 간단하고 이해하기 쉽다. C++ Code 수 많은 반복 코드와 노가다… 통제가 안될 정도로 커진다.
좀 더 견고한 방법. – 상태 기계 언어 고전적인 의미의 상태 기계와 현실적인 의미의 상태 기계. 대부분의 게임 개발자는 느슨한 정의를 이용. 상태안의 상태. 다중 상태 변수. 상태 전이의 임의성. 상태 안에서 모든 게임 tick를 실행하는 코드. 기타 생각할 수 있는 모든 것.
코딩된 상태 기계 합법적인 코드 그러나… void RunLogic( int* state ) {     switch( *state )     {         case 0: //돌아다님             Wander();             if( SeeEnemy() )             {                 if( GetRandomChance() < 0.8 ) *state = 1;                 else *state = 2;             }             if( Dead() ) *state = 3;             break;         case 1: //공격             Attack();             if( Dead() ) *state = 3;             break;         case 2: //도망 RunAway();             if( Dead() ) *state = 3;             break;         case 3: //죽음 SlowlyRot();             break;     } } ,[object Object]
상태들이 int형태이며, 열거형이라면 더 견고하고 디버그 하기 쉬울 것이다.
Break 키워드 하나만 지워도 찾기 어려운 버그들을 만들게 된다.
중복적인 논리가 다중 상태에 나타난다.
어떤 상태에 처음 들어갔는지를 알려줄 수 있는 방법이 없다.
상태 기계가 시간에 따라 어떻게 움직여 왔는지를 모티너하거나 기록으로 남길(log) 방법이 없다.,[object Object]
상태 기계 언어 기본 예제 BeginStateMachine     State( STATE_Wander ) OnEnter // 상태시작점에대한C나C++ 코드 OnUpdate // 매틱(tick)마다실행되는C나C++ 코드 OnExit // 상태의뒷정리를위한C나C++ 코드     State( STATE_Attack ) OnEnter // 상태시작점에대한C나C++ 코드 EndStateMachine #define BeginStateMachine	if(state < 0) { if (0) { #define EndStateMachinereturn (true); }} else { assert(0);br />return (false); } return (false); #define State(a)	return (true);}}else if(a == state){if(0){ #define OnEvent(a)	return (true);}else if(a == event){ #define OnEnterOnEvent(EVENT_Enter) #define OnUpdateOnEvent(EVENT_Update) #define OnExitOnEvent(EVENT_Exit)
실제로 확장 해보면.. if( state < 0 ){ 	if( 0 ) { 		return ( true ); } }else if( STATE_Wander == state ) { 	if( 0 ){ 		return ( true );	 	}else if( EVENT_Enter== state ) { // 상태시작점에대한C++ 코드 		return ( true );	 	}else if(EVENT_Update== state ) { // 매틱(tick)마다실행되는C++ 코드 		return ( true ); 	}else if(EVENT_Wander== state ) { // 상태의뒷정리를위한C++ 코드 		return ( true );	 } }else if( STATE_Attack == state ) { 	if( 0 ){ 		return ( true );	 	}else if( EVENT_Enter == state ) { // 상태시작점에대한C++ 코드 		return ( true );		 } }else { 	assert(0); 	return( false ); } return false; BeginStateMachine     State( STATE_Wander ) OnEnter // 상태시작점에대한C나C++ 코드 OnUpdate // 매틱(tick)마다실행되는C나C++ 코드 OnExit // 상태의뒷정리를위한C나C++ 코드     State( STATE_Attack ) OnEnter // 상태시작점에대한C나C++ 코드 EndStateMachine
좀 더 나아가서.. AI 디자이너의 생산성 높이기. GUI 기반의 모델링. C++ 코더로의 변환 용이성.
CreatureMachine::CreatureMachine() { 	// add all variables to the variable list AddVariable("Health",VAR_INTEGER,&m_Health); AddVariable("EnemyLocation",VAR_POSITION,&m_Enemy; 	// now add conditions (may reference variables) AddCondition("InRange",LESSTHAN,"EnemyLocation",100); AddCondition("LowHealth",LESSTHAN,"Health", 50); 	// now add all the actions (may be referenced by the // states)	 AddAction("IdleAction"); AddAction("FightAction"); AddAction("FleeAction"); 	// now add all the states AddState("Idle","IdleAction"); AddState("Fight","FightAction"); AddState("Flee","FleeAction"); 	// now add all the transitions (may reference states  	// and variables) 	// transitions syntax : <condition-name> <start state> 	// <end state> AddTransition("In Range","Idle","Fight"); AddTransition("Low Health","Fight","Flee"); }; 다이어 그램의 코드화
SMC – The State Map Compiler http://smc.sourceforge.net/SmcManual.htm “Your detailed state diagrams are only pictures.  How are you going to translate your drawings into code?  A transition matrix is cryptic while switch statements means  your state machine logic is scattered all over your code.  The state pattern looks like a great solution but that means writing  and maintaining a class for each state - too much work.”
SMC
Adding a state machine to your class Download SMC - http://sourceforge.net/projects/smc/files/smc/6_0_0/smc_6_0_0.zip/download Include the SMC class definitions into your application. Include the state machine's source file. Instantiate the state machine's context object. If you want to execute the start state's entry actions call the state machine context's enterStartState method. This is not needed to set the start state as that is done when the state machine context is instantiated. enterStartState only executes the start state's entry actions (if any exist).
Make SMC file // This FSM works for the Task class only and only the Task  // class may instantiate it. %class Task  %package com.acme.supercron %fsmclassTaskFSM %access package  %start TaskFSM::Suspended  %map TaskFSM %%  <snip>  Running    Exit     {   stopSliceTimer();     } {      Suspend    Suspended { suspendTask(); }     Block         Blocked { blockTask(); }   Done         Stopped { releaseResources(); }  }  <snip>  }  %% End State Transition Action {      Suspend    Suspended { suspendTask(); }      Block         Blocked { blockTask(); }   Done         Stopped { releaseResources(); }  }
Transition Guards // State  Idle  {     // Trans     Run     // Guard condition     [ctxt.isProcessorAvailable() == true &&  ctxt.getConnection().isOpen() == true]     // Next State     Running     // Actions     {  StopTimer("Idle");  DoWork();     }     Run nil {RejectRequest();}  }
Transition Arguments // State  Idle  {     // Transition     Run(msg: const Message&)     // Guard condition     [ctxt.isProcessorAvailable() == true &&  msg.isValid() == true]     // Next State     Running     // Actions     {  StopTimer("Idle");  DoWork(msg);     }     Run(msg: const Message&)     // Next State    Actions     nil                     {RejectRequest(msg);} }
Transition Arguments CLOSED { PassiveOpen(port: unsigned short) ServiceOpening { openServerSocket(port); } void MainMap_CLOSED::PassiveOpen(TcpConnectionContext& context, unsigned short port) { TcpConnection& ctxt(context.getOwner());
Default Transitions What happens if a state receives a transition that is not defined in that state? Default {     // Valid run request but transition occurred in an invalid     // state. Send a reject reply to valid messages.     Run(msg: const Message&)       [ctxt.isProcessorAvailable() == true && msg.isValid() == true]         nil         { RejectRequest(msg);         }     // Ignore invalid messages are ignored when received in     // an invalid state.     Run(msg: const Message&)         nil         {}     Shutdown ShuttingDown         { StartShutdown();         } } Connecting {     // We are now connected to the far-end. Now we can logon.     Connected         Connected         {             logon();         }     // Any other transition at this point is an error.     // Stop the connecting process and retry later.     Default RetryConnection         { stopConnecting();         } }

More Related Content

What's hot

Malzilla tutorial1
Malzilla tutorial1Malzilla tutorial1
Malzilla tutorial1re4lfl0w
 
3.4병행성 시간은 중요하다.
3.4병행성   시간은 중요하다.3.4병행성   시간은 중요하다.
3.4병행성 시간은 중요하다.aceigy6322
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)문익 장
 
11장 윈도우 스레드 풀
11장 윈도우 스레드 풀11장 윈도우 스레드 풀
11장 윈도우 스레드 풀홍준 김
 
GCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with Exception
GCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with ExceptionGCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with Exception
GCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with Exception상현 조
 
Half sync/Half Async
Half sync/Half AsyncHalf sync/Half Async
Half sync/Half Asyncscor7910
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class웅식 전
 
[OpenTRS-001] Hotel California
[OpenTRS-001] Hotel California[OpenTRS-001] Hotel California
[OpenTRS-001] Hotel CaliforniaTheori
 
windows via c++ Ch 5. Job
windows via c++ Ch 5. Jobwindows via c++ Ch 5. Job
windows via c++ Ch 5. JobHyosung Jeon
 
GCGC- CGCII 서버 엔진에 적용된 기술 (1)
GCGC- CGCII 서버 엔진에 적용된 기술 (1)GCGC- CGCII 서버 엔진에 적용된 기술 (1)
GCGC- CGCII 서버 엔진에 적용된 기술 (1)상현 조
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기jongho jeong
 
GCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server Sample
GCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server SampleGCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server Sample
GCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server Sample상현 조
 
동기화, 스케줄링
동기화, 스케줄링동기화, 스케줄링
동기화, 스케줄링xxbdxx
 
07 스레드스케줄링,우선순위,그리고선호도
07 스레드스케줄링,우선순위,그리고선호도07 스레드스케줄링,우선순위,그리고선호도
07 스레드스케줄링,우선순위,그리고선호도ssuser3fb17c
 
[Swift] Protocol (1/2)
[Swift] Protocol (1/2)[Swift] Protocol (1/2)
[Swift] Protocol (1/2)Bill Kim
 
GCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group System
GCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group SystemGCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group System
GCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group System상현 조
 
GDG 2014 - RxJava를 활용한 Functional Reactive Programming
GDG 2014 - RxJava를 활용한 Functional Reactive Programming GDG 2014 - RxJava를 활용한 Functional Reactive Programming
GDG 2014 - RxJava를 활용한 Functional Reactive Programming waynejo
 
GCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing System
GCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing SystemGCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing System
GCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing System상현 조
 

What's hot (20)

Malzilla tutorial1
Malzilla tutorial1Malzilla tutorial1
Malzilla tutorial1
 
3.4병행성 시간은 중요하다.
3.4병행성   시간은 중요하다.3.4병행성   시간은 중요하다.
3.4병행성 시간은 중요하다.
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)
 
11장 윈도우 스레드 풀
11장 윈도우 스레드 풀11장 윈도우 스레드 풀
11장 윈도우 스레드 풀
 
Thread programming
Thread programmingThread programming
Thread programming
 
GCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with Exception
GCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with ExceptionGCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with Exception
GCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with Exception
 
Half sync/Half Async
Half sync/Half AsyncHalf sync/Half Async
Half sync/Half Async
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class
 
[OpenTRS-001] Hotel California
[OpenTRS-001] Hotel California[OpenTRS-001] Hotel California
[OpenTRS-001] Hotel California
 
windows via c++ Ch 5. Job
windows via c++ Ch 5. Jobwindows via c++ Ch 5. Job
windows via c++ Ch 5. Job
 
GCGC- CGCII 서버 엔진에 적용된 기술 (1)
GCGC- CGCII 서버 엔진에 적용된 기술 (1)GCGC- CGCII 서버 엔진에 적용된 기술 (1)
GCGC- CGCII 서버 엔진에 적용된 기술 (1)
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기
 
GCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server Sample
GCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server SampleGCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server Sample
GCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server Sample
 
동기화, 스케줄링
동기화, 스케줄링동기화, 스케줄링
동기화, 스케줄링
 
07 스레드스케줄링,우선순위,그리고선호도
07 스레드스케줄링,우선순위,그리고선호도07 스레드스케줄링,우선순위,그리고선호도
07 스레드스케줄링,우선순위,그리고선호도
 
[Swift] Protocol (1/2)
[Swift] Protocol (1/2)[Swift] Protocol (1/2)
[Swift] Protocol (1/2)
 
GCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group System
GCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group SystemGCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group System
GCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group System
 
교착 상태
교착 상태교착 상태
교착 상태
 
GDG 2014 - RxJava를 활용한 Functional Reactive Programming
GDG 2014 - RxJava를 활용한 Functional Reactive Programming GDG 2014 - RxJava를 활용한 Functional Reactive Programming
GDG 2014 - RxJava를 활용한 Functional Reactive Programming
 
GCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing System
GCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing SystemGCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing System
GCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing System
 

Similar to Smc–state machinecompiler

[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?NAVER D2
 
Surface flingerservice(서피스 상태 변경 jb)
Surface flingerservice(서피스 상태 변경 jb)Surface flingerservice(서피스 상태 변경 jb)
Surface flingerservice(서피스 상태 변경 jb)fefe7270
 
Surface flingerservice(서피스 상태 변경 및 출력 요청)
Surface flingerservice(서피스 상태 변경 및 출력 요청)Surface flingerservice(서피스 상태 변경 및 출력 요청)
Surface flingerservice(서피스 상태 변경 및 출력 요청)fefe7270
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsSeok-joon Yun
 
TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편ymtech
 
Blockchain 3rd smart contract programming
Blockchain 3rd smart contract programmingBlockchain 3rd smart contract programming
Blockchain 3rd smart contract programmingihpark92
 
Android+init+process
Android+init+processAndroid+init+process
Android+init+processHong Jae Kwon
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSCirculus
 
Blockchain 4th dapp programming
Blockchain 4th dapp programmingBlockchain 4th dapp programming
Blockchain 4th dapp programmingihpark92
 
[Live coding] 2회 5 23 (camp-exam_javalanguage)
[Live coding] 2회 5 23 (camp-exam_javalanguage)[Live coding] 2회 5 23 (camp-exam_javalanguage)
[Live coding] 2회 5 23 (camp-exam_javalanguage)동욱 하
 
Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Circulus
 
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Isaac Jeon
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍NAVER D2
 
[스프링 스터디 2일차] 서비스 추상화
[스프링 스터디 2일차] 서비스 추상화[스프링 스터디 2일차] 서비스 추상화
[스프링 스터디 2일차] 서비스 추상화AnselmKim
 
스프링처럼 JDBC 리팩터링하기
스프링처럼 JDBC 리팩터링하기 스프링처럼 JDBC 리팩터링하기
스프링처럼 JDBC 리팩터링하기 Chanwook Park
 
#19.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#19.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#19.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#19.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Easy gameserver
Easy gameserverEasy gameserver
Easy gameserver진상 문
 
C Language I
C Language IC Language I
C Language ISuho Kwon
 
[D2] java 애플리케이션 트러블 슈팅 사례 & pinpoint
[D2] java 애플리케이션 트러블 슈팅 사례 & pinpoint [D2] java 애플리케이션 트러블 슈팅 사례 & pinpoint
[D2] java 애플리케이션 트러블 슈팅 사례 & pinpoint NAVER D2
 

Similar to Smc–state machinecompiler (20)

[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
Spring statemachine
Spring statemachineSpring statemachine
Spring statemachine
 
Surface flingerservice(서피스 상태 변경 jb)
Surface flingerservice(서피스 상태 변경 jb)Surface flingerservice(서피스 상태 변경 jb)
Surface flingerservice(서피스 상태 변경 jb)
 
Surface flingerservice(서피스 상태 변경 및 출력 요청)
Surface flingerservice(서피스 상태 변경 및 출력 요청)Surface flingerservice(서피스 상태 변경 및 출력 요청)
Surface flingerservice(서피스 상태 변경 및 출력 요청)
 
C++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threadsC++ Concurrency in Action 9-2 Interrupting threads
C++ Concurrency in Action 9-2 Interrupting threads
 
TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편TR 069 클라이언트 검토자료 3편
TR 069 클라이언트 검토자료 3편
 
Blockchain 3rd smart contract programming
Blockchain 3rd smart contract programmingBlockchain 3rd smart contract programming
Blockchain 3rd smart contract programming
 
Android+init+process
Android+init+processAndroid+init+process
Android+init+process
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JS
 
Blockchain 4th dapp programming
Blockchain 4th dapp programmingBlockchain 4th dapp programming
Blockchain 4th dapp programming
 
[Live coding] 2회 5 23 (camp-exam_javalanguage)
[Live coding] 2회 5 23 (camp-exam_javalanguage)[Live coding] 2회 5 23 (camp-exam_javalanguage)
[Live coding] 2회 5 23 (camp-exam_javalanguage)
 
Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리Startup JavaScript 3 - 조건문, 반복문, 예외처리
Startup JavaScript 3 - 조건문, 반복문, 예외처리
 
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
 
[스프링 스터디 2일차] 서비스 추상화
[스프링 스터디 2일차] 서비스 추상화[스프링 스터디 2일차] 서비스 추상화
[스프링 스터디 2일차] 서비스 추상화
 
스프링처럼 JDBC 리팩터링하기
스프링처럼 JDBC 리팩터링하기 스프링처럼 JDBC 리팩터링하기
스프링처럼 JDBC 리팩터링하기
 
#19.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#19.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#19.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#19.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Easy gameserver
Easy gameserverEasy gameserver
Easy gameserver
 
C Language I
C Language IC Language I
C Language I
 
[D2] java 애플리케이션 트러블 슈팅 사례 & pinpoint
[D2] java 애플리케이션 트러블 슈팅 사례 & pinpoint [D2] java 애플리케이션 트러블 슈팅 사례 & pinpoint
[D2] java 애플리케이션 트러블 슈팅 사례 & pinpoint
 

Smc–state machinecompiler

  • 1. SMC – State Machine Compiler jeddli@gmail.com 아꿈사. 이동현
  • 2. FSM? 상태기계를 이용하면 프로그램이 간단하고 이해하기 쉽다. C++ Code 수 많은 반복 코드와 노가다… 통제가 안될 정도로 커진다.
  • 3. 좀 더 견고한 방법. – 상태 기계 언어 고전적인 의미의 상태 기계와 현실적인 의미의 상태 기계. 대부분의 게임 개발자는 느슨한 정의를 이용. 상태안의 상태. 다중 상태 변수. 상태 전이의 임의성. 상태 안에서 모든 게임 tick를 실행하는 코드. 기타 생각할 수 있는 모든 것.
  • 4.
  • 5. 상태들이 int형태이며, 열거형이라면 더 견고하고 디버그 하기 쉬울 것이다.
  • 6. Break 키워드 하나만 지워도 찾기 어려운 버그들을 만들게 된다.
  • 7. 중복적인 논리가 다중 상태에 나타난다.
  • 8. 어떤 상태에 처음 들어갔는지를 알려줄 수 있는 방법이 없다.
  • 9.
  • 10. 상태 기계 언어 기본 예제 BeginStateMachine State( STATE_Wander ) OnEnter // 상태시작점에대한C나C++ 코드 OnUpdate // 매틱(tick)마다실행되는C나C++ 코드 OnExit // 상태의뒷정리를위한C나C++ 코드 State( STATE_Attack ) OnEnter // 상태시작점에대한C나C++ 코드 EndStateMachine #define BeginStateMachine if(state < 0) { if (0) { #define EndStateMachinereturn (true); }} else { assert(0);br />return (false); } return (false); #define State(a) return (true);}}else if(a == state){if(0){ #define OnEvent(a) return (true);}else if(a == event){ #define OnEnterOnEvent(EVENT_Enter) #define OnUpdateOnEvent(EVENT_Update) #define OnExitOnEvent(EVENT_Exit)
  • 11. 실제로 확장 해보면.. if( state < 0 ){ if( 0 ) { return ( true ); } }else if( STATE_Wander == state ) { if( 0 ){ return ( true ); }else if( EVENT_Enter== state ) { // 상태시작점에대한C++ 코드 return ( true ); }else if(EVENT_Update== state ) { // 매틱(tick)마다실행되는C++ 코드 return ( true ); }else if(EVENT_Wander== state ) { // 상태의뒷정리를위한C++ 코드 return ( true ); } }else if( STATE_Attack == state ) { if( 0 ){ return ( true ); }else if( EVENT_Enter == state ) { // 상태시작점에대한C++ 코드 return ( true ); } }else { assert(0); return( false ); } return false; BeginStateMachine State( STATE_Wander ) OnEnter // 상태시작점에대한C나C++ 코드 OnUpdate // 매틱(tick)마다실행되는C나C++ 코드 OnExit // 상태의뒷정리를위한C나C++ 코드 State( STATE_Attack ) OnEnter // 상태시작점에대한C나C++ 코드 EndStateMachine
  • 12. 좀 더 나아가서.. AI 디자이너의 생산성 높이기. GUI 기반의 모델링. C++ 코더로의 변환 용이성.
  • 13. CreatureMachine::CreatureMachine() { // add all variables to the variable list AddVariable("Health",VAR_INTEGER,&m_Health); AddVariable("EnemyLocation",VAR_POSITION,&m_Enemy; // now add conditions (may reference variables) AddCondition("InRange",LESSTHAN,"EnemyLocation",100); AddCondition("LowHealth",LESSTHAN,"Health", 50); // now add all the actions (may be referenced by the // states) AddAction("IdleAction"); AddAction("FightAction"); AddAction("FleeAction"); // now add all the states AddState("Idle","IdleAction"); AddState("Fight","FightAction"); AddState("Flee","FleeAction"); // now add all the transitions (may reference states // and variables) // transitions syntax : <condition-name> <start state> // <end state> AddTransition("In Range","Idle","Fight"); AddTransition("Low Health","Fight","Flee"); }; 다이어 그램의 코드화
  • 14.
  • 15. SMC – The State Map Compiler http://smc.sourceforge.net/SmcManual.htm “Your detailed state diagrams are only pictures. How are you going to translate your drawings into code? A transition matrix is cryptic while switch statements means your state machine logic is scattered all over your code. The state pattern looks like a great solution but that means writing and maintaining a class for each state - too much work.”
  • 16. SMC
  • 17. Adding a state machine to your class Download SMC - http://sourceforge.net/projects/smc/files/smc/6_0_0/smc_6_0_0.zip/download Include the SMC class definitions into your application. Include the state machine's source file. Instantiate the state machine's context object. If you want to execute the start state's entry actions call the state machine context's enterStartState method. This is not needed to set the start state as that is done when the state machine context is instantiated. enterStartState only executes the start state's entry actions (if any exist).
  • 18. Make SMC file // This FSM works for the Task class only and only the Task // class may instantiate it. %class Task %package com.acme.supercron %fsmclassTaskFSM %access package %start TaskFSM::Suspended %map TaskFSM %% <snip> Running Exit { stopSliceTimer(); } { Suspend Suspended { suspendTask(); } Block Blocked { blockTask(); } Done Stopped { releaseResources(); } } <snip> } %% End State Transition Action { Suspend Suspended { suspendTask(); } Block Blocked { blockTask(); } Done Stopped { releaseResources(); } }
  • 19. Transition Guards // State Idle { // Trans Run // Guard condition [ctxt.isProcessorAvailable() == true && ctxt.getConnection().isOpen() == true] // Next State Running // Actions { StopTimer("Idle"); DoWork(); } Run nil {RejectRequest();} }
  • 20. Transition Arguments // State Idle { // Transition Run(msg: const Message&) // Guard condition [ctxt.isProcessorAvailable() == true && msg.isValid() == true] // Next State Running // Actions { StopTimer("Idle"); DoWork(msg); } Run(msg: const Message&) // Next State Actions nil {RejectRequest(msg);} }
  • 21. Transition Arguments CLOSED { PassiveOpen(port: unsigned short) ServiceOpening { openServerSocket(port); } void MainMap_CLOSED::PassiveOpen(TcpConnectionContext& context, unsigned short port) { TcpConnection& ctxt(context.getOwner());
  • 22. Default Transitions What happens if a state receives a transition that is not defined in that state? Default { // Valid run request but transition occurred in an invalid // state. Send a reject reply to valid messages. Run(msg: const Message&) [ctxt.isProcessorAvailable() == true && msg.isValid() == true] nil { RejectRequest(msg); } // Ignore invalid messages are ignored when received in // an invalid state. Run(msg: const Message&) nil {} Shutdown ShuttingDown { StartShutdown(); } } Connecting { // We are now connected to the far-end. Now we can logon. Connected Connected { logon(); } // Any other transition at this point is an error. // Stop the connecting process and retry later. Default RetryConnection { stopConnecting(); } }
  • 23. Transition Precedence Guarded transition Unguarded transition The Default state's guarded definition. The Default state's unguarded definition. The current state's guarded Default transition. The current state's unguarded Default transition. The Default state's guarded Default transition. The Default state's unguarded Default transition.
  • 24. Compiling a .sm Prepare Java 1.6.0 or newer is properly installed and the "javac", "java" and "jar" executables are in your PATH environment variable. The standard Java Development Kit can be obtained for free from http://java.sun.com . The SMC_HOME environment variable contains the path to where SMC is installed. $ java -jar $SMC_HOME/bin/Smc.jar [-c | -c++ | -csharp | -graph | -groovy | -java | -lua | -objc | -perl | -php | -python | -ruby | -scala | -table | -tcl | -vb] <fsm_source_file>.sm
  • 25. Behind the Curtain GOF’s State Pattern SMC Pattern
  • 26. Ex4 State FSMContext StoplightState StoplightContext enterStartState StopMap_Default Stoplight StopMap_EastWestGreen StopMap_EastWestYellow StopMap_NorthSouthGreen StopMap_NorthSouthYellow StopMap