code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
// -*- Java -*- /*! * @file GAEConnector.java * @date $Date$ * * $Id$ */ import jp.go.aist.rtm.RTC.Manager; import jp.go.aist.rtm.RTC.RTObject_impl; import jp.go.aist.rtm.RTC.RtcDeleteFunc; import jp.go.aist.rtm.RTC.RtcNewFunc; import jp.go.aist.rtm.RTC.RegisterModuleFunc; import jp.go.aist.rtm.RTC.util.Properties; /*! * @class GAEConnector * @brief http connector for GAE */ public class GAEConnector implements RtcNewFunc, RtcDeleteFunc, RegisterModuleFunc { // Module specification // <rtc-template block="module_spec"> public static String component_conf[] = { "implementation_id", "GAEConnector", "type_name", "GAEConnector", "description", "http connector for GAE", "version", "1.0.0", "vendor", "AIST", "category", "Connector", "activity_type", "STATIC", "max_instance", "1", "language", "Java", "lang_type", "compile", "exec_cxt.periodic.rate", "1.0", // Configuration variables "conf.default.Account", "xxxxxxxx", "conf.default.Password", "xxxxxxxx", "" }; // </rtc-template> public RTObject_impl createRtc(Manager mgr) { return new GAEConnectorImpl(mgr); } public void deleteRtc(RTObject_impl rtcBase) { rtcBase = null; } public void registerModule() { Properties prop = new Properties(component_conf); final Manager manager = Manager.instance(); manager.registerFactory(prop, new GAEConnector(), new GAEConnector()); } }
100uhaco
trunk/RTC/java/GAEConnector/GAEConnector.java
Java
asf20
1,667
title GAEConnector cd C:.\GAEConnector set "CLASSPATH=.;%RTM_JAVA_ROOT%\jar\OpenRTM-aist-1.0.0.jar;%RTM_JAVA_ROOT%\jar\commons-cli-1.1.jar;C:.\lib\commons-codec-1.4.jar;C:.\lib\commons-httpclient-3.1.jar;C:.\lib\commons-logging-1.1.1.jar" java GAEConnectorComp
100uhaco
trunk/RTC/java/GAEConnector/classes/GAEConnector.bat
Batchfile
asf20
263
#include <NTP.h> #include <DateTime.h> #include <ASocket.h> #include <Client.h> #include <Ethernet.h> #include <Server.h> #include <PString.h> #include <Dhcp.h> #include <Dns.h> #include <string.h> #include <WString.h> //MAC ID\uff08\u5404\u30b7\u30fc\u30eb\u30c9\u306b\u8a18\u8f09\uff09 #include "WProgram.h" void setup(); void loop(); void makeMsg(int post_count, int current, int ilum, int temp); void post(char msg[]); void getTime(); void printArray(Print *output, char* delimeter, byte* data, int len, int base); void basic_make(const char *user_and_passwd); static char mime_code(const char c); void mimeEncode(const char *buf); void alert(); byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x5E }; //ip\u304c\u901a\u3063\u305f\u304b boolean ipAcquired = false; //DNS\u30af\u30e9\u30b9 DnsClass targetDns; //ip\u683c\u7d0d\u7528\u30d0\u30c3\u30d5\u30a1 byte buffer[6]; //NTP\u30b5\u30fc\u30d0\u306eip byte ntp_dot_nist_dot_jp[] = {133, 243, 238, 243}; // ntp.nict.jp //\u5404\u30bb\u30f3\u30b5\u30d4\u30f3 int ledPin = 2; int CurrentPin = 0; int IlumPin = 1; int TempPin = 2; //base64\u30a8\u30f3\u30b3\u30fc\u30c9\u5f8c\u306e\u6587\u5b57\u5217\u683c\u7d0d\u7528 char mime[65]; void setup() { Serial.begin(9600); //\u5185\u90e8\u96fb\u5727\u8a2d\u5b9a analogReference( INTERNAL); pinMode(ledPin, OUTPUT); //////////////////////////////////// /////\u30d9\u30fc\u30b7\u30c3\u30af\u8a8d\u8a3c\u7528ID\uff06PASS/////// //////////////////////////////////// basic_make("tanikawa:tanikawa"); Serial.println("getting ip..."); int result = Dhcp.beginWithDHCP(mac); if(result == 1) { ipAcquired = true; Serial.println("ip acquired..."); Dhcp.getMacAddress(buffer); Serial.print("mac address: "); printArray(&Serial, ":", buffer, 6, 16); Dhcp.getLocalIp(buffer); Serial.print("ip address: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getSubnetMask(buffer); Serial.print("subnet mask: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getGatewayIp(buffer); Serial.print("gateway ip: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getDhcpServerIp(buffer); Serial.print("dhcp server ip: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getDnsServerIp(buffer); Serial.print("dns server ip: "); printArray(&Serial, ".", buffer, 4, 10); //// Do DNS Lookup targetDns.init("100uhaco.appspot.com", buffer); //Buffer contains the IP address of the DNS server targetDns.resolve(); int results; while(!(results=targetDns.finished())) ; //wait for DNS to resolve the name if(results != 1) { Serial.print("DNS Error code: "); Serial.print(results,DEC); alert(); } targetDns.getIP(buffer); //buffer now contains the IP address for google.com Serial.print("target IP address: "); printArray(&Serial, ".", buffer, 4, 10); //NTP\u540c\u671f NTP ntp(ntp_dot_nist_dot_jp); DateTime.sync( (ntp.get_unix_gmt() + (9 * 60 * 60)) ); if( DateTime.available() ){ Serial.println("NTP OK"); } else{ Serial.println("NTP FALSE"); alert(); } } else{ Serial.println("unable to acquire ip address..."); alert(); } } void loop() { digitalWrite(ledPin, LOW); //\u30dd\u30b9\u30c8\u6e08\u307f\u30ca\u30f3\u30d0\u30fc static int posted =0; static int SAMPLE_COUNT =0; static int max_current = 0; static int current_tmp = 0; static int ilum_sum = 0; static int temp_sum =0; //\u88dc\u6b63\u7528sec int sec; getTime(); sec = (int)DateTime.Second; //\u73fe\u5728\u306epnum\u3092\u751f\u6210 int pnum = ((int)DateTime.Hour) * 6+ (int)DateTime.Minute / 10; if(pnum >= 144){ pnum = pnum - 144 ; } //10\u5206\u304a\u304d\u3001\u304b\u3064\u307e\u3060\u30dd\u30b9\u30c8\u3057\u3066\u3044\u306a\u304b\u3063\u305f\u5834\u5408 if( ((int)DateTime.Minute % 10) == 0 && (pnum != posted)){ int ilum_Value = 0; int temp_Value = 0; //\u5e73\u5747\u5316 if(SAMPLE_COUNT != 0){ ilum_Value = ilum_sum / SAMPLE_COUNT ; temp_Value = temp_sum / SAMPLE_COUNT ; } //HTTP\u901a\u4fe1 makeMsg(pnum, max_current, ilum_Value, temp_Value); //posted\u66f4\u65b0 posted = pnum; //\u521d\u671f\u5316 SAMPLE_COUNT =0; max_current = 0; current_tmp = 0; ilum_sum = 0; temp_sum =0; //\u70b9\u6ec5 digitalWrite(ledPin,HIGH); delay(1000); digitalWrite(ledPin, LOW); } //30\u79d2\u3054\u3068\u306b\u30c7\u30fc\u30bf\u3092\u53ce\u96c6 else if( ( 0 == sec)|| (sec == 30) ){ //\u96fb\u529b\u30c7\u30fc\u30bf current_tmp = analogRead(CurrentPin); if(max_current < current_tmp){ max_current = current_tmp; } //\u7167\u5ea6\u30c7\u30fc\u30bf ilum_sum +=analogRead(IlumPin); //\u6e29\u5ea6\u30c7\u30fc\u30bf temp_sum +=analogRead(TempPin); SAMPLE_COUNT++; Serial.println("logging"); Serial.println(max_current); Serial.println(ilum_sum); Serial.println(temp_sum); delay(30000); } } //\u30e1\u30c3\u30bb\u30fc\u30b8\u4f5c\u6210\u51e6\u7406 void makeMsg(int post_count, int current, int ilum, int temp) { char msg[200]; PString mystring(msg, sizeof(msg)); mystring.print("GET http://100uhaco.appspot.com/haco/record/"); mystring.print("?pnum="); mystring.print(post_count); mystring.print("&temp="); mystring.print(temp); mystring.print("&light="); mystring.print(ilum); mystring.print("&watt="); mystring.print(current); mystring.println(" HTTP/1.0 "); mystring.print("Authorization: Basic "); mystring.println(mime); post(msg); } //GAE\u306b\u30dd\u30b9\u30c8 void post(char msg[]) { // //HTTP request phase // Client client(buffer,80); Serial.println("HTTP connecting..."); if (client.connect()) { Serial.println("connected"); //client.write(msg); client.println(msg); client.println(); delay(100); Serial.println("disconnecting."); client.stop(); } } void getTime(){ if( DateTime.available() ) { //\u306a\u305c\u304b\u4e00\u30f6\u6708\u9045\u308c\u306a\u306e\u3067\u66ab\u5b9a\u7684\u306b+1 Serial.print((int)DateTime.Month + 1); Serial.print("/"); Serial.print((int)DateTime.Day); Serial.print(" "); Serial.print(((int)DateTime.Hour)); Serial.print(":"); Serial.print((int)DateTime.Minute); Serial.print(":"); Serial.print((int)DateTime.Second); Serial.println(" JST"); } } //IPadress\u7fa4\u3092\u51fa\u529b\u3059\u308b\u305f\u3081\u306e\u51e6\u7406 void printArray(Print *output, char* delimeter, byte* data, int len, int base) { char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(int i = 0; i < len; i++) { if(i != 0) output->print(delimeter); output->print(itoa(data[i], buf, base)); } output->println(); } // //\u30d9\u30fc\u30b7\u30c3\u30af\u8a8d\u8a3c\u7528base64\u30a8\u30f3\u30b3\u30fc\u30c9\u95a2\u6570\u90e1 //(Twitter\u30e9\u30a4\u30d6\u30e9\u30ea\u304b\u3089\u62dd\u501f) // void basic_make(const char *user_and_passwd) { mimeEncode(user_and_passwd); } static char mime_code(const char c) { if (c < 26) return c+'A'; if (c < 52) return c-26+'a'; if (c < 62) return c-52+'0'; if (c == 62) return '+'; return '/'; } void mimeEncode(const char *buf) { int i = 0, j = 0, c[3]; while (j < 64 && buf[i]) { c[0] = buf[i++]; c[1] = buf[i] ? buf[i++] : 0; c[2] = buf[i] ? buf[i++] : 0; mime[j++] = mime_code(c[0]>>2); mime[j++] = mime_code(((c[0]<<4)&0x30) | (c[1]>>4)); mime[j++] = c[1] ? mime_code(((c[1]<<2)&0x3c) | (c[2]>>6)) : '='; mime[j++] = c[2] ? mime_code(c[2]&0x3f) : '='; } mime[j] = 0; } void alert(){ while(1){ //\u30a2\u30e9\u30fc\u30c8 digitalWrite(ledPin,HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); } } int main(void) { init(); setup(); for (;;) loop(); return 0; }
100uhaco
trunk/Arduino/Sender/applet/Sender.cpp
C++
asf20
8,185
#include <NTP.h> #include <DateTime.h> #include <ASocket.h> #include <Client.h> #include <Ethernet.h> #include <Server.h> #include <PString.h> #include <Dhcp.h> #include <Dns.h> #include <string.h> #include <WString.h> //MAC ID(各シールドに記載) byte mac[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //ipが通ったか boolean ipAcquired = false; //DNSクラス DnsClass targetDns; //ip格納用バッファ byte buffer[6]; //NTPサーバのip byte ntp_dot_nist_dot_jp[] = {133, 243, 238, 243}; // ntp.nict.jp //各センサピン int ledPin = 2; int CurrentPin = 0; int IlumPin = 1; int TempPin = 2; //base64エンコード後の文字列格納用 char mime[65]; void setup() { Serial.begin(9600); //内部電圧設定 analogReference( INTERNAL); pinMode(ledPin, OUTPUT); //////////////////////////////////// /////ベーシック認証用ID&PASS/////// //////////////////////////////////// basic_make("id:pass"); Serial.println("getting ip..."); int result = Dhcp.beginWithDHCP(mac); if(result == 1) { ipAcquired = true; Serial.println("ip acquired..."); Dhcp.getMacAddress(buffer); Serial.print("mac address: "); printArray(&Serial, ":", buffer, 6, 16); Dhcp.getLocalIp(buffer); Serial.print("ip address: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getSubnetMask(buffer); Serial.print("subnet mask: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getGatewayIp(buffer); Serial.print("gateway ip: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getDhcpServerIp(buffer); Serial.print("dhcp server ip: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getDnsServerIp(buffer); Serial.print("dns server ip: "); printArray(&Serial, ".", buffer, 4, 10); //// Do DNS Lookup targetDns.init("100uhaco.appspot.com", buffer); //Buffer contains the IP address of the DNS server targetDns.resolve(); int results; while(!(results=targetDns.finished())) ; //wait for DNS to resolve the name if(results != 1) { Serial.print("DNS Error code: "); Serial.print(results,DEC); alert(); } targetDns.getIP(buffer); //buffer now contains the IP address for google.com Serial.print("target IP address: "); printArray(&Serial, ".", buffer, 4, 10); //NTP同期 NTP ntp(ntp_dot_nist_dot_jp); DateTime.sync( (ntp.get_unix_gmt() + (9 * 60 * 60)) ); if( DateTime.available() ){ Serial.println("NTP OK"); } else{ Serial.println("NTP FALSE"); alert(); } } else{ Serial.println("unable to acquire ip address..."); alert(); } } void loop() { digitalWrite(ledPin, LOW); //ポスト済みナンバー static int posted =0; static int SAMPLE_COUNT =0; static int max_current = 0; static int current_tmp = 0; static int ilum_sum = 0; static int temp_sum =0; //補正用sec int sec; getTime(); sec = (int)DateTime.Second; //現在のpnumを生成 int pnum = ((int)DateTime.Hour) * 6+ (int)DateTime.Minute / 10; if(pnum >= 144){ pnum = pnum - 144 ; } //10分おき、かつまだポストしていなかった場合 if( ((int)DateTime.Minute % 10) == 0 && (pnum != posted)){ int ilum_Value = 0; int temp_Value = 0; //平均化 if(SAMPLE_COUNT != 0){ ilum_Value = ilum_sum / SAMPLE_COUNT ; temp_Value = temp_sum / SAMPLE_COUNT ; } //HTTP通信 makeMsg(pnum, max_current, ilum_Value, temp_Value); //posted更新 posted = pnum; //初期化 SAMPLE_COUNT =0; max_current = 0; current_tmp = 0; ilum_sum = 0; temp_sum =0; //点滅 digitalWrite(ledPin,HIGH); delay(1000); digitalWrite(ledPin, LOW); } //30秒ごとにデータを収集 else if( ( 0 == sec)|| (sec == 30) ){ //電力データ current_tmp = analogRead(CurrentPin); if(max_current < current_tmp){ max_current = current_tmp; } //照度データ ilum_sum +=analogRead(IlumPin); //温度データ temp_sum +=analogRead(TempPin); SAMPLE_COUNT++; Serial.println("logging"); Serial.println(max_current); Serial.println(ilum_sum); Serial.println(temp_sum); delay(30000); } } //メッセージ作成処理 void makeMsg(int post_count, int current, int ilum, int temp) { char msg[200]; PString mystring(msg, sizeof(msg)); mystring.print("GET http://100uhaco.appspot.com/haco/record/"); mystring.print("?pnum="); mystring.print(post_count); mystring.print("&temp="); mystring.print(temp); mystring.print("&light="); mystring.print(ilum); mystring.print("&watt="); mystring.print(current); mystring.println(" HTTP/1.0 "); mystring.print("Authorization: Basic "); mystring.println(mime); post(msg); } //GAEにポスト void post(char msg[]) { // //HTTP request phase // Client client(buffer,80); Serial.println("HTTP connecting..."); if (client.connect()) { Serial.println("connected"); //client.write(msg); client.println(msg); client.println(); delay(100); Serial.println("disconnecting."); client.stop(); } } void getTime(){ if( DateTime.available() ) { //なぜか一ヶ月遅れなので暫定的に+1 Serial.print((int)DateTime.Month + 1); Serial.print("/"); Serial.print((int)DateTime.Day); Serial.print(" "); Serial.print(((int)DateTime.Hour)); Serial.print(":"); Serial.print((int)DateTime.Minute); Serial.print(":"); Serial.print((int)DateTime.Second); Serial.println(" JST"); } } //IPadress群を出力するための処理 void printArray(Print *output, char* delimeter, byte* data, int len, int base) { char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(int i = 0; i < len; i++) { if(i != 0) output->print(delimeter); output->print(itoa(data[i], buf, base)); } output->println(); } // //ベーシック認証用base64エンコード関数郡 //(Twitterライブラリから拝借) // void basic_make(const char *user_and_passwd) { mimeEncode(user_and_passwd); } static char mime_code(const char c) { if (c < 26) return c+'A'; if (c < 52) return c-26+'a'; if (c < 62) return c-52+'0'; if (c == 62) return '+'; return '/'; } void mimeEncode(const char *buf) { int i = 0, j = 0, c[3]; while (j < 64 && buf[i]) { c[0] = buf[i++]; c[1] = buf[i] ? buf[i++] : 0; c[2] = buf[i] ? buf[i++] : 0; mime[j++] = mime_code(c[0]>>2); mime[j++] = mime_code(((c[0]<<4)&0x30) | (c[1]>>4)); mime[j++] = c[1] ? mime_code(((c[1]<<2)&0x3c) | (c[2]>>6)) : '='; mime[j++] = c[2] ? mime_code(c[2]&0x3f) : '='; } mime[j] = 0; } void alert(){ while(1){ //アラート digitalWrite(ledPin,HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); } }
100uhaco
trunk/Arduino/Sender/Sender.pde
Processing
asf20
7,104
#include <Ethernet.h> #include <WString.h> #include <ASocket.h> #include <Client.h> #include <Server.h> #include <PString.h> #include <Dhcp.h> #include <Dns.h> #include <string.h> #include <UdpBytewise.h> //RTC用ステータスコード #define RTC_ON_INITIALIZE 0 #define RTC_ON_SHUTDOWN 1 #define RTC_ON_STARTUP 2 #define RTC_ON_ACTIVATE 3 #define RTC_ON_EXEXCUTE 4 #define RTC_ON_DEACTIVATE 5 #define RTC_ON_ERROR 6 #define RTC_ON_RESET 7 #define RTC_ON_ABORTING 8 //MAC ID(各シールドに記載) //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x22, 0x51 }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x22, 0x55 }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x58 }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x37 }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x46 }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x5E }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x87 }; byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x8B }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x3B }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x40 }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x47 }; //byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x4F }; //ipが通ったか boolean ipAcquired = false; //サーバIP byte ip[4]; //受信IP byte remoteIp[4]; //受信パケットサイズ int packetSize; //DNSクラス DnsClass targetDns; //ip格納用バッファ byte buffer[6]; //ポート設定(80:HTTPプロトコル) Server server(80); //接続フラグ boolean connect_flg = false; //リクエスト格納用文字列 String inString = String(80); //各センサピン int ledPin = 2; int CurrentPin = 0; int IlumPin = 1; int TempPin = 2; void setup(){ //読み取り電圧設定 analogReference(INTERNAL); Serial.begin(9600); pinMode(ledPin, OUTPUT); Serial.println("getting ip..."); int result = Dhcp.beginWithDHCP(mac); Serial.println(result); if(result == 1) { ipAcquired = true; Serial.println("ip acquired..."); Dhcp.getMacAddress(buffer); Serial.print("mac address: "); printArray(&Serial, ":", buffer, 6, 16, false); Dhcp.getLocalIp(buffer); Serial.print("ip address: "); //ipアドレスをip[]に格納 printArray(&Serial, ".", buffer, 4, 10, true); Dhcp.getSubnetMask(buffer); Serial.print("subnet mask: "); printArray(&Serial, ".", buffer, 4, 10, false); Dhcp.getGatewayIp(buffer); Serial.print("gateway ip: "); printArray(&Serial, ".", buffer, 4, 10, false); Dhcp.getDhcpServerIp(buffer); Serial.print("dhcp server ip: "); printArray(&Serial, ".", buffer, 4, 10, false); Dhcp.getDnsServerIp(buffer); Serial.print("dns server ip: "); printArray(&Serial, ".", buffer, 4, 10, false); Serial.println("Ethernet.begin"); //サーバ開始 server.begin(); UdpBytewise.begin(80); } } void loop(){ digitalWrite(ledPin, LOW); // //UDPゾーン // //コネクト確立フラグが立っていない場合 if(!connect_flg){ if(packetSize = UdpBytewise.available()) { Serial.print("Received packet of size "); Serial.println(packetSize); //送信先のIPをremoteIpに格納 UdpBytewise.getSenderIp(remoteIp); Serial.print("From IP "); for(int i=0; i<4; i++) { Serial.print(remoteIp[i],DEC); if(i<3) Serial.print("."); } Serial.println("Contents:"); while(UdpBytewise.available()) { Serial.print(UdpBytewise.read(),BYTE); } //送信先ポート1300に返信 UdpBytewise.beginPacket(remoteIp,1300); //MACを送付 for(int m=0; m<6; m++) { UdpBytewise.print(mac[m],HEX); if(m<5) UdpBytewise.print("-"); } UdpBytewise.endPacket(); delay(500); } } //wait a bit delay(10); // //HTTPゾーン // //RTCステータスの初期化 int state = -1; //クライアントからのデータ受信 Client client = server.available(); if (client) { digitalWrite(ledPin, HIGH); Serial.println("http access"); //読み込み用文字列の初期化 inString=String(""); boolean blank_line = true; while (client.connected()) { if (client.available()) { char c = client.read(); inString.append(c); //最初の一行のみ走査 if (c == '\n') { //コマンドが含まれているか走査し、ステータスコードを設定 if(inString.contains("GET")){ //if(inString.contains("INT")){ // state = 0; //} //if(inString.contains("SHT")){ // state = 1; //} //if(inString.contains("STA")){ // state = 2; //} if(inString.contains("ACT")){ state = 3; } if(inString.contains("EXE")){ state = 4; } if(inString.contains("DEA")){ state = 5; } //if(inString.contains("ERR")){ // state = 6; //} //if(inString.contains("RST")){ // state = 7; //} //if(inString.contains("ABT")){ // state = 8; //} server.println("HTTP/1.1 200 OK"); server.println("Content-Type: text/html"); server.println(); //RTC実装関数で残りのヘッダ部分を作成 RTC_impl(state); break; } } } } //終了処理 delay(1); client.stop(); } } //RTCハンドラの実装 void RTC_impl(int state){ switch (state) { case RTC_ON_INITIALIZE: break; case RTC_ON_SHUTDOWN: break; case RTC_ON_STARTUP: break; case RTC_ON_ACTIVATE: connect_flg = true; break; case RTC_ON_EXEXCUTE:{ int SAMPLE_COUNT =30; int max_current = 0; int current_tmp = 0; int temp_sum =0; int ilum_sum =0; for( int i =0; i <SAMPLE_COUNT; i++){ //電流値データ current_tmp = analogRead(CurrentPin); if(max_current < current_tmp){ max_current = current_tmp; } //温度データ temp_sum +=analogRead(TempPin); //照度データ ilum_sum +=analogRead(IlumPin); } //平均化 int ilum_Value = ilum_sum / SAMPLE_COUNT ; int temp_Value = temp_sum / SAMPLE_COUNT ; //サーバへ書き出し server.println(max_current); server.println(ilum_Value); server.println(temp_Value); break; } case RTC_ON_DEACTIVATE: connect_flg = false; break; case RTC_ON_ERROR: break; case RTC_ON_RESET: break; case RTC_ON_ABORTING: break; default: break; } } //IPadress群を出力するための処理 void printArray(Print *output, char* delimeter, byte* data, int len, int base, boolean flg) { char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(int i = 0; i < len; i++) { if(i != 0) output->print(delimeter); if(flg){ ip[i] = data[i];} output->print(itoa(data[i], buf, base)); } output->println(); }
100uhaco
trunk/Arduino/Sender_RTC/Sender_RTC.pde
Processing
asf20
7,407
window.site_data = {};window.site_data.settings = {"MEDIA_URL": "/media/1/"};
100uhaco
trunk/.dynamic_media/mediautils-site_data.js
JavaScript
asf20
77
var LANGUAGE_CODE = "de"; var LANGUAGE_BIDI = false; /* gettext library */ var catalog = new Array(); function pluralidx(count) { return (count == 1) ? 0 : 1; } function gettext(msgid) { var value = catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } } function ngettext(singular, plural, count) { value = catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value[pluralidx(count)]; } } function gettext_noop(msgid) { return msgid; } function interpolate(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } } window.hgettext = function(text) { return gettext(text); }; window.hngettext = function(singular, plural, count) { return ngettext(singular, plural, count); };
100uhaco
trunk/.dynamic_media/mediautils-lang-de.js
JavaScript
asf20
1,017
var LANGUAGE_CODE = "en"; var LANGUAGE_BIDI = false; /* gettext library */ var catalog = new Array(); function pluralidx(count) { return (count == 1) ? 0 : 1; } function gettext(msgid) { var value = catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } } function ngettext(singular, plural, count) { value = catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value[pluralidx(count)]; } } function gettext_noop(msgid) { return msgid; } function interpolate(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } } window.hgettext = function(text) { return gettext(text); }; window.hngettext = function(singular, plural, count) { return ngettext(singular, plural, count); };
100uhaco
trunk/.dynamic_media/mediautils-lang-en.js
JavaScript
asf20
1,017
# -*- coding: utf-8 -*- #!/bin/env python import socket import urllib import urllib2 ######################################################################### ##-backup_csvスクリプトの使用方法について- ## ##以下で実行されます。 ##>backup("ID","PASS", min, max ) ## 各パラメータについて ## ID,PASS ## 100uhacoプロジェクトに使用しているもの ## min,max ## "今日"から"四日前"のデータを保存したい場合は ## min=0,max=-4のように指定。 ## ##出力先はスクリプト実行ディレクトリとなり、以下の形式で保存されます。 ##"ID"-backup.csv (ex:pot-backup.csv) ## ######################################################################### def backup(ID, passwd,min ,max): if max > min: print "Invalid" elif min > 0: print "Invalid" else: socket.setdefaulttimeout(31) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(username= ID, password= passwd)) try: f = opener.open('http://100uhaco.appspot.com/account/login/?next=/haco/csv/', params) data = f.read() if not data.count("Login"): f.close() for delta in range(max, min + 1): load(ID, passwd, opener, delta) else: f.close() print "Auth Error" except Exception , e: print e def load(ID, passwd, opener, delta): print("processing day "+str(delta)+" data") URL = "http://100uhaco.appspot.com/haco/csv/?delta=" + str(delta) try: f = opener.open(URL) data = f.read() f.close() w_file(ID, data) except urllib2.HTTPError,e : print " Failed:" + str(e) def w_file(ID, data): title = ID +"-backup.csv" file = open(title, "a") print >> file ,data
100uhaco
trunk/doc/backup-tool/backup_csv.py
Python
asf20
2,412
# -*- coding: utf-8 -*- #!/bin/env python import socket import urllib import urllib2 import xml.dom.minidom ######################################################################### ##-backupスクリプトの使用方法について- ## ##以下で実行されます。 ##>backup("ID","PASS", min, max ) ## 各パラメータについて ## ID,PASS ## 100uhacoプロジェクトに使用しているもの ## min,max ## "今日"から"四日前"のデータを保存したい場合は ## min=0,max=-4のように指定。 ## ##出力先はスクリプト実行ディレクトリとなり、以下の形式で保存されます。 ##"ID"-"指定した日付".xml (ex:pot-2010-03-26.xml) ## ######################################################################### def backup(ID, passwd,min ,max): if max > min: print "Invalid" elif min > 0: print "Invalid" else: socket.setdefaulttimeout(31) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(username= ID, password= passwd)) try: f = opener.open('http://100uhaco.appspot.com/account/login/?next=/haco/csv/', params) data = f.read() if not data.count("Login"): f.close() for delta in range(max, min + 1): load(ID, passwd, opener, delta) else: f.close() print "Auth Error" except Exception , e: print e def load(ID, passwd, opener, delta): URL = "http://100uhaco.appspot.com/haco/feed/?delta=" + str(delta) try: f = opener.open(URL) data = f.read() f.close() title = naming(data) w_file( data, title) except urllib2.HTTPError,e : print " Failed:" + str(e) def w_file( data , title): file = open(title,"a") print >> file ,data def naming( data): dom = xml.dom.minidom.parseString(data) dates = dom.getElementsByTagName("date") usernames = dom.getElementsByTagName("username") date = elements( dates) username = elements( usernames) dom.unlink() print "genarating file:" +username +"-"+ date+".xml" return username +"-"+ date+".xml" def elements( nodes): for node in nodes: return node.childNodes[0].data
100uhaco
trunk/doc/backup-tool/backup.py
Python
asf20
2,913
#clock { background-color:red; color:white; }
0corrina-kmltreeclone
examples/remote.css
CSS
bsd
53
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>kmlLoaded Event</title> <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script> <!-- earth-api-utility-library dependencies --> <script src="http://geojs.googlecode.com/svn/trunk/dist/geo.pack.js" type="text/javascript" charset="utf-8"></script> <script src="http://earth-api-utility-library.googlecode.com/svn/trunk/extensions/dist/extensions.pack.js" type="text/javascript" charset="utf-8"></script> <!-- kmltree source files --> <link rel="stylesheet" href="../dist/kmltree.css" media="screen"> <script src="../dist/kmltree.min.js" type="text/javascript"></script> <link rel="stylesheet" href="examples.css" type="text/css" media="screen" title="no title" charset="utf-8"> <script type="text/javascript" charset="utf-8"> google.load("earth", "1"); function init() { google.earth.createInstance('map3d', initCB, failureCB); } function initCB(instance) { ge = instance; ge.getWindow().setVisibility(true); var gex = gex = new GEarthExtensions(ge); var tree = kmltree({ url: './kml/hello.kml', gex: gex, mapElement: $('#map3d'), element: $('#tree'), setExtent: true }); $(tree).bind('kmlLoaded', function(event, kmlObject){ alert(event.type + " triggered. kmlObject type = " + kmlObject.getType()); }); tree.load(); } function failureCB(errorCode) { alert('failed to load plugin'); } $(document).ready(init); </script> </head> <body> <h1><a href="http://code.google.com/p/kmltree/">kmltree</a> > <a href="http://code.google.com/p/kmltree/wiki/ExampleUses">examples</a> > kmlLoaded event</h1> <a class="src" href="kml/hello.kml">source kml</a> <p class="description"> kmltree triggers kmlLoaded events whenever a kml file is loaded or refreshed. </p> <div id="tree"></div> <div id="map3d"></div> <br style="clear:both;"> </body> </html>
0corrina-kmltreeclone
examples/kmlLoaded.html
HTML
bsd
2,771
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>kmlLoaded Event</title> <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script> <!-- earth-api-utility-library dependencies --> <script src="http://geojs.googlecode.com/svn/trunk/dist/geo.pack.js" type="text/javascript" charset="utf-8"></script> <script src="http://earth-api-utility-library.googlecode.com/svn/trunk/extensions/dist/extensions.pack.js" type="text/javascript" charset="utf-8"></script> <!-- kmltree source files --> <link rel="stylesheet" href="../dist/kmltree.css" media="screen"> <script src="../dist/kmltree.min.js" type="text/javascript"></script> <link rel="stylesheet" href="examples.css" type="text/css" media="screen" title="no title" charset="utf-8"> <script src="examples.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> google.load("earth", "1"); function init() { google.earth.createInstance('map3d', initCB, failureCB); } function initCB(instance) { var log = new Log(); ge = instance; ge.getWindow().setVisibility(true); var gex = gex = new GEarthExtensions(ge); var tree = kmltree({ url: './kml/clickEvents.kml', gex: gex, mapElement: $('#map3d'), element: $('#tree'), setExtent: true }); $(tree).bind('click', function(event, node, kmlObject){ log.add('clicked "'+kmlObject.getName() + '"'); }); $(tree).bind('dblclick', function(event, node, kmlObject){ log.add('dblclicked "'+kmlObject.getName() + '"'); }); tree.load(); } function failureCB(errorCode) { alert('failed to load plugin'); } $(document).ready(init); </script> </head> <body> <h1><a href="http://code.google.com/p/kmltree/">kmltree</a> > <a href="http://code.google.com/p/kmltree/wiki/ExampleUses">examples</a> > click events</h1> <a class="src" href="kml/clickEvents.kml">source kml</a> <p class="description"> Events fired whenever a node is clicked in the tree. </p> <div id="tree"></div> <div id="map3d"></div> <br style="clear:both;"> </body> </html>
0corrina-kmltreeclone
examples/clickEvents.html
HTML
bsd
2,995
$(document).one('ready', function(){ // Append stylesheets addLinks([ 'http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css', 'examples.css', '../dist/kmltree.css' ]); $.ajaxSetup({ dataType: 'script' }); $.when( $.ajax({url: 'http://geojs.googlecode.com/svn/trunk/dist/geo.pack.js'}), $.ajax({url: 'http://earth-api-utility-library.googlecode.com/svn/trunk/extensions/dist/extensions.pack.js'}), $.ajax({url: '../dist/kmltree.min.js'}) ) .then(function(){ var t = $('#sample').html(); jQuery.globalEval(t); $(document).trigger('ready'); setTimeout(function(){ resizeMap3d(); }, 100); setTimeout(function(){ if(tree){ $('a.src').attr('href', tree.url); } }, 2000); }) .fail(function(){ alert('error loading scripts'); }) $('.description').before($('<a class="src" href="#">source kml</a><h1><a href="http://code.google.com/p/kmltree/">kmltree</a> > <a href="http://code.google.com/p/kmltree/wiki/ExampleUses">examples</a> > <span class="breadcrumb-end"></span></h1><div id="tree"></div><div id="tree2"></div><div id="map3d"></div><br style="clear:both;">')); $('span.breadcrumb-end').text($('title').text()); $('.content').append('<pre class="prettyprint" id="codeSample"></pre>'); $('#codeSample').text($('#sample').html()); jQuery.getScript('http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js', function(){ prettyPrint(); }); $(window).resize(function(){ resizeMap3d(); }); }); function resizeMap3d(){ var cw = $('.content').width(); var tw = $('#tree').width(); var mw = $('#map3d').width(); $('#map3d').width(cw - tw - 23); } function addLink(href){ var link = $("<link/>").appendTo($("head")); link.attr({ rel: "stylesheet", href: href }); } function addLinks(hrefs){ for(var i=0;i<hrefs.length;i++){ addLink(hrefs[i]); } }
0corrina-kmltreeclone
examples/examples.js
JavaScript
bsd
2,177
html, body { margin:0px; padding:0px; background-color:#4C6882; } .content { margin-left:auto; margin-right:auto; width:90%; background-color:white; border:solid 2px #314253; border-top:none; } #tree { float:left; padding:10px; width:35%; height: 650px; overflow-y:auto; } #tree2 { position:absolute; top:250px; left:6%; } #map3d { float:right; height: 665px; width: 65%; } h1 { background-color:#E6E6E6; font-size:1em; font-weight:normal; font-family:sans-serif; margin:0; padding:10px; } #nav { margin:0px; margin-top:7px; position:absolute; top:0px; right:5px; padding:5px; list-style:none; } #nav a, #nav a:visited { color:#DBE8EB; } #nav li { margin:0px; padding:0px; float:left; } a.src { float:right; padding:10px; top:10px; left:10px; padding-left:20px; background: transparent url(kml.png) no-repeat left center; } p { padding:10px; } ul.log { position:absolute; left:250px; top:0; margin:0; padding:0; } ul.log li { list-style:none; background-color:#EDDD83; margin:5px; padding:5px; } #codeSample { padding:0; margin:0; border:none; }
0corrina-kmltreeclone
examples/examples.css
CSS
bsd
1,282
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Combo KML Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script src="examples.js" type="text/javascript"></script> <script src="https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22earth%22%2C%22version%22%3A%221%22%7D%5D%7D&key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ" type="text/javascript" charset="utf-8"></script> <script id="sample" type="text/example" charset="utf-8"> var tree; var gex; $(document).ready(function(){ google.earth.createInstance('map3d', init, failure); }); function init(ge) { ge.getWindow().setVisibility(true); gex = new GEarthExtensions(ge); $('#submit').show(); $('#urlform').submit(function(e){ e.preventDefault(); if(tree && tree.destroy){ tree.destroy(); } $('#tree').replaceWith('<div id="tree" class="tree"></div>'); var url = $('#url').attr('value'); if(url){ tree = kmltree({ url: url, gex: gex, mapElement: $('#map3d'), element: $('.tree'), restoreState: false }); tree.load(); $('#refresh').show(); }else{ alert('you must enter a url'); } }); $('#refresh').click(function(e){ tree.refresh(); e.preventDefault(); }); } function failure(errorCode) { alert('failed to load plugin'); } </script> </head> <body> <div class="content"> <p class="description"> This example demonstrates one of kmltree's most useful features, state restoration. Load any kml file with the following form, and expand/contract folders, toggle features, etc. Hitting refresh will reload the tree, preserving your changes. </p> <form style="margin:0px; padding:0;padding-left:10px;" id="urlform"> <input style="width:500px;" type="text" name="url" value="http://kmltree.googlecode.com/hg/examples/demo.kmz" id="url" autofocus> <input type="submit" id="submit" name="submit"> <button id="refresh" style="display:none;">refresh</button> </form> </div> </body> </html>
0corrina-kmltreeclone
examples/refresh.html
HTML
bsd
3,073
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Combo KML Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script src="examples.js" type="text/javascript"></script> <script src="https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22earth%22%2C%22version%22%3A%221%22%7D%5D%7D&key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ" type="text/javascript" charset="utf-8"></script> <script id="sample" type="text/example" charset="utf-8"> var tree; $(document).ready(function(){ google.earth.createInstance('map3d', init, failure); }); function init(ge) { ge.getWindow().setVisibility(true); var gex = gex = new GEarthExtensions(ge); tree = kmltree({ url: './kml/kmlForestTest.kml', gex: gex, mapElement: $('#map3d'), element: $('#tree'), setExtent: true }); tree.load(); } function failure(errorCode) { alert('failed to load plugin'); } </script> </head> <body> <div class="content"> <p class="description"> This example demonstrates how kmltree renders a wide variety of KML features, included NetworkLinks, Tours, Placemarks, and Folders. Notice that some Placemarks have custom icons, and that you can expand NetworkLinks. Also, the visibility and open state specified within the kml document is respected. </p> </div> </body> </html>
0corrina-kmltreeclone
examples/comboExample.html
HTML
bsd
2,014
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Simple Example</title> <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script> <!-- earth-api-utility-library dependencies --> <script src="http://geojs.googlecode.com/svn/trunk/dist/geo.pack.js" type="text/javascript" charset="utf-8"></script> <script src="http://earth-api-utility-library.googlecode.com/svn/trunk/extensions/dist/extensions.pack.js" type="text/javascript" charset="utf-8"></script> <!-- kmltree source files --> <link rel="stylesheet" href="../dist/kmltree.css" media="screen"> <script src="../dist/kmltree.min.js" type="text/javascript"></script> <link rel="stylesheet" href="examples.css" type="text/css" media="screen" title="no title" charset="utf-8"> <script type="text/javascript" charset="utf-8"> google.load("earth", "1"); function init() { google.earth.createInstance('map3d', initCB, failureCB); } function initCB(instance) { ge = instance; $('h1').text('You have version '+ge.getPluginVersion() + ' of the Google Earth Plugin'); $('#map3d').hide(); } function failureCB(errorCode) { alert('failed to load plugin'); } $(document).ready(init); </script> </head> <body> <h1></h1> <div id="map3d"></div> <br style="clear:both;"> </body> </html>
0corrina-kmltreeclone
examples/apiVersion.html
HTML
bsd
1,855
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Popup Whitelist</title> <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script> <!-- earth-api-utility-library dependencies --> <script src="http://geojs.googlecode.com/svn/trunk/dist/geo.pack.js" type="text/javascript" charset="utf-8"></script> <script src="http://earth-api-utility-library.googlecode.com/svn/trunk/extensions/dist/extensions.pack.js" type="text/javascript" charset="utf-8"></script> <!-- kmltree source files --> <link rel="stylesheet" href="../dist/kmltree.css" media="screen"> <script src="../dist/kmltree.min.js" type="text/javascript"></script> <link rel="stylesheet" href="examples.css" type="text/css" media="screen" title="no title" charset="utf-8"> <script type="text/javascript" charset="utf-8"> google.load("earth", "1"); var tree; var gex; function init() { google.earth.createInstance('map3d', initCB, failureCB); } function initCB(instance) { ge = instance; ge.getWindow().setVisibility(true); gex = new GEarthExtensions(ge); $('#submit').show(); $('#urlform').submit(function(e){ if(tree){ tree.destroy(); } $('.tree').replaceWith('<div class="tree"></div>'); e.preventDefault(); var url = $('#url').attr('value'); if(url){ tree = kmltree({ url: url, gex: gex, mapElement: $('#map3d'), element: $('.tree'), restoreState: false, whitelist: [ new RegExp(''), ] }); // console.time('load'); // console.profile(); $(tree).one('kmlLoaded', function(e, kmlObject){ // console.profileEnd(); // console.timeEnd('load'); }); tree.load(); $('#refresh').show(); }else{ alert('you must enter a url'); } }); $('#refresh').click(function(e){ // console.profile(); // console.time('refresh'); tree.refresh(); $(tree).one('kmlLoaded', function(e, kmlObject){ // console.log('loaded'); // console.profileEnd(); // console.timeEnd('refresh'); }); e.preventDefault(); }); } function failureCB(errorCode) { alert('failed to load plugin'); } $(document).ready(init); </script> </head> <body> <h1><a href="http://code.google.com/p/kmltree/">kmltree</a> > <a href="http://code.google.com/p/kmltree/wiki/ExampleUses">examples</a> > whitelisted popups</h1> <p class="description" style="margin-bottom:0px;"> In this example the whitelist is set to support full css, javascript and html on all loaded kml files. Copy&paste the url of a kml file below to test. </p> <form style="margin:0px; padding:0;padding-left:10px;" id="urlform"> <input style="width:500px;" type="text" name="url" value="http://kmltree.googlecode.com/hg/examples/demo.kmz" id="url" autofocus> <input type="submit" id="submit" name="submit"> <button id="refresh" style="display:none;">refresh</button> </form> <div class="tree"></div> <div id="map3d"></div> <br style="clear:both;"> </body> </html>
0corrina-kmltreeclone
examples/refreshWithWhitelist.html
HTML
bsd
4,470
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Simple Example</title> <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script> <!-- earth-api-utility-library dependencies --> <script src="http://geojs.googlecode.com/svn/trunk/dist/geo.pack.js" type="text/javascript" charset="utf-8"></script> <script src="http://earth-api-utility-library.googlecode.com/svn/trunk/extensions/dist/extensions.pack.js" type="text/javascript" charset="utf-8"></script> <!-- kmltree source files --> <link rel="stylesheet" href="../dist/kmltree.css" media="screen"> <script src="../dist/kmltree.min.js" type="text/javascript"></script> <link rel="stylesheet" href="examples.css" type="text/css" media="screen" title="no title" charset="utf-8"> <script type="text/javascript" charset="utf-8"> google.load("earth", "1"); function init() { google.earth.createInstance('map3d', initCB, failureCB); } function initCB(instance) { ge = instance; ge.getWindow().setVisibility(true); var gex = gex = new GEarthExtensions(ge); var tree = kmltree({ url: './kml/hello.kml', gex: gex, element: $('#tree'), mapElement: $('#map3d'), setExtent: true }); tree.load(); } function failureCB(errorCode) { alert('failed to load plugin'); } $(document).ready(init); </script> </head> <body> <h1><a href="http://code.google.com/p/kmltree/">kmltree</a> > <a href="http://code.google.com/p/kmltree/wiki/ExampleUses">examples</a> > hello world</h1> <a class="src" href="kml/hello.kml">source kml</a> <p class="description"> This simple example shows how to display a kml file via a relative link. </p> <div id="tree"></div> <div id="map3d"></div> <br style="clear:both;"> </body> </html>
0corrina-kmltreeclone
examples/hello.html
HTML
bsd
2,534
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Panoramio and Youtube Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script src="examples.js" type="text/javascript"></script> <script src="https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22earth%22%2C%22version%22%3A%221%22%7D%5D%7D&key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ" type="text/javascript" charset="utf-8"></script> <script id="sample" type="text/example" charset="utf-8"> var tree; $(document).ready(function(){ google.earth.createInstance('map3d', init, failure); }); function init(ge) { ge.getWindow().setVisibility(true); var gex = gex = new GEarthExtensions(ge); tree = kmltree({ url: './kml/youtube_panoramio.kmz', gex: gex, element: $('#tree'), mapElement: $('#map3d'), setExtent: true, displayEnhancedContent: true, unknownIframeDimensionsDefault: function(kmlObject){ if(kmlObject.getUrl().match(/youtube/)){ // All youtube popups are around this size return {height: 335, width:335}; }else{ // Panoramio popups vary greatly, but this // dimension seems to work for many of them return {height: 455, width:535}; } } }); tree.load(); } function failure(errorCode) { alert('failed to load plugin'); } </script> </head> <body> <div class="content"> <p class="description"> This examples shows both Youtube and Panoramio kml layers using the <code>displayEnhancedContent</code> option. Because both these layers include dynamic description content that resets the window.location of the popup, <code>unkownIframeDimensionsDefault</code> must be specified. </p> <p> <em>Note, this demo may not work in versions of the plugin < 1.007.</em> It appears that Google may be providing different versions of the layer based on plugin version. If you have a prior version of the earth api installed, <code>displayEnhancedContent</code> will still work but not for this layer. Try <a href="displayEnhancedContent.html">this example</a> instead. </p> </div> </body> </html>
0corrina-kmltreeclone
examples/panoramio.html
HTML
bsd
3,129
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Combo KML Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script src="examples.js" type="text/javascript"></script> <script src="https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22earth%22%2C%22version%22%3A%221%22%7D%5D%7D&key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ" type="text/javascript" charset="utf-8"></script> <script id="sample" type="text/example" charset="utf-8"> var tree; $(document).ready(function(){ google.earth.createInstance('map3d', init, failure); }); function init(ge) { ge.getWindow().setVisibility(true); var gex = gex = new GEarthExtensions(ge); var tree = kmltree({ url: './kml/selection.kml', gex: gex, element: $('#tree'), mapElement: $('#map3d'), setExtent: true, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); tree.load(); $(tree).bind('select', function(e, selectData){ if(console && console.log){ console.log('select event', selectData); } }); $(tree).bind('context', function(e, selectData){ if(console && console.log){ console.log('context event', selectData); } }); } function failure(errorCode) { alert('failed to load plugin'); } </script> </head> <body> <div class="content"> <p class="description"> This example shows selection support via the <code>selectable</code> option in combination with the <code>multipleSelect</code> option. Try using the command/control and shift keys to select multiple features from the tree. Also, notice how selecting features from the map that are within contracted Folders or NetworkLinks show "breadcrumb" indicators on their first visible parent. </p> <p> If your browser supports the <code>console.log</code> function, you can see the <code>code</code> and <code>context</code> events firing. </p> </div> </body> </html>
0corrina-kmltreeclone
examples/selection.html
HTML
bsd
2,964
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>displayEnhancedContent option</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script src="examples.js" type="text/javascript"></script> <script src="https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22earth%22%2C%22version%22%3A%221%22%7D%5D%7D&key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ" type="text/javascript" charset="utf-8"></script> <script id="sample" type="text/example" charset="utf-8"> var tree; $(document).ready(function(){ google.earth.createInstance('map3d', init, failure); }); function init(ge) { ge.getWindow().setVisibility(true); var gex = gex = new GEarthExtensions(ge); var tree = kmltree({ url: 'http://www.tnccmaps.org/kml/estuary_info.kml', gex: gex, element: $('#tree'), mapElement: $('#map3d'), setExtent: true, displayEnhancedContent: true }); tree.load(); } function failure(errorCode) { alert('failed to load plugin'); } </script> </head> <body> <div class="content"> <p class="description"> displayEnhancedContent option enabled. Will open popup balloons with full js/css/html capabilities within an iframe sandbox. </p> </div> </body> </html>
0corrina-kmltreeclone
examples/displayEnhancedContent.html
HTML
bsd
1,839
<h1>kmltree examples</h1> <ul> <li><a href="comboExample.html">combo example</a></li> <li><a href="refresh.html">load / refresh any kml file</a></li> <li><a href="includedLayers.html">managing included Google Earth layers and options like 3d terrain</a></li> <li><a href="panoramio.html">Youtube and Panoramio Layers</a></li> <li><a href="selection.html">Selection, click, and context events</a></li> </ul>
0corrina-kmltreeclone
examples/index.html
HTML
bsd
430
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Managing Included Layers (Street View, Borders, etc...)</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script src="examples.js" type="text/javascript"></script> <script src="https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22earth%22%2C%22version%22%3A%221%22%7D%5D%7D&key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ" type="text/javascript" charset="utf-8"></script> <script id="sample" type="text/example" charset="utf-8"> var tree; $(document).ready(function(){ google.earth.createInstance('map3d', init, failure); }); function init(ge) { ge.getWindow().setVisibility(true); var gex = gex = new GEarthExtensions(ge); var layers = kmltree({ url: './kml/includedLayers.kml', gex: gex, element: $('#tree'), mapElement: $('#map3d'), setExtent: true, supportItemIcon: true, restoreState: true }); layers.load(); var options = kmltree({ url: './kml/displayOptions.kml', gex: gex, element: $('#tree2'), mapElement: $('#map3d'), setExtent: true, supportItemIcon: true, restoreState: true }); options.load(); enableGoogleLayersControl(layers, ge); enableGoogleLayersControl(options, ge); } function failure(errorCode) { alert('failed to load plugin'); } </script> </head> <body> <div class="content"> <p class="description"> This example shows how to control the visibility of the built-in Google layers like Roads and display options like Atmosphere and Street View. </p> </div> </body> </html>
0corrina-kmltreeclone
examples/includedLayers.html
HTML
bsd
2,494
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> <style type="text/css" media="screen"> html, body { margin:0; padding:0; font-size:0.9em; } .kmlTreeReset { font-family: sans-serif; color: black; } .kmlTreeReset h1 { font-size: 18px; } .kmlTreeReset h1 a { font-size: 18px; } .kmlTreeReset h2 { font-size: 16px; } .kmlTreeReset h2 a { font-size: 16px; } .kmlTreeReset h3 { font-size: 14px; } .kmlTreeReset h3 a { font-size: 14px; } .kmlTreeReset h1, .kmlTreeReset h2, .kmlTreeReset h3 { margin: 1em 0; } .kmlTreeReset h1, .kmlTreeReset h2, .kmlTreeReset h3, .kmlTreeReset h4, .kmlTreeReset h5, .kmlTreeReset h6, .kmlTreeReset strong, .kmlTreeReset dt { font-weight: bold; color: black; } .kmlTreeReset em { font-style: italic; } .kmlTreeReset blockquote, .kmlTreeReset ul, .kmlTreeReset ol, .kmlTreeReset dl { margin: 1em; } .kmlTreeReset ol, .kmlTreeReset ul, .kmlTreeReset dl { margin-left: 2em; } .kmlTreeReset ol li { list-style: decimal outside; } .kmlTreeReset ul li { list-style: disc outside; } .kmlTreeReset dl dd { margin-left: 1em; } .kmlTreeReset th, .kmlTreeReset td { padding: 0em; } .kmlTreeReset th { font-weight: bold; text-align: center; } .kmlTreeReset p, .kmlTreeReset fieldset, .kmlTreeReset table, .kmlTreeReset pre { margin-bottom: 1em; } .kmlTreeReset p, .kmlTreeReset div { font-size: 12px; color: black; } .kmlTreeReset a { font-size: 12px; color: blue; text-decoration: underline; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> /** * * Base64 encode / decode * http://www.webtoolkit.info/ * **/ var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(b){var d="",c,a,f,g,h,e,i=0;for(b=Base64._utf8_encode(b);i<b.length;){c=b.charCodeAt(i++);a=b.charCodeAt(i++);f=b.charCodeAt(i++);g=c>>2;c=(c&3)<<4|a>>4;h=(a&15)<<2|f>>6;e=f&63;if(isNaN(a))h=e=64;else if(isNaN(f))e=64;d=d+this._keyStr.charAt(g)+this._keyStr.charAt(c)+this._keyStr.charAt(h)+this._keyStr.charAt(e)}return d},decode:function(b){var d="",c,a,f,g,h,e=0;for(b=b.replace(/[^A-Za-z0-9\+\/\=]/g, "");e<b.length;){c=this._keyStr.indexOf(b.charAt(e++));a=this._keyStr.indexOf(b.charAt(e++));g=this._keyStr.indexOf(b.charAt(e++));h=this._keyStr.indexOf(b.charAt(e++));c=c<<2|a>>4;a=(a&15)<<4|g>>2;f=(g&3)<<6|h;d+=String.fromCharCode(c);if(g!=64)d+=String.fromCharCode(a);if(h!=64)d+=String.fromCharCode(f)}return d=Base64._utf8_decode(d)},_utf8_encode:function(b){b=b.replace(/\r\n/g,"\n");for(var d="",c=0;c<b.length;c++){var a=b.charCodeAt(c);if(a<128)d+=String.fromCharCode(a);else{if(a>127&&a<2048)d+= String.fromCharCode(a>>6|192);else{d+=String.fromCharCode(a>>12|224);d+=String.fromCharCode(a>>6&63|128)}d+=String.fromCharCode(a&63|128)}}return d},_utf8_decode:function(b){for(var d="",c=0,a=c1=c2=0;c<b.length;){a=b.charCodeAt(c);if(a<128){d+=String.fromCharCode(a);c++}else if(a>191&&a<224){c2=b.charCodeAt(c+1);d+=String.fromCharCode((a&31)<<6|c2&63);c+=2}else{c2=b.charCodeAt(c+1);c3=b.charCodeAt(c+2);d+=String.fromCharCode((a&15)<<12|(c2&63)<<6|c3&63);c+=3}}return d}}; // unencode and display requested content $(window).bind("message", function(e){ var e = e.originalEvent; if(e.source !== parent){return;}; var msg = JSON.parse(e.data); var html = Base64.decode(msg.html); var callback = Base64.decode(msg.callback); eval('var callback = '+callback); // Check whether the balloon immediately sets a new location, // like the panoramio layer. var match = html.match(/window.location[.href]*\s*=\s*/); if(match){ // If so, grab that content and display it. parent.postMessage( JSON.stringify({unknownIframeDimensions: true}), "*"); $(document.body).append(html); }else{ var doc = $(html); // jQuery doesn't execute inline scripts after remote // scripts are loaded reliably when using the append // method, so here I'm loading them manually. var inlineScripts = []; var remoteScripts = false; var waiting = 0; var done = function(){ waiting--; if(waiting <= 0){ $.each(inlineScripts, function(i, elem){ jQuery.globalEval(elem.text || elem.textContent || elem.innerHTML || "" ); }); // Needed for Firefox to execute callbacks after // scripts are Eval'd. Not sure why setTimeout(function(){ callback(); }, 1) } } // Get all script tags doc.each(function(i, v){ if($.nodeName(this, 'script')){ if(!this.type || this.type.toLowerCase() === "text/javascript"){ // If of type text/javascript and has src, add // to a queue to fetch if(!this.src){ inlineScripts.push(this); }else{ // otherwise wait to run inline scripts until // remote scripts are fetched. remoteScripts = true; waiting++; $.ajax({ cache: true, url: this.src, dataType: 'script', success: done, error: done }); } doc.splice(i, 1); } } }); // Don't forget there might be only inline scripts! if(!remoteScripts){ done(); } if(doc.find('body').length){ doc = doc.find('body').children(); } $(document.body).append(doc); parentResize(); handleContent(); } }); function parentResize(){ var height = $(document.body).height() + 30; var width = $(document.body).width() + 23; parent.postMessage( JSON.stringify({height: height, width:width}), '*'); } function handleContent(){ // Link click handling $('a').each(function(){ if(!this.target){ this.target = '_blank'; } }); } </script> </head> <body class="kmlTreeReset"> </body> </html>
0corrina-kmltreeclone
src/iframe.html
HTML
bsd
8,614
// src/kmltree.js // I don't like documentation being in more than one place, and I couldn't // find any javascript documentation tools that I found satisfactory. So, // docs can be found on the project page and should be kept up to date there: // http://code.google.com/p/kmltree/wiki/ApiReference var kmltree = (function(){ // can be removed when the following ticket is resolved: // http://code.google.com/p/earth-api-samples/issues/detail?id=290 function qualifyURL(url) { var a = document.createElement('a'); a.href = url; return a.href; } var NetworkLinkQueue = function(opts){ if(opts['success'] && opts['error'] && opts['tree']){ this.queue = []; this.opts = opts; }else{ throw('missing required option'); } }; NetworkLinkQueue.prototype.add = function(node, callback){ this.queue.push({ node: node, callback: callback, loaded: false, errors: false }); }; NetworkLinkQueue.prototype.execute = function(){ if(this.queue.length === 0){ this.opts['success']([]); }else{ for(var i=0;i<this.queue.length;i++){ var item = this.queue[i]; item.node.data('queueItem', item); if(!item.loaded && !item.loading){ var self = this; $(item.node).bind('loaded', function(e, node, kmlObject){ self.nodeLoadedCallback(e, node, kmlObject) }); // This handler could be a bit smarter? $(item.node).bind('error', function(e, node, kmlObject){ self.nodeLoadedCallback(e, node, kmlObject) }); this.opts['tree'].openNetworkLink(item.node); item.loading = true; } } } }; NetworkLinkQueue.prototype.nodeLoadedCallback = function(e, node, kmlObj){ var item = node.data('queueItem'); if(item.loaded === true){ throw('event listener fired twice for ' + node.find('>span.name').text()); } item.loaded = true; item.loading = false; $(node).unbind('loaded'); item.callback(node); this.execute(); this.finish(item); }; NetworkLinkQueue.prototype.finish = function(item){ var done = true; var noerrors = true; for(var i=0;i<this.queue.length;i++){ done = (done && this.queue[i].loaded); noerrors = (noerrors && !this.queue[i].errors); } if(done){ if(noerrors){ this.opts['success'](this.queue); this.destroy(); }else{ this.opts['error'](this.queue); this.destroy(); } } }; NetworkLinkQueue.prototype.destroy = function(){ for(var i=0;i<this.queue.length;i++){ var item = this.queue[i]; item.node.unbind('load'); } this.queue = []; }; // Returns a jquery object representing a kml file var template = tmpl([ '<li UNSELECTABLE="on" id="<%= id %>" class="kmltree-item ', '<%= listItemType %> ', '<%= type %> ', '<%= classname %> ', '<%= (visible ? "visible " : "") %>', '<%= (customIcon ? "hasIcon " : "") %>', '<%= (alwaysRenderNodes ? "alwaysRenderNodes " : "") %>', '<%= (select ? "select " : "") %>', '<%= (open ? "open " : "") %>', '<%= (description ? "hasDescription " : "") %>', '<%= (snippet ? "hasSnippet " : "") %>', '<%= (customIcon ? "customIcon " : "") %>', '<% if(kmlId){ %>', '<%= kmlId %> ', '<% } %>', '<% if(geoType){ %>', '<%= geoType %>', '<% } %>', '"', '<% if(kmlId){ %>', ' data-id="<%= kmlId %>"', '<% } %>', '>', '<div UNSELECTABLE="on" class="expander">&nbsp;</div>', '<div UNSELECTABLE="on" class="toggler">&nbsp;</div>', '<div ', '<% if(customIcon){ %>', 'style="background:url(<%= customIcon %>); -moz-background-size:16px 16px; -webkit-background-size:16px 16px;"', '<% } %>', 'class="icon">', '<% if(type === "KmlNetworkLink"){ %>', '<div class="nlSpinner">&nbsp;</div>', '<% } %>', '&nbsp;', '</div>', '<span UNSELECTABLE="on" class="name"><%= name %></span>', '<% if(snippet){ %>', '<p UNSELECTABLE="on" class="snippet"><%= snippet %></p>', '<% } %>', '<% if(children.length) { %>', '<ul><%= renderOptions(children) %></ul>', '<% } %>', '</li>' ].join('')); var constructor_defaults = { refreshWithState: true, bustCache: false, restoreState: false, whitelist: [], supportItemIcon: false, loadingMsg: 'Loading data', setExtent: false, displayDocumentRoot: 'auto', displayEnhancedContent: false, iframeSandbox: 'http://kmltree.googlecode.com/hg/src/iframe.html', unknownIframeDimensionsDefault: {height: 450, width:530}, sandboxedBalloonCallback: function(){}, selectable: function(kmlObject){return false;}, multipleSelect: false, classname: function(kmlObject){return ''} }; return function(opts){ var that = {}; var errorCount = 0; var lookupTable = {}; that.lookupTable = lookupTable; that.kmlObject = null; var docs = []; var opts = jQuery.extend({}, constructor_defaults, opts); var ge = opts.gex.pluginInstance; var destroyed = false; var internalState = {}; var selectData = []; that.url = opts.url; function clearSelectData(){ selectData = []; } function indexOfSelectData(node, kmlObject){ for(var i=0;i<selectData.length;i++){ if($(selectData[i]['node'])[0] === $(node)[0]){ return i; } } return -1; }; function addSelectData(node, kmlObject){ var index = indexOfSelectData(node, kmlObject); if(index === -1){ selectData.push({'node': node, 'kmlObject': kmlObject}); } } function removeSelectData(node, kmlObject){ var index = indexOfSelectData(node, kmlObject); if(index === -1){ throw('removeSelectData error'); }else{ selectData.splice(index, 1); } } if(parseFloat(ge.getApiVersion()) < 1.005){ alert('kmltree requires a google earth plugin version >= 1.005'); } if(!opts.url || !opts.gex || !opts.element || !opts.mapElement){ throw('kmltree requires options url, gex, mapElement & element'); } opts.element = $(opts.element); if(!opts.element.attr('id')){ opts.element.attr('id', 'kml-tree'+(new Date()).getTime()); opts.element.attr('UNSELECTABLE', "on"); } if(opts.restoreState){ $(window).unload(function(){ that.destroy(); }); } if(opts.element.css('position') !== 'absolute'){ $(opts.element).css({position: 'relative'}); } // check for background-size support var div = $(['<div class="kmltree" style="', 'background-size: 16px 16px; ', '-moz-background-size: 16px 16px; ', '-o-background-size: 16px 16px; ', '-webkit-background-size: 16px 16px; ', '-khtml-background-size: 16px 16px;"></div>'].join('')); var supportsBgSize = (div[0].style.backgroundSize !== undefined || div[0].style.MozBackgroundSize !== undefined || div[0].style.oBackgroundSize !== undefined || div[0].style.khtmlBackgroundSize !== undefined || div[0].style.webkitBackgroundSize !== undefined); var buildOptions = function(kmlObject, docUrl, extra_scope){ var options = {name: kmlObject.getName(), id: 'kml' + (extra_scope ? extra_scope.replace(/\W/g, '-') : '') + docUrl.replace(/\W/g, '-')}; google.earth.executeBatch(ge, function(){ opts.gex.dom.walk({ visitCallback: function(context){ var parent = context.current; if(!parent.children){ parent.children = []; } var name = this.getName(); var id = addLookup(this, parent.id, docUrl, name); var snippet = this.getSnippet(); // To support generated output from certain software // (Arc2Earth, etc) if(!snippet || snippet === 'empty'){ snippet = false; } var type = this.getType(); var geotype = false; if(type === 'KmlPlacemark'){ var geo = this.getGeometry(); if(geo){ geotype = geo.getType(); } } var style = this.getComputedStyle(); var selectable = opts.selectable; if(typeof selectable === 'function'){ selectable = selectable(this); } selectable = selectable && this.getId(); var child = { renderOptions: renderOptions, name: name || '&nbsp;', visible: !!this.getVisibility(), type: type, open: this.getOpen(), id: id, description: this.getDescription(), snippet: snippet, select: selectable, listItemType: getListItemType(style), customIcon: customIcon(this), classname: opts.classname(this), children: [], alwaysRenderNodes: false, kmlId: this.getId().replace(/\W/g, '-'), geoType: geotype } parent.children.push(child); if(child.listItemType !== 'checkHideChildren'){ context.child = child; }else{ context.walkChildren = false; } }, rootObject: kmlObject, rootContext: options }); }); return options; }; var load = function(cachebust){ if(that.kmlObject){ throw('KML already loaded'); } showLoading(); var url = qualifyURL(opts.url); if(cachebust || opts.bustCache){ var buster = (new Date()).getTime(); if(url.indexOf('?') === -1){ url = url + '?cachebuster=' + buster; }else{ url = url + '&cachebuster=' + buster; } } google.earth.fetchKml(ge, url, function(kmlObject){ if(!destroyed){ processKmlObject(kmlObject, url, opts.url); } }); }; that.load = load; var refresh = function(){ if(opts.refreshWithState){ that.previousState = getState(); } clearKmlObjects(); clearLookups(); // opts.element.html(''); ge.setBalloon(null); load(true); }; that.refresh = refresh; // returns all nodes that represent a kmlObject with a matching ID var getNodesById = function(id){ return opts.element.find('.'+id.replace(/\W/g, '-')); }; that.getNodesById = getNodesById; var expandParentsOf = function(node){ node = $(node); var parent = node.parent().parent(); while(!parent.hasClass('kmltree') && !parent.find('>ul:visible').length){ parent.addClass('open'); var parent = parent.parent().parent(); } }; that.expandParentsOf = expandParentsOf; // Selects the first node found matching the ID var selectById = function(id, kmlObject, silent){ var nodes = getNodesById(id); if(nodes.length){ var node = $(nodes[0]); clearSelection(true, true); selectNode(node, kmlObject || lookup(node), silent); return true; }else{ // couldn't find feature in list. Might be in unexpanded // networklink // highlight parent networklink if feature isn't shown in // the tree yet var node = getFirstRenderedParentNetworkLink(kmlObject); if(node){ node = $(node); if(node.is(':visible')){ clearSelection(true, true); node.addClass('kmltree-breadcrumb'); if(!silent){ triggerSelect(node, kmlObject); } return true; }else{ setExpanderBreadcrumbs(node); // var parent = firstVisibleParentOf(node); node.addClass('kmltree-breadcrumb'); // setModified maybe someday if(!silent){ triggerSelect(parent, kmlObject); } } }else{ clearSelection(); return false; } } }; that.selectById = selectById; var getParentNetworkLink = function(kmlObject){ var parent = kmlObject.getParentNode(); switch(parent.getType()){ case 'KmlNetworkLink': return parent; break; case 'GEGlobe': return false; break; default: return getParentNetworkLink(parent); } }; var getFirstRenderedParentNetworkLink = function(kmlObject, loadedNl){ var treeid = opts.element.attr('id'); if(!loadedNl){ var loadedNl = []; $('#'+treeid+' li.KmlNetworkLink').each(function(){ if(!$(this).hasClass('loaded')){ loadedNl.push([this, lookup(this)]); } }); } var nL = getParentNetworkLink(kmlObject); if(nL === false){ // walked all the way up to GEGlobe, couldn't find it. return false; }else{ // if nL has an ID, look for that // look at all networklinks in tree that aren't expanded var url = nL.getLink().getHref(); for(var i=0;i<loadedNl.length;i++){ var loadedHref = loadedNl[i][1].getLink().getHref(); var nLHref = nL.getLink().getHref() if(nLHref === loadedHref){ return loadedNl[i][0]; } } // if none match, keep moving up until hitting ge globe return getFirstRenderedParentNetworkLink(nL, loadedNl); } }; var selectNode = function(node, kmlObject, silent){ if(!kmlObject){ kmlObject = lookup(node); } node = $(node); var visible = $(node).is(':visible'); // need to make this actually work toggleVisibility(node, true); node.addClass('kmltree-selected'); setModified(node, 'selected', true); if(!visible){ setExpanderBreadcrumbs(node); } if(!silent){ kmltreeManager._clearEverythingButMe(that); triggerSelect(node, kmlObject); }else{ addSelectData(node, kmlObject); } }; that.selectNode = selectNode; var selectNodes = function(nodes, silent){ var last = nodes.length - 1; nodes.each(function(i){ selectNode(this, null, !!silent || (!silent && i !== nodes.length - 1)); }); }; that.selectNodes = selectNodes; var deselectNodes = function(nodes, silent){ nodes.each(function(i){ deselectNode(this, null, !!silent || (!silent && i !== nodes.length - 1)); }); }; that.deselectNodes = deselectNodes; var deselectNode = function(node, kmlObject, silent){ if(!kmlObject){ kmlObject = lookup(node); } node = $(node); // var visible = $(node).is(':visible'); node.removeClass('kmltree-selected'); setModified(node, 'selected', false); // if(!visible){ // setExpanderBreadcrumbs(node); // } if(!silent){ removeAndTrigger(node, kmlObject); }else{ removeSelectData(node, kmlObject); } }; var triggerSelect = function(node, kmlObject){ if(node && kmlObject){ addSelectData(node, kmlObject); }else{ clearSelectData(); } setTimeout(function(){ $(that).trigger('select', [selectData]); }, 1); }; var removeAndTrigger = function(node, kmlObject){ removeSelectData(node, kmlObject); setTimeout(function(){ $(that).trigger('select', [selectData]); }, 1); } var setExpanderBreadcrumbs = function(node){ var node = $(node); var parent = node.parent().parent(); parent.addClass('kmltree-breadcrumb'); if(!parent.is(':visible')){ return setExpanderBreadcrumbs(parent); }else{ return parent; } }; var clearSelection = function(keepBalloons, dontTriggerEvent){ clearSelectData(); var treeEl = $('#'+opts.element.attr('id')); var prev = treeEl .find('.kmltree-selected').removeClass('kmltree-selected'); treeEl.find('.kmltree-breadcrumb') .removeClass('kmltree-breadcrumb'); treeEl.find('.kmltree-cursor-1').removeClass('kmltree-cursor-1'); treeEl.find('.kmltree-cursor-2').removeClass('kmltree-cursor-2'); if(prev.length){ prev.each(function(){ setModified($(this), 'selected', false); }); } if(!dontTriggerEvent){ triggerSelect(null, null); } var balloon = ge.getBalloon(); if(balloon && !keepBalloons){ ge.setBalloon(null); } } // Don't give external callers access to the keepBalloons and // dontTriggerEvent arguments that.clearSelection = function(){ return clearSelection(); }; var showLoading = function(msg){ hideLoading(); var msg = msg || opts.loadingMsg; var h = $('<div class="kmltree-loading"><span>' + msg + '</span></div>'); var height = opts.element.height(); if(height !== 0){ h.height(height); }else{ // h.height(200); } opts.element.append(h); }; that.showLoading = showLoading; var hideLoading = function(){ opts.element.find('.kmltree-loading').remove(); }; that.hideLoading = hideLoading; // url has cachebusting GET vars, original_url does not var processKmlObject = function(kmlObject, url, original_url){ internalState = {}; if (!kmlObject) { if(errorCount === 0){ errorCount++; setTimeout(function(){ // Try to reset the browser cache, then try again jQuery.ajax({ url: url, success: function(){ that.load(true); }, error: function(){ processKmlObject( kmlObject, url, original_url); } }); // try to load }, 100); return; }else{ // show error setTimeout(function() { opts.element.html([ '<div class="kmltree">', '<h4 class="kmltree-title">', 'Error Loading', '</h4>', '<p class="error">', 'could not load kml file. Try clicking ', '<a target="_blank" href="', url, '">', 'this link', '</a>', ', then refreshing the application.', '<p>', '</div>' ].join('')); $(that).trigger('kmlLoadError', [kmlObject]); }, 0); return; } } errorCount = 0; that.kmlObject = kmlObject; docs.push(kmlObject); that.kmlObject.setVisibility(true); var options = buildOptions(kmlObject, original_url); var root; if(opts.displayDocumentRoot === false){ root = options.children[0].children; }else if(opts.displayDocumentRoot === true){ root = options.children[0]; }else{ // opts.displayDocumentRoot === 'auto' var children = options.children[0].children; var i = 0; var placemarks = false; while(i < children.length && placemarks === false){ placemarks = children[i].type === 'KmlPlacemark'; i++; } if(placemarks){ root = options.children[0]; }else{ root = options.children[0].children; } } var rendered = renderOptions(root); opts.element.find('div.kmltree').remove(); opts.element.find('.kmltree-loading').before([ '<div UNSELECTABLE="on" class="kmltree">', '<h4 UNSELECTABLE="on" class="kmltree-title">', options.children[0].name, '</h4>', '<ul UNSELECTABLE="on" class="kmltree">', rendered, '</ul>', '</div>' ].join('')); ge.getFeatures().appendChild(kmlObject); if(!that.previousState){ if(opts.restoreState && !!window.localStorage){ that.previousState = getStateFromLocalStorage(); } } var queue = new NetworkLinkQueue({ success: function(links){ hideLoading(); if(opts.setExtent){ var aspectRatio = null; var m = $(opts.mapElement); if(m.length){ var aspectRatio = m.width() / m.height(); } opts.gex.util.flyToObject(kmlObject, { boundsFallback: true, aspectRatio: aspectRatio }); opts.setExtent = false; } $(that).trigger('kmlLoaded', [kmlObject]); }, error: function(links){ hideLoading(); $(that).trigger('kmlLoadError', [kmlObject]); }, tree: that }); if(that.previousState){ restoreState(that.previousState, queue); }else{ queueOpenNetworkLinks(queue, $('#' + opts.element.attr('id'))); } }; var restoreState = function(state, queue){ // go thru the whole state, opening, changing visibility, // and selecting for(var id in state){ var el = $('#'+id); if(el.length === 1){ for(var key in state[id]){ el.toggleClass(key, state[id][key]['value']); setModified(el, key, state[id][key]['value']); if(key === 'visible'){ lookup(el).setVisibility(state[id][key]['value']); } } delete state[id]; } } var links = $('#' + opts.element.attr('id')).find( 'li.KmlNetworkLink.open'); links.each(function(){ var n = $(this); // no need to open if checkHideChildren is set if(!n.hasClass('checkHideChildren') && !n.hasClass('loading') && !n.hasClass('loaded') && !n.hasClass('error')){ queue.add(n, function(loadedNode){ restoreState(state, queue); }); } }); queue.execute(); } var queueOpenNetworkLinks = function(queue, topNode){ var links = topNode.find('li.KmlNetworkLink.open'); links.each(function(){ var n = $(this); // no need to open if checkHideChildren is set if(!n.hasClass('checkHideChildren') && !n.hasClass('loading') && !n.hasClass('loaded')){ n.removeClass('open'); queue.add(n, function(loadedNode){ loadedNode.addClass('open'); setModified(loadedNode, 'open', n.hasClass('open')); queueOpenNetworkLinks(queue, loadedNode); }); } }); queue.execute(); }; var customIcon = function(kmlObject){ var result = false; if(supportsBgSize && kmlObject.getType() === 'KmlPlacemark' && kmlObject.getGeometry() && kmlObject.getGeometry().getType() === 'KmlPoint'){ result = kmlObject.getComputedStyle().getIconStyle() .getIcon().getHref(); } if(!opts.supportItemIcon){ return result; } var doc = kmldom(kmlObject.getKml()); var root = doc.find('kml>Folder, kml>Document, kml>Placemark, ' + 'kml>NetworkLink'); var href = root.find('>Style>ListStyle>ItemIcon>href').text(); if(href){ return href; }else{ return false; } } // See http://code.google.com/apis/kml/documentation/kmlreference.html#listItemType var getListItemType = function(style){ var listItemType = 'check'; var lstyle = style.getListStyle(); if(lstyle){ var ltype = lstyle.getListItemType(); switch(ltype){ case 0: // 'check' break; case 5: listItemType = 'radioFolder'; break; case 2: listItemType = 'checkOffOnly'; break; case 3: listItemType = 'checkHideChildren'; break; } } return listItemType; }; var renderOptions = function(options){ if(jQuery.isArray(options)){ var strings = []; for(var i=0;i<options.length;i++){ strings.push(_render(options[i])); } return strings.join(''); }else{ var string = _render(options); return string; } }; var defaults = { renderOptions: renderOptions }; var _render = function(options){ var s = template(jQuery.extend({}, defaults, options)); return s; }; var clearLookups = function(){ // try to clear some memory lookupTable = null; lookupTable = {}; }; // Deletes references to networklink kmlObjects, removes them from the // dom. Prepares for refresh or tree destruction. var clearNetworkLinks = function(){ $('.KmlNetworkLink').each(function(){ var kmlObject = lookup($(this)); if(kmlObject && kmlObject.getParentNode()){ opts.gex.dom.removeObject(lookup($(this))); } }); }; var clearKmlObjects = function(){ clearNetworkLinks(); if(that.kmlObject && that.kmlObject.getParentNode()){ opts.gex.dom.removeObject(that.kmlObject); // that.kmlObject.release(); } that.kmlObject = null; docs = []; }; var getStateFromLocalStorage = function(){ var json = localStorage.getItem( 'kmltree-('+opts.url+')'); if(json){ return JSON.parse(json); }else{ return false; } }; var setStateInLocalStorage = function(){ var state = JSON.stringify(getState()); localStorage.setItem('kmltree-('+opts.url+')', state); }; var destroy = function(){ destroyed = true; kmltreeManager.remove(that); if(opts.restoreState && !!window.localStorage){ setStateInLocalStorage(); } clearKmlObjects(); clearLookups(); var b = ge.getBalloon(); if(b){ var f = b.getFeature(); if(f){ var owner = kmltreeManager.getOwner(f); if(owner && owner.instance === that){ ge.setBalloon(null); } } } ge.setBalloon(null); var id = opts.element.attr('id'); $('#'+id+' li > span.name').die(); $('#'+id+' li').die(); $('#'+id+' li > .expander').die(); $(that).die(); $(that).unbind(); $('#kmltree-balloon-iframe').remove(); opts.element.html(''); }; that.destroy = destroy; var lookup = function(li){ var li = $(li); if(li.length){ return lookupTable[li.attr('id')]; }else{ return false; } }; that.lookup = lookup; var addLookup = function(kmlObject, parentID, docUrl, name){ var id = getID(kmlObject, parentID, docUrl, name); // if the ID exists already, just append the position of the // repeated name to the id. var tries = 0; while(!!lookupTable[id]){ tries++; id = id + tries; } lookupTable[id] = kmlObject; return id; }; // Returns an ID that is used on the DOM element representing this // kmlObject. If the kmlObject has it's own ID, the generated ID will // be created from that ID + the kml document's url. If not, the name // of the element and the name of it's parents will be used to // generate an ID. // // Arguments: kmlObject, parentID var getID = function(kmlObject, parentID, docUrl, name, ignoreID){ if(name){ key = name.replace(/\W/g, '-'); }else{ key = "blank" } return parentID + key; }; var setLookup = function(node, kmlObject){ lookupTable[node.attr('id')] = kmlObject; }; var toggleDown = function(node, toggling){ if(toggling){ if(node.hasClass('checkOffOnly')){ return; }else{ if(node.hasClass('radioFolder')){ if(node.find('>ul>li.visible').length){ // one node already turned on, do nothing return; }else{ var children = node.find('>ul>li'); if(children.length){ toggleItem($(children[0]), true); toggleDown($(children[0]), true); }else{ return; } } }else{ node.find('>ul>li').each(function(){ var n = $(this); if(!n.hasClass('checkOffOnly')){ toggleItem(n, true); toggleDown(n, true); } }); } } }else{ node.find('li').each(function(){ toggleItem($(this), false); }); } }; var toggleUp = function(node, toggling, from){ var parent = node.parent().parent(); if(!parent.hasClass('kmltree')){ if(toggling){ var herParent = parent.parent().parent(); if(herParent.hasClass('radioFolder')){ // toggle off any siblings and toggle them down herParent.find('>ul>li.visible').each(function(){ if(this !== parent[0]){ var sib = $(this); toggleItem(sib, false); toggleDown(sib, false); }else{ } }); } if(!parent.hasClass('visible')){ toggleItem(parent, true); toggleUp(parent, true); } }else{ if(parent.find('>ul>li.visible').length === 0){ toggleItem(parent, false); toggleUp(parent, false); } } } }; var toggleVisibility = function(node, toggle){ if(node.hasClass('checkOffOnly') && toggle){ return; } var parent = node.parent().parent(); if(parent.hasClass('radioFolder')){ parent.find('>ul>li.visible').each(function(){ toggleItem($(this), false); toggleDown($(this), false); }); } toggleItem(node, toggle); if(toggle && node.find('li.visible').length){ // if children are already toggled, do nothing }else{ toggleDown(node, toggle); } toggleUp(node, toggle); }; var toggleItem = function(node, toggling){ var node = $(node); if(node.hasClass('visible') === toggling){ return; } setModified(node, 'visible', toggling); lookup(node).setVisibility(toggling); node.toggleClass('visible', toggling); }; var setModified = function(node, key, value){ var id = node.attr('id'); if(!internalState[id]){ internalState[id] = {}; } var record = internalState[id]; if(!record[key]){ record[key] = {original: !value, value: value} }else{ record[key]['value'] = value; } }; var getState = function(){ for(var id in internalState){ for(var key in internalState[id]){ if(internalState[id][key]['original'] === internalState[id][key]['value']){ delete internalState[id][key]; } } var len = 0; for(var key in internalState[id]){ if(internalState[id].hasOwnProperty(key)){ len++; } } if(len === 0){ delete internalState[id]; } } return internalState; }; that.getState = getState; var openNetworkLink = function(node){ if(node.find('> ul').length){ throw('networklink already loaded'); }else{ var NetworkLink = lookup(node); var link = NetworkLink.getLink(); if(link){ link = link.getHref(); var original_url = link; }else{ var dom = kmldom(NetworkLink.getKml()); var href = dom.find('Url>href'); if(href.length){ var link = href.text(); var original_url = link; }else{ node.addClass('error'); // setModified(node, 'visibility', false); $(node).trigger('loaded', [node, false]); node.removeClass('open'); setModified(node, 'open', false); return; } } var uri = new URI(link); if(uri.getAuthority() === null){ var doc = NetworkLink.getOwnerDocument(); if(doc && doc.getUrl()){ var base = doc.getUrl(); if(base){ var base = new URI(base); var new_url = uri.resolve(base); } } if(!new_url){ alert(['Could not resolve relative link in kml ', 'document. You may need to upgrade to the ', 'latest Google Earth Plugin.'].join()); }else{ link = new_url.toString(); } } if(opts.bustCache){ var buster = (new Date()).getTime(); if(link.indexOf('?') === -1){ link = link + '?cachebuster=' + buster; }else{ link = link + '&cachebuster=' + buster; } } node.addClass('loading'); google.earth.fetchKml(ge, link, function(kmlObject){ if(!kmlObject){ alert('Error loading ' + link); node.addClass('error'); // setModified(node, 'visibility', false); $(that).trigger('kmlLoadError', [kmlObject]); $(node).trigger('error', [node, kmlObject]); node.removeClass('loading'); node.removeClass('open'); return; } ge.getFeatures().appendChild(kmlObject); kmlObject.setVisibility(NetworkLink.getVisibility()); var extra_scope = NetworkLink.getName(); var parent = NetworkLink.getParentNode(); parent.getFeatures().removeChild(NetworkLink); var data = buildOptions(kmlObject, original_url, extra_scope); var html = renderOptions(data.children[0].children); node.append('<ul>'+html+'</ul>'); node.addClass('open'); setModified(node, 'open', node.hasClass('open')); node.removeClass('loading'); node.addClass('loaded'); setLookup(node, kmlObject); docs.push(kmlObject); rememberNetworkLink(node, NetworkLink); $(node).trigger('loaded', [node, kmlObject]); $(that).trigger('networklinkload', [node, kmlObject, NetworkLink]); }); } }; that.openNetworkLink = openNetworkLink; var rememberedLinks = []; var rememberNetworkLink = function(node, networkLink){ $(node).attr( 'data-rememberedLink', rememberedLinks.length.toString()); $(node).data('original-networklink', networkLink); rememberedLinks.push(networkLink); }; var getNetworkLink = function(node){ var id = $(node).attr('data-rememberedLink'); if(id && rememberedLinks.length >= id){ return rememberedLinks[id]; }else{ return false; } }; that.getNetworkLink = getNetworkLink; // Creates a new NetworkLinkQueue that simply opens up the given // NetworkLink and any open NetworkLinks within it. var openNetworkLinkRecursive = function(node, callback){ var queue = new NetworkLinkQueue({ success: function(links){ if(callback){ callback(node, links); }; }, error: function(links){ }, tree: that }); queue.add(node, function(loadedNode){ loadedNode.addClass('open'); setModified(loadedNode, 'open', node.hasClass('open')); queueOpenNetworkLinks(queue, loadedNode); }); queue.execute(); } var id = opts.element.attr('id'); $('#'+id+' li > span.name').live('click', function(e){ e.stopPropagation(); var dontOpen = false; var node = $(this).parent(); var kmlObject = lookup(node); if(node.hasClass('error') && node.hasClass('KmlNetworkLink')){ if(kmlObject.getLink() && kmlObject.getLink().getHref()){ alert('Could not load NetworkLink with url ' + kmlObject.getLink().getHref()) }else{ alert('Could not load NetworkLink. Link tag with href not found'); } } if(node.hasClass('select')){ if(opts.multipleSelect && e.metaKey){ if(node.hasClass('kmltree-selected')){ $('.kmltree-cursor-1').removeClass('kmltree-cursor-1'); node.removeClass('kmltree-cursor-1'); deselectNode(node, kmlObject) }else{ $('.kmltree-cursor-1').removeClass('kmltree-cursor-1'); $('.kmltree-cursor-2').removeClass('kmltree-cursor-2'); node.addClass('kmltree-cursor-1'); selectNode(node, kmlObject); } kmltreeManager.pauseListeners(function(){ ge.setBalloon(null); }); dontOpen = true; }else if(opts.multipleSelect && e.shiftKey){ // if(node.hasClass('kmltree-selected') || node.hasClass('kmltree-breadcrumbs')){ // // do nothing // }else{ // make sure not shift+selecting something in a // different part of the tree (shift select only works // with siblings) var treeEl = $('#'+opts.element.attr('id')); selected = treeEl.find('.kmltree-selected'); if(selected.length === 1){ selected.addClass('kmltree-cursor-1'); } var cursor1 = treeEl.find('.kmltree-cursor-1'); if(cursor1.length === 0){ // just do a normal selection clearSelection(true, true); selectNode(node, kmlObject); }else{ var parent = node.parent().parent(); var first_cursor = treeEl.find('.kmltree-cursor-1'); if(first_cursor.parent().parent()[0] !== parent[0]){ // do nothing. can only shift-select siblings }else{ var cursor2 = treeEl.find('.kmltree-cursor-2'); if(cursor2.length){ var cursors = treeEl.find('.kmltree-cursor-1, .kmltree-cursor-2'); var first = cursors.first(); var last = cursors.last() var siblings = first.parent().parent().find('> ul > li'); // already have a range selected. Need to deselect var range = first.nextUntil('[id="'+last.attr('id')+'"]').andSelf().add(last); cursor2.removeClass('kmltree-cursor-2'); deselectNodes(range, true) } node.addClass('kmltree-cursor-2'); var cursors = treeEl.find('.kmltree-cursor-1, .kmltree-cursor-2'); var first = cursors.first(); var last = cursors.last(); var range; if(first[0] === last[0]){ // just one is selected range = first; treeEl.find('.kmltree-cursor-1, .kmltree-cursor-2').removeClass('kmltree-cursor-2').removeClass('kmltree-cursor-1'); }else{ var siblings = first.parent().parent().find('> ul > li'); var range = first.nextUntil('[id="'+last.attr('id')+'"]').andSelf().add(last); } selectNodes(range); kmltreeManager.pauseListeners(function(){ ge.setBalloon(null); }); } // if(selected.first) // get furthest selected sibling // deselect everything quickly // select range dontOpen = true; } }else{ clearSelection(true, true); selectNode(node, kmlObject); } }else{ clearSelection(); node.addClass('kmltree-cursor-1'); if(node.hasClass('hasDescription') || kmlObject.getType() === 'KmlPlacemark'){ if(kmlObject.getType() === 'KmlPlacemark'){ toggleVisibility(node, true); } } } if(!dontOpen){ if(kmlObject.getType() === 'KmlPlacemark' || kmlObject.getDescription()){ kmltreeManager.pauseListeners(function(){ kmltreeManager._openBalloon(kmlObject, that); }); } } $(that).trigger('click', [node[0], kmlObject]); }); $('#'+id+' li').live('contextmenu', function(e){ var node = $(this); if(node.hasClass('select')){ if(!node.hasClass('kmltree-selected')){ clearSelection(true, true); selectNode(node); } setTimeout(function(){ // Set timeout so that it fires after select event if // selecting new feature $(that).trigger('context', [selectData]); }, 2); } e.preventDefault(); return false; }); // Events to handle clearing selection opts.element.click(function(e){ var el = $(e.target); var fire = false; if(e.target === this){ fire = true; }else{ if(el.hasClass('toggle') && !el.hasClass('select')){ fire = true; } } if(el.find('.kmltree-selected').length || el.find('.kmltree-breadcrumb').length){ clearSelection(); } }); // expand events $('#'+id+' li > .expander').live('click', function(e){ var el = $(this).parent(); var closing = el.hasClass('open'); if(el.hasClass('KmlNetworkLink') && !el.hasClass('loaded') && !el.hasClass('loading')){ openNetworkLinkRecursive(el, function(node, links){ if(node.hasClass('kmltree-breadcrumb')){ if(closing){ if(el.find('.kmltree-selected').length){ el.addClass('kmltree-breadcrumb'); } }else{ el.removeClass('kmltree-breadcrumb'); } var kmlObject = ge.getBalloon().getFeature(); selectById(kmlObject.getId(), kmlObject, true); } }); }else{ el.toggleClass('open'); setModified(el, 'open', el.hasClass('open')); if(closing){ if(el.find('.kmltree-selected').length){ el.addClass('kmltree-breadcrumb'); } }else{ el.removeClass('kmltree-breadcrumb'); } } }); $('#'+id+' li > .toggler').live('click', function(){ var node = $(this).parent(); var toggle = !node.hasClass('visible'); if(!toggle && node.hasClass('kmltree-selected')){ clearSelection(); } if(!toggle && ge.getBalloon()){ ge.setBalloon(null); } if(node.hasClass('checkOffOnly') && toggle){ // do nothing. Should not be able to toggle-on from this node. return; }else{ if(node.hasClass('KmlNetworkLink') && node.hasClass('alwaysRenderNodes') && !node.hasClass('open') && !node.hasClass('loading') && !node.hasClass('loaded')){ openNetworkLinkRecursive(node); $(node).bind('loaded', function(e, node, kmlObject){ toggleVisibility(node, true); node.removeClass('open'); }); }else{ toggleVisibility(node, toggle); } $(that).trigger('toggleItem', [node, toggle, lookup(node)]); } }); $('#'+id+' li').live('dblclick', function(e){ e.stopPropagation(); var target = $(e.target); var parent = target.parent(); if(target.hasClass('expander') || target.hasClass('toggler') || parent.hasClass('expander') || parent.hasClass('toggler')){ // dblclicking the expander icon or checkbox should not zoom return; } var node = $(this); var kmlObject = lookup(node); if(node.hasClass('error')){ if(kmlObject.getLink() && kmlObject.getLink().getHref()){ alert('Could not load NetworkLink with url ' + kmlObject.getLink().getHref()) }else{ alert('Could not load NetworkLink. Link tag with href not found'); } return; } toggleVisibility(node, true); if(kmlObject.getType() == 'KmlTour'){ ge.getTourPlayer().setTour(kmlObject); }else{ var aspectRatio = null; var m = $(opts.mapElement); if(m.length){ var aspectRatio = m.width() / m.height(); } opts.gex.util.flyToObject(kmlObject, { boundsFallback: parent.find('li').length < 1000, aspectRatio: aspectRatio }); } $(that).trigger('dblclick', [node, kmlObject]); }); var doubleClicking = false; google.earth.addEventListener(ge.getGlobe(),'dblclick',function(e, d){ if(e.getButton() === -1){ // related to scrolling, ignore return; } var target = e.getTarget(); if(target.getType() === 'GEGlobe'){ // do nothing }else if(target.getType() === 'KmlPlacemark'){ var id = target.getId(); var nodes = getNodesById(id); if(nodes.length >= 1){ // e.preventDefault(); if(!doubleClicking){ doubleClicking = true; setTimeout(function(){ doubleClicking = false; var n = $(nodes[0]); $(that).trigger('dblclick', [n, target]); }, 200); } }else{ // do nothin } } }); // fix for jquery 1.4.2 compatibility. See http://forum.jquery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jquery-1-4-2 that.removeEventListener = that.detachEvent = function(){}; var privilegedApi = { opts: opts, docs: docs }; kmltreeManager.register(that, privilegedApi); that.docs = docs; return that; }; })();
0corrina-kmltreeclone
src/kmltree.js
JavaScript
bsd
58,638
// src/kmldom.js // returns a jquery object that wraps the kml dom kmldom = (function(){ return function(kml){ if( window.ActiveXObject && window.GetObject ) { var dom = new ActiveXObject( 'Microsoft.XMLDOM' ); dom.loadXML(kml); return jQuery(dom); } if( window.DOMParser ) { return jQuery(new DOMParser().parseFromString( kml, 'text/xml' )); } throw new Error( 'No XML parser available' ); } })();
0corrina-kmltreeclone
src/kmldom.js
JavaScript
bsd
503
/* * Copyright © 2007 Dominic Mitchell * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the Dominic Mitchell nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * An URI datatype. Based upon examples in RFC3986. * * TODO %-escaping * TODO split apart authority * TODO split apart query_string (on demand, anyway) * TODO handle parameters containing empty strings properly * TODO keyword escaping * * @(#) $Id$ */ // Globals we introduce. var URI; var URIQuery; // Introduce a new scope to define some private helper functions. (function () { //// HELPER FUNCTIONS ///// // RFC3986 §5.2.3 (Merge Paths) function merge(base, rel_path) { var dirname = /^(.*)\//; if (base.authority && !base.path) { return "/" + rel_path; } else { return base.getPath().match(dirname)[0] + rel_path; } } // Match two path segments, where the second is ".." and the first must // not be "..". var DoubleDot = /\/((?!\.\.\/)[^\/]*)\/\.\.\//; function remove_dot_segments(path) { if (!path) { return ""; } // Remove any single dots var newpath = path.replace(/\/\.\//g, '/'); // Remove any trailing single dots. newpath = newpath.replace(/\/\.$/, '/'); // Remove any double dots and the path previous. NB: We can't use // the "g", modifier because we are changing the string that we're // matching over. while (newpath.match(DoubleDot)) { newpath = newpath.replace(DoubleDot, '/'); } // Remove any trailing double dots. newpath = newpath.replace(/\/([^\/]*)\/\.\.$/, '/'); // If there are any remaining double dot bits, then they're wrong // and must be nuked. Again, we can't use the g modifier. while (newpath.match(/\/\.\.\//)) { newpath = newpath.replace(/\/\.\.\//, '/'); } return newpath; } // give me an ordered list of keys of this object function hashkeys(obj) { var list = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { list.push(key); } } return list.sort(); } // TODO: Make these do something function uriEscape(source) { return source; } function uriUnescape(source) { return source; } //// URI CLASS ///// // Constructor for the URI object. Parse a string into its components. // note that this 'exports' 'URI' to the 'global namespace' URI = function (str) { if (!str) { str = ""; } // Based on the regex in RFC2396 Appendix B. var parser = /^(?:([^:\/?\#]+):)?(?:\/\/([^\/?\#]*))?([^?\#]*)(?:\?([^\#]*))?(?:\#(.*))?/; var result = str.match(parser); // Keep the results in private variables. var scheme = result[1] || null; var authority = result[2] || null; var path = result[3] || null; var query = result[4] || null; var fragment = result[5] || null; // Set up accessors. this.getScheme = function () { return scheme; }; this.setScheme = function (newScheme) { scheme = newScheme; }; this.getAuthority = function () { return authority; }; this.setAuthority = function (newAuthority) { authority = newAuthority; }; this.getPath = function () { return path; }; this.setPath = function (newPath) { path = newPath; }; this.getQuery = function () { return query; }; this.setQuery = function (newQuery) { query = newQuery; }; this.getFragment = function () { return fragment; }; this.setFragment = function (newFragment) { fragment = newFragment; }; }; // Restore the URI to it's stringy glory. URI.prototype.toString = function () { var str = ""; if (this.getScheme()) { str += this.getScheme() + ":"; } if (this.getAuthority()) { str += "//" + this.getAuthority(); } if (this.getPath()) { str += this.getPath(); } if (this.getQuery()) { str += "?" + this.getQuery(); } if (this.getFragment()) { str += "#" + this.getFragment(); } return str; }; // RFC3986 §5.2.2. Transform References; URI.prototype.resolve = function (base) { var target = new URI(); if (this.getScheme()) { target.setScheme(this.getScheme()); target.setAuthority(this.getAuthority()); target.setPath(remove_dot_segments(this.getPath())); target.setQuery(this.getQuery()); } else { if (this.getAuthority()) { target.setAuthority(this.getAuthority()); target.setPath(remove_dot_segments(this.getPath())); target.setQuery(this.getQuery()); } else { // XXX Original spec says "if defined and empty"…; if (!this.getPath()) { target.setPath(base.getPath()); if (this.getQuery()) { target.setQuery(this.getQuery()); } else { target.setQuery(base.getQuery()); } } else { if (this.getPath().charAt(0) === '/') { target.setPath(remove_dot_segments(this.getPath())); } else { target.setPath(merge(base, this.getPath())); target.setPath(remove_dot_segments(target.getPath())); } target.setQuery(this.getQuery()); } target.setAuthority(base.getAuthority()); } target.setScheme(base.getScheme()); } target.setFragment(this.getFragment()); return target; }; URI.prototype.parseQuery = function () { return URIQuery.fromString(this.getQuery(), this.querySeparator); }; //// URIQuery CLASS ///// URIQuery = function () { this.params = {}; this.separator = "&"; }; URIQuery.fromString = function (sourceString, separator) { var result = new URIQuery(); if (separator) { result.separator = separator; } result.addStringParams(sourceString); return result; }; // From http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 // (application/x-www-form-urlencoded). // // NB: The user can get this.params and modify it directly. URIQuery.prototype.addStringParams = function (sourceString) { var kvp = sourceString.split(this.separator); var list, key, value; for (var i = 0; i < kvp.length; i++) { // var [key,value] = kvp.split("=", 2) only works on >= JS 1.7 list = kvp[i].split("=", 2); key = uriUnescape(list[0].replace(/\+/g, " ")); value = uriUnescape(list[1].replace(/\+/g, " ")); if (!this.params.hasOwnProperty(key)) { this.params[key] = []; } this.params[key].push(value); } }; URIQuery.prototype.getParam = function (key) { if (this.params.hasOwnProperty(key)) { return this.params[key][0]; } return null; }; URIQuery.prototype.toString = function () { var kvp = []; var keys = hashkeys(this.params); var ik, ip; for (ik = 0; ik < keys.length; ik++) { for (ip = 0; ip < this.params[keys[ik]].length; ip++) { kvp.push(keys[ik].replace(/ /g, "+") + "=" + this.params[keys[ik]][ip].replace(/ /g, "+")); } } return kvp.join(this.separator); }; })();
0corrina-kmltreeclone
src/URI.js
JavaScript
bsd
9,617
/** * * Base64 encode / decode * http://www.webtoolkit.info/ * **/ var Base64 = { // private property _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, // public method for decoding decode : function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } };
0corrina-kmltreeclone
src/base64.js
JavaScript
bsd
3,003
var enableGoogleLayersControl = (function(){ var setVisibility = function(kmlObject, toggle, ge){ var id = kmlObject.getId(); if(id && id.match(/^LAYER/)){ ge.getLayerRoot().enableLayerById(ge[id], toggle); }else{ var options = ge.getOptions(); switch(id){ case 'SUN': ge.getSun().setVisibility(toggle); break; case 'NAVIGATION_CONTROLS': var vis = ge.VISIBILITY_SHOW if(!toggle){ vis = ge.VISIBILITY_HIDE } ge.getNavigationControl().setVisibility(vis); break; case 'STATUS_BAR': options.setStatusBarVisibility(toggle); break; case 'OVERVIEW_MAP': options.setOverviewMapVisibility(toggle); break; case 'SCALE_LEGEND': options.setScaleLegendVisibility(toggle); break; case 'ATMOSPHERE': options.setAtmosphereVisibility(toggle); break; case 'HISTORICAL_IMAGERY': ge.getTime().setHistoricalImageryEnabled(toggle); break; case 'GRID': options.setGridVisibility(toggle); break; case 'STREET_VIEW': ge.getNavigationControl().setStreetViewEnabled(toggle); } } }; return function(tree, ge){ if(!tree || !ge){ alert('Must call enableGoogleLayersControl with both tree'+ ' and ge options!'); } $(tree).bind('toggleItem', function(e, node, toggle, kmlObject){ setVisibility(kmlObject, toggle, ge); }); $(tree).bind('kmlLoaded', function(e, kmlObject){ var list = kmlObject.getFeatures().getChildNodes(); var length = list.getLength(); for(var i = 0; i < length; i++){ var item = list.item(i); setVisibility(item, item.getVisibility(), ge); } }); } })();
0corrina-kmltreeclone
src/googleLayers.js
JavaScript
bsd
2,304
var kmltreeManager = (function(){ that = {}; var trees = []; var ge; var cache = {}; function init(earthInstance){ ge = earthInstance; google.earth.addEventListener(ge, 'balloonopening', balloonOpening); google.earth.addEventListener(ge, 'balloonclose', balloonClose); google.earth.addEventListener(ge.getGlobe(), 'click', function(e, d){ if(e.getButton() === -1){ // related to scrolling, ignore return; } var target = e.getTarget(); if(target.getType() === 'GEGlobe' && $('.kmltree-selected').length){ for(var i=0;i<trees.length;i++){ var treeEl = $(trees[i].api.opts.element); if(treeEl.find('.kmltree-selected').length + treeEl.find('.kmltree-breadcrumb').length > 0){ trees[i].instance.clearSelection(); } } } }); } var register = function(tree, privilegedApi){ if(trees.length === 0){ init(privilegedApi.opts.gex.pluginInstance); } trees.push({ key: 'kmltree-tree-' + trees.length.toString(), instance: tree, api: privilegedApi }); }; that.register = register; var remove = function(tree){ for(var i = 0; i<trees.length; i++){ if(trees[i].instance === tree){ trees.splice(i, 1); break; } } for(var key in cache){ if(cache[key].instance === tree){ delete cache[key]; } } return tree; }; that.remove = remove; var pauseListeners = function(callable){ google.earth.removeEventListener( ge, 'balloonopening', balloonOpening); google.earth.removeEventListener( ge, 'balloonclose', balloonClose); callable(); google.earth.addEventListener( ge, 'balloonopening', balloonOpening); google.earth.addEventListener( ge, 'balloonclose', balloonClose); }; that.pauseListeners = pauseListeners; var getApi = function(tree){ for(var i=0;i<trees.length;i++){ if(trees[i].instance === tree){ return trees[i].api; } } }; var balloonOpening = function(e){ var f = e.getFeature(); var tree = getOwner(f); if(tree){ e.preventDefault(); ge.setBalloon(null); var selectable = false; var id = f.getId(); if(id){ selectable = tree.api.opts.selectable; if(typeof selectable === 'function'){ selectable = selectable(f); } } if(selectable){ tree.instance.selectById(id, f); } openBalloon(f, tree); return false; } // otherwise feature likely loaded outside of a kmltree instance } var balloonClose = function(e){ $('#kmltree-balloon-iframe').remove(); for(var i=0;i<trees.length;i++){ var treeEl = $(trees[i].api.opts.element); if(treeEl.find('.kmltree-selected').length + treeEl.find('.KmlNetworkLink.kmltree-breadcrumb:not(.loaded)').length === 1 && treeEl.find('.kmltree-cursor-2').length === 0){ trees[i].instance.clearSelection(); }else{ // console.log('didnt find stuff', treeEl.find('.kmltree-selected'), treeEl.find('KmlNetworkLink.kmltree-breadcrumb:not(.loaded)'), treeEl.find('.kmltree-selected').length + treeEl.find('KmlNetworkLink.kmltree-breadcrumb:not(.loaded)').length); } } }; var _clearEverythingButMe = function(tree){ for(var i=0;i<trees.length;i++){ if(trees[i].instance !== tree){ if($(trees[i].api.opts.element).find('.kmltree-selected').length || $(trees[i].api.opts.element).find('.kmltree-breadcrumb').length){ trees[i].instance.clearSelection(); } } } }; that._clearEverythingButMe = _clearEverythingButMe; var ownsUrl = function(doc, url){ if(!doc){ // In case the tree failed to load return false; } if(doc.getUrl() === url){ return true; } if(trimUrl(doc.getUrl()) === trimUrl(url)){ return true; } if(doc.getElementByUrl(url)){ return true; } if(doc.getElementByUrl(trimUrl(url))){ return true; } return false; } var trimUrl = function(url){ var newUrl = url.split('#')[0]; // Remove cachebuster. If not done, selection of features within // networklinks from the map will stop working after refresh. // Took a while to notice that bug!! newUrl = newUrl.replace(/cachebuster=\d+/, ''); if(newUrl.indexOf('?') === newUrl.length - 1){ newUrl = newUrl.replace('?', ''); } return newUrl; } var getOwner = function(kmlObject){ var url = kmlObject.getUrl(); var urlWithoutId = trimUrl(url); if(cache[urlWithoutId]){ return cache[urlWithoutId]; } // First check if url matches root element for(var i=0;i<trees.length;i++){ if(ownsUrl(trees[i].instance.kmlObject, url)){ cache[urlWithoutId] = trees[i]; return trees[i]; } } // Then check each tree's expanded NetworkLinks // TODO: Test if this works for(var i=0;i<trees.length;i++){ var tree = trees[i].instance; var api = trees[i].api; var docs = tree.docs; for(var j = 0; j<docs.length;j++){ var doc = docs[j]; if(ownsUrl(doc, url)){ cache[urlWithoutId] = trees[i]; return trees[i]; } } } // Couldn't find. Could be content loaded outside kmltree. // In any case, ignore return false; }; that.getOwner = function(kmlObject){ var t = getOwner(kmlObject); if(t){ return t.instance; }else{ return false; } }; var openBalloon = function(kmlObject, tree){ $(window).unbind("message.kmlTreeIframeEvents"); var balloon; var tree = tree.instance ? tree.instance : tree; var api = tree.api ? tree.api : getApi(tree); // Compare getBalloonHtmlUnsafe to getBalloonHtml to determine whether // there is even any need to use an iframe to display unsafe content var allow = api.opts.displayEnhancedContent; if(typeof allow === 'function'){ allow = allow(kmlObject); } if(allow){ // don't bother checking if not going to display var unsafeHtml = kmlObject.getBalloonHtmlUnsafe(); var safeHtml = kmlObject.getBalloonHtml(); var safeHtml = $.trim( safeHtml.replace( /\s*<!--\s*Content-type: mhtml-die-die-die\s*-->/, '')); var hasUnsafeContent = safeHtml != $.trim(unsafeHtml); } if(allow && hasUnsafeContent){ balloon = ge.createHtmlDivBalloon(''); var iframe = document.createElement('iframe'); iframe.setAttribute('src', api.opts.iframeSandbox); iframe.setAttribute('frameBorder', '0'); iframe.setAttribute('id', 'kmltree-balloon-iframe'); var div = document.createElement('div'); $(div).append(iframe); $(iframe).one('load', function(){ $(window).bind("message.kmlTreeIframeEvents", {'window': iframe.contentWindow}, function(e){ var ev = e.originalEvent; if(ev.source === e.data.window){ resize(ev); } }); var msg = JSON.stringify({ html: Base64.encode(unsafeHtml), callback: Base64.encode( api.opts.sandboxedBalloonCallback.toString()) }); // Posting to any domain since iframe popups may have their // window.location changed by javascript code in the // description. this.contentWindow.postMessage(msg, '*'); }); balloon.setContentDiv(div); }else{ balloon = ge.createFeatureBalloon(''); // callback for normal popups. Enhanced popup balloonopen event is // triggered by resize function var boCallback = function(e){ // This has to be done within a setTimeout call. Otherwise you // can't open another balloon using an event listener and // count on that event to fire. I think this is so you can // have callbacks like balloonOpening that don't go into an // infinite loop google.earth.removeEventListener( ge, 'balloonopening', boCallback); setTimeout(function(){ $(tree).trigger('balloonopen', [ e.getBalloon(), e.getFeature()]); }, 1); }; google.earth.addEventListener(ge, 'balloonopening', boCallback); } balloon.setFeature(kmlObject); ge.setBalloon(balloon); }; that._openBalloon = openBalloon; function resize(e){ var b = ge.getBalloon(); var f = b.getFeature(); var iframe = $('#kmltree-balloon-iframe'); if( // There should at least be an iframe present !iframe.length || // Message must include a new dimension or specify that none could // be calculated !(e.data.match(/width/) || e.data.match(/unknownIframeDimensions/) ) || // Make sure the current popup is an HtmlDivBalloon b.getType() !== 'GEHtmlDivBalloon'){ // and if all those conditions aren't met... // Oooooo... A zombie Iframe!!! // don't do anything, that balloon has already closed return; } var tree = getOwner(f); var dim = JSON.parse(e.data) if(dim.unknownIframeDimensions){ var dim = tree.api.opts.unknownIframeDimensionsDefault; if(typeof dim === 'function'){ dim = dim(f); } } var el = $('#kmltree-balloon-iframe'); b.setMinWidth(dim.width); b.setMaxWidth(dim.width + (dim.width * .1)); b.setMinHeight(dim.height); b.setMaxHeight(dim.height + (dim.height * .1)); el.height(dim.height); el.width(dim.width); $(tree.instance).trigger('balloonopen', [b, f]); } // Implemented this because call window.frameElement on a cross-origin // iframe results in a security exception. function frameElement(win){ var iframes = document.getElementsByTagName('iframe'); for(var i =0;i<iframes.length;i++){ if(iframes[0].contentWindow === win){ return iframes[i]; } } } return that; })();
0corrina-kmltreeclone
src/kmltreeManager.js
JavaScript
bsd
11,725
=opacity( $pct ) opacity: $pct/100 -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=#{$pct})" filter: alpha(opacity='#{$pct}') = user-select( $user_select ) -moz-user-select: $user_select -khtml-user-select: $user_select -webkit-user-select: $user_select user-select: $user_select // from http://gist.github.com/215561 // Apply a CSS text-shadow cross-browser. // There is one todo/gotcha: the direction is hardcoded to towards // the bottom-right for IE, but that's good enough for my use case. // Usage example: +text-shadow(#333, 1px, 1px, 1) =text-shadow($color, $x, $y, $blur) text-shadow: $color $x $y "#{$blur}px" -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Color=#{$color},Direction=135,Strength=#{$blur})" =background-size( $x, $y ) -moz-background-size: $x $y -khtml-background-size: $x, $y -webkit-background-size: $x, $y -o-background-size: $x, $y background-size: $x, $y
0corrina-kmltreeclone
src/_mixins.sass
Sass
bsd
942
// src/tmpl.js // Simple JavaScript Templating // John Resig - http://ejohn.org/ - MIT Licensed (function(){ var cache = {}; this.tmpl = function tmpl(str, data){ // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; })();
0corrina-kmltreeclone
src/tmpl.js
JavaScript
bsd
1,215
@import sprites.sass @import mixins.sass div.kmltree font-family: sans-serif font-size: 12px +user-select(none) li +user-select(none) .toggler, .expander +user-select(none) p.error +user-select(text) ul list-style: none padding-left: 18px li ul padding-top: 5px display: none // allows for folders and networklinks to be opened and closed &.open > ul display: block // these elements are just used as identifiers and should be hidden span &.kmlId, &.nlDocId display: none li.kmltree-item white-space: nowrap margin: 0 padding: 5px 0 // using off-blank to make it easy on the eyes span.name color: #313841 cursor: default // act like a link so users know to click &.hasDescription > span.name color: blue text-decoration: underline cursor: pointer h4.kmltree-title color: #6C7C90 font-weight: bold margin: 0 0 -5px 0 .expander, .toggler, .icon margin: 0 padding: 0 float: left width: 16px height: 16px .expander, .toggler cursor: pointer // Expander sprites .expander +sprite("kml", "arrow-right") margin-left: -17px &:hover +sprite("kml", "arrow-right-hover") &:active +sprite("kml", "arrow-right-active") li.open > .expander +sprite("kml", "arrow-down") &:hover +sprite("kml", "arrow-down-hover") &:active +sprite("kml", "arrow-down-active") // Toggling Sprites .toggler margin-right: 4px +sprite("kml", "unchecked") &:hover +sprite("kml", "unchecked-hover") &:active +sprite("kml", "unchecked-active") li.checkOffOnly > .toggler +sprite("kml", "unchecked-checkOffOnly") li &.visible > .toggler +sprite("kml", "checked") &:hover +sprite("kml", "checked-hover") &:active +sprite("kml", "checked-active") &.radioFolder > ul > li > .toggler +sprite("kml", "radio-off") &:hover +sprite("kml", "radio-off-hover") &:active +sprite("kml", "radio-off-active") &.visible > .toggler +sprite("kml", "radio-on") &:hover +sprite("kml", "radio-on-hover") &:active +sprite("kml", "radio-on-active") &.radioFolder > .toggler +sprite("kml", "radio-off") &:hover +sprite("kml", "radio-off-hover") &:active +sprite("kml", "radio-off-active") &.radioFolder.visible > .toggler +sprite("kml", "radio-on") &:hover +sprite("kml", "radio-on-hover") &:active +sprite("kml", "radio-on-active") &.KmlPlacemark > .expander, &.KmlPhotoOverlay > .expander, &.KmlGroundOverlay > .expander, &.KmlTour > .expander display: none li.KmlPlacemark > span.name, li.select > span.name cursor: pointer div.kmltree li.checkHideChildren ul, .expander display: none .icon display: none padding: 0px // Icon Sprites li.KmlFolder > .icon, li.KmlNetworkLink > .icon, li.KmlTour > .icon, li.KmlPhotoOverlay > .icon, li.KmlGroundOverlay > .icon, li.KmlScreenOverlay > .icon, li.customIcon > .icon, li.KmlPolygon > .icon, li.KmlLineString > .icon, li.KmlMultiGeometry > .icon, li.KmlDocument > .icon margin-right: 4px display: block .nlSpinner display: none li &.KmlFolder > .icon, &.KmlDocument > .icon +sprite("kml", "folder") &.KmlFolder.open > .icon, &.KmlDocument.open > .icon +sprite("kml", "folder-open") &.KmlNetworkLink > .icon +sprite("kml", "folder") &.loading > .icon position: relative +sprite("kml", "networklink-loading") &.loading > .icon > .nlSpinner width: 8px height: 8px display: block position: absolute left: 6px top: 6px background: transparent url(./images/networklink-loading-animated.gif) no-repeat !important &.loading > .expander +opacity(30) &.error > .icon +sprite("kml", "folder-error") &.error > .expander display: none &.KmlTour > .icon +sprite("kml", "tour") &.KmlPhotoOverlay > .icon, &.KmlGroundOverlay > .icon +sprite("kml", "superoverlay") &.KmlScreenOverlay > .icon +sprite("kml", "screenoverlay") &.KmlPolygon > .icon +sprite("kml", "polygon") &.KmlLineString > .icon, &.KmlMultiGeometry > .icon +sprite("kml", "linestring") &.customIcon > .icon +background-size(16px, 16px) background: transparent no-repeat &.kmltree-item p.snippet text-indent: 0px width: 80% margin: 5px 0px 5px 20px color: #6C7C90 white-space: normal span.name clear: both position: relative top: 1px div &.kmltree li.kmltree-selected background-color: #BEDCED padding-left: 5px margin-left: -5px > span.name font-weight: bold border-bottom: none &:hover border: none // // li.kmltree-cursor-1 // border-left: solid 1px blue // // li.kmltree-cursor-2 // border-left: solid 1px red // div &.kmltree li.kmltree-breadcrumb background-color: #E6F7FB margin-top: -1px margin-left: -1px margin-bottom: -1px border: dotted 1px #CCC // Loading throbber div.kmltree-loading position: absolute left: 0px top: 0px width: 100% height: 100% background-color: #FFF +opacity(70) text-align: center span position: absolute padding-top: 20px top: 0px left: 0px width: 100% +opacity(100) font-weight: bold height: 40px padding-bottom: 15px background: transparent url(images/ajax-loader.gif) no-repeat center bottom .kmlTreeReset font-family: sans-serif color: black h1 font-size: 18px a font-size: 18px h2 font-size: 16px a font-size: 16px h3 font-size: 14px a font-size: 14px h1, h2, h3 margin: 1em 0 h1,h2,h3,h4,h5,h6,strong,dt font-weight: bold color: black em font-style: italic blockquote,ul,ol,dl margin: 1em ol,ul,dl margin-left: 2em ol li list-style: decimal outside ul li list-style: disc outside dl dd margin-left: 1em th,td padding: 0em th font-weight: bold text-align: center p, fieldset, table, pre margin-bottom: 1em p, div font-size: 12px color: black a font-size: 12px color: blue text-decoration: underline
0corrina-kmltreeclone
src/main.sass
Sass
bsd
6,333
module('kmlTree'); (function(){ function triggerBalloon(ge, url){ var f = ge.getElementByUrl(url); if(!f){ throw('could not find feature with url ', url); } var balloon = ge.createHtmlStringBalloon(''); balloon.setFeature(f); ge.setBalloon(balloon); } // from http://stackoverflow.com/questions/901115/get-querystring-with-jquery function getParameterByName( name, href ) { href = href || window.location.href; name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( href ); if( results == null ){ return ""; }else{ return results[1]; } } // given the name of a file within examples/kml, creates an absolute url // to it, appending ?r=revision if necessary function example(filename){ var url = '../examples/kml/' + filename; // var url = 'http://kmltree.googlecode.com/hg/examples/kml/' + filename; var r = getParameterByName('r'); if(r !== ''){ url = url + '?r=' + r; } return url; } earthTest('create instance', 2, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var errors = false; try{ var tree = kmltree({ gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); }catch(e){ errors = true; } ok(errors); var tree = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); ok(tree !== false, 'Tree initialized'); tree.destroy(); $('.kmltreetest').remove(); }); earthAsyncTest('load kml, fire kmlLoaded event. <a href="../examples/kmlLoaded.html">example</a>', 4, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: true }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ok(this === tree, '"this" refers to the instance of kmltree'); equals(kmlObject.getType(), 'KmlDocument', 'kmlObject refers to the loaded KmlDocument'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(); }); earthAsyncTest('click events <a href="../examples/clickEvents.html">example</a>', 5, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('clickEvents.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(Click Me)') .click(); }); $(tree).bind('click', function(e, node, kmlObject){ equals(kmlObject.getName(), 'Click Me'); equals(e.target, tree); equals(this, tree, '"this" refers to the instance of kmltree'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('events arent confused across multiple instances', 9, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); $(document.body).append('<div class="kmltreetest2"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); var tree2 = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest2'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ tree2.load(true); ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); equals(e.target, tree); $('.kmltreetest').find('span.name:contains(Placemark without description)') .click(); }); $(tree).bind('click', function(e, node, kmlObject){ equals(kmlObject.getName(), 'Placemark without description'); equals(e.target, tree); }); $(tree2).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); equals(e.target, tree2); $('.kmltreetest2').find('span.name:contains(Placemark without description)') .click(); }); $(tree2).bind('click', function(e, node, kmlObject){ equals(kmlObject.getName(), 'Placemark without description'); equals(e.target, tree2); tree.destroy(); tree2.destroy(); $('.kmltreetest').remove(); $('.kmltreetest2').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('dblclick events', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(Placemark without description)') .dblclick(); }); $(tree).bind('dblclick', function(e, node, kmlObject){ equals(kmlObject.getName(), 'Placemark without description'); equals(e.target, tree); equals(this, tree, '"this" refers to the instance of kmltree'); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('setExtent option', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, setExtent: true }); $(tree).bind('kmlLoaded', function(e, kmlObject){ setTimeout(function(){ var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ok(secondLat !== firstLat); $('.kmltreetest').remove(); tree.destroy(); start(); }, 500); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('context menu support', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); var e = jQuery.Event('click'); e.metaKey = true; $(tree).one('select', function(e, data){ equals(data.length, 2, 'Two kmlObjects selected'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree).one('context', function(e, data){ equals(data.length, 2, 'Two kmlObjects selected'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree).one('context', function(e, data){ equals(data.length, 1, 'One kmlObject selected'); ok(inSelectData(data, "Admiral's Reef"), "Admiral's Reef in selected features"); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('li.ADMRLS').trigger('contextmenu'); }); $('li.GullIsland > span.name').trigger('contextmenu'); }); $('li.GullIsland > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); // className option earthAsyncTest('classname option', 4, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, classname: function(kmlObject){ var type = kmlObject.getType(); if(type === 'KmlPlacemark'){ return 'myPlacemarkClass' }else if(type === 'KmlDocument'){ return 'myDocClass'; }else{ return 'myClass'; } } }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); equals($('li.myPlacemarkClass.KmlPlacemark').length, 1, 'Placemark has custom class'); equals($('li.myDocClass.KmlDocument').length, 1, 'Doc has custom class'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('getNodesById', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Placemark with ID)').parent(); equals(node.length, 1); var nodes = tree.getNodesById('myId'); equals(nodes.length, 1); equals(nodes[0], node[0]); equals(tree.getNodesById('non-existent').length, 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // earthAsyncTest('optional title support', function(ge, gex){ // $(document.body).append('<div class="kmltreetest"></div>'); // var tree = kmltree({ // url: example('kmlForestTest.kml'), // gex: gex, // mapElement: $('#map3d'), // element: $('.kmltreetest'), // title: true, // bustCache: false // }); // $(tree).bind('kmlLoaded', function(e, kmlObject){ // ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); // var title = $('.kmltreetest').find('h4:contains(kmlForestTest.kml)'); // equals(title.length, 1); // ok(title.hasClass('marinemap-kmltree-title')) // tree.destroy(); // $('.kmltreetest').remove(); // start(); // }); // ok(tree !== false, 'Tree initialized'); // tree.load(true); // }); earthAsyncTest('supports kml <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#open">open tag</a>', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var closed = $('.kmltreetest').find('span.name:contains(closed folder)'); equals(closed.length, 1); ok(!closed.parent().hasClass('open')); var open = $('.kmltreetest').find('span.name:contains(Radio Folder)'); equals(open.length, 1); ok(open.parent().hasClass('open')); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('supports <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#visibility">visibility tag</a>', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var nodes = tree.getNodesById('myId'); var kmlObject = tree.lookup(nodes); equals(kmlObject.getName(), 'Placemark with ID'); ok(nodes.hasClass('visible')); equals(kmlObject.getVisibility(), 1); var node = $('.kmltreetest').find('span.name:contains(Visibility set to false)').parent(); equals(node.length, 1); ok(!node.hasClass('visible')); var kmlObject = tree.lookup(node); equals(kmlObject.getName(), 'Visibility set to false'); equals(kmlObject.getVisibility(), 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('supports <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#snippet">snippet tag</a>', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(PhotoOverlay of South Coast Study Region)').parent(); equals(node.length, 1); equals(node.find('> .snippet').length, 1); var node = $('.kmltreetest').find('span.name:contains(Visibility set to false)').parent(); equals(node.length, 1); equals(node.find('> .snippet').length, 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('features with descriptions appear as a link', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Placemark without description)').parent(); ok(!node.hasClass('hasDescription')); var node = $('.kmltreetest').find('span.name:contains(Placemark with description)').parent(); ok(node.hasClass('hasDescription')); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("open folder contents visible, closed folders' content not", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(closed folder)').parent(); equals(node.find('> ul:visible').length, 0); var node = $('.kmltreetest').find('span.name:contains(Radio Folder)').parent(); equals(node.find('> ul:visible').length, 1); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('folders expand/collapse', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(closed folder)').parent(); equals(node.length, 1); node.find('> .expander').click(); equals(node.find('>ul:visible').length, 1); node.find('> .expander').click(); equals(node.find('>ul:visible').length, 0); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('can toggle features', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(PhotoOverlay of South Coast Study Region)').parent(); var kmlObject = tree.lookup(node); equals(node.length, 1); ok(!kmlObject.getVisibility()); node.find('> .toggler').click(); ok(kmlObject.getVisibility()); ok(kmlObject.getVisibility()); node.find('> .toggler').click(); ok(!kmlObject.getVisibility()); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('toggling folders toggles children', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Both visible)').parent(); var kmlObject = tree.lookup(node); equals(node.length, 1); // All items on to start ok(node.find('> ul > li.visible').length > 0); ok(kmlObject.getVisibility()); // turn them off node.find('> .toggler').click(); equals(node.find('> ul > li.visible').length, 0); ok(!kmlObject.getVisibility()); var child = node.find('> ul > li')[0]; var childKml = tree.lookup(child); ok(childKml); ok(!childKml.getVisibility()); // turn back on node.find('> .toggler').click(); ok(kmlObject.getVisibility()); ok(childKml.getVisibility()); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('toggling child toggles all parents', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(level 4)').parent(); equals(node.length, 1); // All items off to start ok(!node.hasClass('visible')); // turn on node.find('> .toggler').click(); var kmlObject = tree.lookup(node); ok(kmlObject); ok(kmlObject.getVisibility()); var level1 = $('.kmltreetest').find('span.name:contains(level 1)').parent(); ok(level1.hasClass('visible')); ok(tree.lookup(level1).getVisibility()); var level2sib = $('.kmltreetest').find('span.name:contains(level 2 sibling)').parent(); ok(!level2sib.hasClass('visible')); ok(!tree.lookup(level2sib).getVisibility()); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('toggling all children off toggles parents off', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); $('.kmltreetest').remove(); start(); }); // // Tests for when a semi-toggled state for folders is implemented // // earthAsyncTest('toggling child with no siblings toggles folder', function(ge, gex){ // $(document.body).append('<div class="kmltreetest"></div>'); // $('.kmltreetest').remove(); // start(); // }); // // earthAsyncTest('toggling one of many children semi-toggles folder', function(ge, gex){ // $(document.body).append('<div class="kmltreetest"></div>'); // $('.kmltreetest').remove(); // start(); // }); // // earthAsyncTest('semi-toggling travels up deeply nested trees', function(ge, gex){ // $(document.body).append('<div class="kmltreetest"></div>'); // $('.kmltreetest').remove(); // start(); // }); earthAsyncTest('list items given class names matching kmlObject.getType()', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ok($('.kmltreetest').find('li.KmlPlacemark').length > 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('radioFolder support', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(One at a time)').parent(); var a = node.find('span.name:contains(Radio A)').parent(); var b = node.find('span.name:contains(Radio B)').parent(); ok(node.length === 1); ok(a.length === 1); ok(b.length === 1); ok(node.hasClass('radioFolder')); var kmlObject = tree.lookup(node); // start out not visible ok(!kmlObject.getVisibility()); node.find('> .toggler').click(); ok(kmlObject.getVisibility()); ok(tree.lookup(a).getVisibility()); ok(a.hasClass('visible')); ok(!tree.lookup(b).getVisibility()); ok(!b.hasClass('visible')); b.find('> .toggler').click(); ok(!tree.lookup(a).getVisibility()); ok(tree.lookup(b).getVisibility()); b.find('> .toggler').click(); ok(!tree.lookup(a).getVisibility()); ok(!tree.lookup(b).getVisibility()) tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("toggling parent of radio folder doesn't toggle all radioFolder children.", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(One at a time)').parent(); var a = node.find('span.name:contains(Radio A)').parent(); var b = node.find('span.name:contains(Radio B)').parent(); ok(node.length === 1); ok(a.length === 1); ok(b.length === 1); ok(node.hasClass('radioFolder')); var parent = node.parent().parent(); parent.find('> .toggler').click(); parent.find('> .toggler').click(); parent.find('> .toggler').click(); ok(!tree.lookup(parent).getVisibility(), 'Startout with parent and children cleared'); ok(!tree.lookup(a).getVisibility(), 'Startout with parent and children cleared'); ok(!tree.lookup(b).getVisibility(), 'Startout with parent and children cleared'); parent.find('> .toggler').click(); ok(tree.lookup(a).getVisibility(), 'Should turn on the first child.'); ok(!tree.lookup(b).getVisibility(), 'Only one child of a radioFolder should be turned on at a time.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('<a href="http://code.google.com/apis/kml/documentation/kmlreference.html#liststyle">ListStyle</a> support: checkOffOnly', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var parent = $('.kmltreetest').find('span.name:contains(check off only)').parent(); var a = parent.find('span.name:contains(a)').parent(); var b = parent.find('span.name:contains(b)').parent(); ok(tree.lookup(parent).getVisibility()); ok(tree.lookup(a).getVisibility()); ok(tree.lookup(b).getVisibility()); parent.find('> .toggler').click(); ok(!tree.lookup(parent).getVisibility(), 'Parent visibility off after click.'); ok(!tree.lookup(a).getVisibility(), 'Both children should be turned off by click on parent.'); ok(!tree.lookup(b).getVisibility(), 'Both children should be turned off by click on parent.'); parent.find('> .toggler').click(); ok(!tree.lookup(parent).getVisibility() && !tree.lookup(a).getVisibility() && !tree.lookup(b).getVisibility(), 'Should not be able to toggle visibility with listItemType = checkOffOnly.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('<a href="http://code.google.com/apis/kml/documentation/kmlreference.html#liststyle">ListStyle</a> support: checkHideChildren', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var folder = $('.kmltreetest').find('span.name:contains(folder with contents hidden)').parent(); ok(folder.find('> .toggler:visible').length === 0, 'Toggle icon should not be visible'); ok(folder.find('> ul > li').length === 0, 'Shouldnt add children'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('ItemIcon if option specified', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('earthLayers.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, supportItemIcon: true }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var grid = $('.kmltreetest').find('span.name:contains(Grid)').parent(); var icon = grid.find('>.icon').css('background-image'); ok(icon.indexOf('http://marinemap.googlecode.com/svn/trunk/media/common/images/silk/sport_golf.png') !== -1); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('click on elements with descriptions opens balloon.', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ok(!ge.getBalloon(), 'start out with no balloon open.'); var node = $('.kmltreetest').find('span.name:contains(Placemark with description)').parent(); $('.kmltreetest').find('span.name:contains(Placemark with description)').click(); ok(ge.getBalloon(), 'Balloon should now be open.'); ok(tree.lookup(node).getVisibility(), 'Should be visible if viewing balloon.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('Untoggling feature with balloon closes it.', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ge.setBalloon(null); ok(!ge.getBalloon(), 'start out with no balloon open.'); var node = $('.kmltreetest').find('span.name:contains(Placemark with description)').parent(); $('.kmltreetest').find('span.name:contains(Placemark with description)').click(); ok(ge.getBalloon(), 'Balloon should now be open.'); ok(tree.lookup(node).getVisibility(), 'Should be visible if viewing balloon.'); node.find('> .toggler').click(); ok(!tree.lookup(node).getVisibility(), 'Feature should be invisible'); ok(!ge.getBalloon(), 'Balloon should be closed.'); ge.setBalloon(null); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('double click feature flys to feature', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Visibility set to false)').parent(); node.find('span.name').dblclick(); ok(tree.lookup(node).getVisibility(), 'Feature should be visible.'); setTimeout(function(){ var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(secondLat !== firstLat); tree.destroy(); $('.kmltreetest').remove(); start(); }, 400); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('double click works on icons too', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(Placemark without description)').parent().find('.icon').dblclick(); setTimeout(function(){ var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(secondLat !== firstLat); tree.destroy(); $('.kmltreetest').remove(); start(); }, 400); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // Not a very good test. If the double click event was instead causing the // viewport to zoom to the camera like any other feature, the bug likely // wouldn't be detected. Should really be a ge.getTourPlayer().getTour() api. // A feature request has been submitted for that function // http://code.google.com/p/earth-api-samples/issues/detail?id=309 earthAsyncTest('tours are activated when double-clicked.', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Tour Example)').parent(); ok(node.length, "Tour exists"); var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); node.dblclick(); ge.getTourPlayer().play(); var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(firstLat != secondLat, "Assuming the latitude changes after double-clicking the tour, it must be active."); ge.getTourPlayer().pause(); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refresh reloads kml tree', 3, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); tree.refresh(); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); tree.destroy(); $('.kmltreetest').remove(); start(); }); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('selectNode', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("selection kmltree-breadcrumbs - one networklink deep", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'San Miguel Island', 'Correct feature selected'); ok(node.hasClass('KmlNetworkLink'), 'Node returned to event callback is actually the parent networklink'); ok(node.hasClass('kmltree-breadcrumb'), 'NetworkLink has kmltree-breadcrumb class'); $(tree).one('networklinkload', function(e){ ok(!node.hasClass('kmltree-breadcrumb'), 'NetworkLink should no longer have kmltree-breadcrumb class'); ok(node.find('.kmltree-selected:contains("San Miguel")').length === 1, 'Child feature is selected'); // roll back up var nla = $('.KmlNetworkLink > :contains("networklink a")').parent(); nla.find('.expander').click(); ok(nla.hasClass('kmltree-breadcrumb'), 'collapsing networklink back up add kmltree-breadcrumb.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); node.find('.expander').click() }); setTimeout(function(){ // wait for networklink to load up triggerBalloon(ge, 'http://underbluewaters-try-better-selection-api.googlecode.com/hg/examples/kml/selection_2.kml#SMI'); }, 1000); }); tree.load(true); }); earthAsyncTest("selection kmltree-breadcrumbs - two networklinks deep with folder in-between", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Jalama', 'Correct feature selected'); ok(node.hasClass('KmlNetworkLink'), 'Node returned to event callback is actually the parent networklink'); ok(node.hasClass('kmltree-breadcrumb'), 'NetworkLink has kmltree-breadcrumb class'); $(tree).one('networklinkload', function(e){ ok(!node.hasClass('kmltree-breadcrumb'), 'NetworkLink should no longer have kmltree-breadcrumb class'); var folder = node.find('.KmlFolder.kmltree-breadcrumb'); ok(folder, 'Folder has kmltree-breadcrumb class'); folder.find('> .expander').click(); ok(!folder.hasClass('kmltree-breadcrumb'), 'After expanding, folder kmltree-breadcrumb is removed'); var nlb = folder.find('.KmlNetworkLink.kmltree-breadcrumb'); ok(nlb, 'networklink b kmltree-breadcrumb-ed'); $(tree).one('networklinkload', function(e){ ok(!nlb.hasClass('kmltree-breadcrumb'), 'kmltree-breadcrumb class removed from expanded networklink'); ok(node.find('.kmltree-selected').length, 'Selected item found under networklink'); // rollup node.find('> .expander').click(); ok(node.hasClass('kmltree-breadcrumb'), 'collapsed networklink indicates location of nested selection.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); nlb.find('> .expander').click(); }); node.find('> .expander').click() }); setTimeout(function(){ // wait for networklink to load up triggerBalloon(ge, 'http://underbluewaters-try-better-selection-api.googlecode.com/hg/examples/kml/selection_3.kml#JAL'); }, 2000); }); tree.load(true); }); earthAsyncTest('selectable - static selectable option', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); tree.destroy(); $('.kmltreetest').remove(); start(); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); earthAsyncTest('selectable - callable selectable option', function(ge, gex){ var gulltested = 0; $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ if(kmlObject.getName() === 'Forney'){ return true; }else{ if(kmlObject.getId() === 'GullIsland'){ gulltested++; } return false; } } }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); ge.setBalloon(null); triggerBalloon(ge, tree.kmlObject.getUrl() + '#GullIsland'); equals(gulltested, 2, 'Gull Island clicked on but not selected'); tree.destroy(); $('.kmltreetest').remove(); start(); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); // multiple-select should be turned off by default earthAsyncTest('selectable - multipleSelect off by default', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multiple: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); var e = jQuery.Event('click'); e.metaKey = true; $(tree).one('select', function(e, data){ equals(data.length, 1, 'Only one kmlObject selected'); equals(data[0].kmlObject.getName(), 'Gull Island', 'Correct selected feature'); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('li.GullIsland > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); function inSelectData(data, name){ for(var i =0;i<data.length;i++){ var kmlObject = data[i].kmlObject; if(kmlObject.getName() === name){ return true; } } return false; }; // command-select support earthAsyncTest('selectable - multipleSelect command/ctrl+select support', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); var e = jQuery.Event('click'); e.metaKey = true; $(tree).one('select', function(e, data){ equals(data.length, 2, 'Two kmlObjects selected'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree).one('select', function(e, data){ equals(data.length, 1, 'Command+Clicking again deselects'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); var e = jQuery.Event('click'); e.metaKey = true; $(tree).one('select', function(e, data){ equals(data.length, 2, 'Two kmlObjects selected'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree).one('select', function(e, data){ equals(data.length, 1, 'Clicking without meta-key clears multiple select'); setTimeout(function(){ equals($('.selected').length, 0, 'Trying to select unselectable does nothing.'); tree.destroy(); $('.kmltreetest').remove(); start(); }, 500); var e = jQuery.Event('click'); e.metaKey = true; $('#FLD1').trigger(e); }); $('li.GullIsland > span.name').click(); }); var e = jQuery.Event('click'); e.metaKey = true; $('li.GullIsland > span.name').trigger(e); }); var e = jQuery.Event('click'); e.metaKey = true; $('li.GullIsland > span.name').trigger(e); }); $('li.GullIsland > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); // shift+select support earthAsyncTest('selectable - multipleSelect shift+click', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); $(tree).one('select', function(e, data){ equals(data.length, 3, 'Selected all 3 placemarks'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); ok(inSelectData(data, "Admiral's Reef"), "Admiral's Reef in selected features"); $(tree).one('select', function(e, data){ equals(data.length, 1, 'Switch cursor to gull'); $(tree).one('select', function(e, data){ equals(data.length, 2, 'Selected Admirals and Gull'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, "Admiral's Reef"), "Admiral's Reef in selected features"); $(tree).one('select', function(e, data){ equals(data.length, 2, 'Selected Forney and Gull'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, "Forney"), "Admiral's Reef in selected features"); tree.destroy(); $('.kmltreetest').remove(); start(); }); var e = jQuery.Event('click'); e.shiftKey = true; $('li.Forney > span.name').trigger(e); }); var e = jQuery.Event('click'); e.shiftKey = true; $('li.ADMRLS > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#GullIsland'); }); var e = jQuery.Event('click'); e.shiftKey = true; $('li.ADMRLS > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); // multipleSelect - two kmltrees // normal selections from map and tree // shift select on both trees earthAsyncTest('selectable - multiple trees', function(ge, gex){ var gulltested = 0; $(document.body).append('<div class="kmltreetest"></div>'); $(document.body).append('<div class="kmltreetest2"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); var tree2 = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest2'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(){ $(tree2).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ equals(data.length, 1, 'One feature selected from map'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree2).one('select', function(e, data){ equals(data.length, 1, 'One feature selected from map on other tree'); ok(inSelectData(data, 'Hello!'), 'Hello! in selected features'); equals($('.kmltree .kmltree-selected').length, 1, 'Only one feature from one tree selected'); tree.destroy(); tree2.destroy(); $('.kmltreetest').remove(); $('.kmltreetest2').remove(); start(); }); $('.kmltreetest2 .hello .name').click(); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree2.load(true); }); tree.load(true); }); // TODO: Test cases for all the new apis that aren't yet tested // selections on unexpanded features get kmltree-breadcrumbs indicating what items to expand to reach them in the tree earthAsyncTest("un-expanded feature's parent has kmltree-breadcrumb class, and it is removed when expanded", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Yellowbanks', 'Correct feature selected'); var folder = $('.kmltree-breadcrumb.KmlFolder > :contains(Yellowbanks)').parent(); ok(folder.hasClass('KmlFolder'), 'Parent KmlFolder has kmltree-breadcrumb class'); folder.find('.expander').click(); ok(!folder.hasClass('kmltree-breadcrumb'), 'kmltree-breadcrumb class removed now that folder is expanded'); ok(node.hasClass('kmltree-selected'), 'primary node should be selected'); tree.destroy(); $('.kmltreetest').remove(); start(); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Yellowbanks'); }); tree.load(true); }); earthAsyncTest('Contents of NetworkLinks can be displayed. Depends on <a href="http://code.google.com/p/earth-api-samples/issues/detail?id=260&q=NetworkLink&colspec=ID%20Type%20Summary%20Component%20OpSys%20Browser%20Status%20Stars#c3">this ticket</a>, or a hack', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var nlink = $('.kmltreetest').find('span.name:contains(networklink a)').parent(); var nlinkobject = tree.lookup(nlink); $(tree).bind('networklinkload', function(e, node, kmlObject){ equals(kmlObject.getName(), 'linka.kmz'); equals(kmlObject.getType(), 'KmlDocument', 'kmlObject is a KmlDocument'); equals($('.kmltreetest').find('span.name:contains(NetworkLink Content)').length, 1, 'NetworkLink contents displayed.'); equals(nlinkobject.getVisibility(), kmlObject.getVisibility()); var pmark = $('.kmltreetest').find('li:contains(NetworkLink Content) span.name:contains(Untitled Placemark)'); equals(pmark.length, 1); // toggling-off networklink toggles off linked document nlink.find('.toggler').click(); equals(nlinkobject.getVisibility(), false, 'NetworkLink visibility off'); equals(nlinkobject.getVisibility(), kmlObject.getVisibility(), 'Parent document visibility tracks NetworkLink visibility.'); // Events still work (testing double-click on tree node) pmark.dblclick(); setTimeout(function(){ var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(secondLat !== firstLat, 'Events on tree nodes should still function.'); tree.destroy(); $('.kmltreetest').remove(); start(); }, 400); }); nlink.find('>.expander').click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('getNetworkLink method', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var nlink = $('.kmltreetest').find('.name:contains(networklink a)').parent(); var doc = tree.lookup(nlink); equals(doc.getType(), 'KmlDocument'); equals(tree.getNetworkLink(nlink).getType(), 'KmlNetworkLink'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("NetworkLinks with listItemType=checkHideChildren don't expand", function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var nlink = $('.kmltreetest').find('span.name:contains(networklink checkHideChildren)').parent(); equals(nlink.find('>.expander:visible').length, 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("NetworkLinks with open=1 should automatically be loaded and expanded", function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('openNL.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, restoreState: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'Kmz loaded correctly'); var nlink = $('.kmltreetest').find('span.name:contains(open networklink)').parent(); ok(nlink.hasClass('loaded')); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("NetworkLinks with open=1 but with a style of checkHideChildren should not be expanded", function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('openCheckHideChildrenNL.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, restoreState: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'Kmz loaded correctly'); var nlink = $('.kmltreetest').find('span.name:contains(nl)').parent(); ok(!nlink.hasClass('loaded'), 'Not loaded'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // Depth-first traversal of all nodes in the tree // Will start out with all the children of the root KmlDocument, but // does not include the KmlDocument itself var walk = function(callback, context, node){ var recurse_ = function(node, context){ node.find('>ul>li').each(function(){ var el = $(this); var newcontext = callback(el, context); if(newcontext === false){ // Don't follow into child nodes return true; }else{ recurse_(el, newcontext); } }); }; // if(!node){ // node = opts.element.find('div.kmltree'); // } recurse_(node, context); }; earthAsyncTest("children ignored if callback returns false", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'Document loaded correctly'); var order = ''; walk(function(node){ var name = node.find('>span.name').text(); order += name; if(name === 'B'){ return false; } }, {}, $('.kmltreetest').find('div.kmltree')); equals(order, 'FJBGIH'); var order = ''; walk(function(node){ var name = node.find('>span.name').text(); order += name; if(name === 'D'){ return false; } }, {}, $('.kmltreetest').find('div.kmltree')); equals('FJBADGIH', order); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refresh tracks previous state', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(E)').parent().find('>.toggler').click(); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var E = $('.kmltreetest').find('span.name:contains(E)').parent(); ok(!E.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(E).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('more complex example', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(H)').parent().find('>.toggler').click(); $('.kmltreetest').find('span.name:contains(G)').parent().find('>.expander').click(); $('.kmltreetest').find('span.name:contains(A)').parent().find('>.toggler').click(); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); var H = $('.kmltreetest').find('span.name:contains(H)').parent(); var G = $('.kmltreetest').find('span.name:contains(G)').parent(); ok(!A.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(A).getVisibility(), 'Visibility set on kmlObject'); ok(!H.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(H).getVisibility(), 'Visibility set on kmlObject'); ok(!G.hasClass('visible'), 'History remembered in tree widget'); ok(!G.hasClass('open'), 'History remembered in tree widget'); ok(!tree.lookup(G).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refreshing twice has the same affect', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(H)').parent().find('>.toggler').click(); $('.kmltreetest').find('span.name:contains(G)').parent().find('>.expander').click(); $('.kmltreetest').find('span.name:contains(A)').parent().find('>.toggler').click(); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); var H = $('.kmltreetest').find('span.name:contains(H)').parent(); var G = $('.kmltreetest').find('span.name:contains(G)').parent(); ok(!A.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(A).getVisibility(), 'Visibility set on kmlObject'); ok(!H.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(H).getVisibility(), 'Visibility set on kmlObject'); ok(!G.hasClass('visible'), 'History remembered in tree widget'); ok(!G.hasClass('open'), 'History remembered in tree widget'); ok(!tree.lookup(G).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('history with networklinks', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('NLHistory.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); L.find('>.expander').click(); $(tree).one('networklinkload', function(){ var X = $('.kmltreetest').find('span.name:contains(X)').parent(); X.find('>.toggler').click(); ok(!X.hasClass('visible')); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); ok(L.hasClass('open'), 'Networklink open state remembered'); ok(!X.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(X).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('more complex history with networklinks', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('NLHistory.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); L.find('>.expander').click(); $(tree).one('networklinkload', function(){ var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var Z = $('.kmltreetest').find('span.name:contains(Z)').parent(); var Y = $('.kmltreetest').find('span.name:contains(Y)').parent(); X.find('>.toggler').click(); Y.find('>.toggler').click(); Z.find('>.toggler').click(); ok(!X.hasClass('visible')); ok(!Y.hasClass('visible')); ok(!Z.hasClass('visible')); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var Y = $('.kmltreetest').find('span.name:contains(Y)').parent(); var Z = $('.kmltreetest').find('span.name:contains(Z)').parent(); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); ok(L.hasClass('open'), 'Networklink open state remembered'); ok(!L.hasClass('visible'), 'L should not be visible since children are not'); ok(!X.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(X).getVisibility(), 'Visibility set on kmlObject'); ok(!Y.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(Y).getVisibility(), 'Visibility set on kmlObject'); ok(!Z.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(Z).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('history with nested networklinks', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('NLHistory.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); $(tree).one('networklinkload', function(){ $(tree).one('networklinkload', function(){ var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var Z = $('.kmltreetest').find('span.name:contains(Z)').parent(); var B = $('.kmltreetest').find('span.name:contains(B)').parent(); X.find('>.toggler').click(); B.find('>.toggler').click(); Z.find('>.toggler').click(); ok(!X.hasClass('visible')); ok(!B.hasClass('visible')); ok(!Z.hasClass('visible')); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var Y = $('.kmltreetest').find('span.name:contains(Y)').parent(); var B = $('.kmltreetest').find('span.name:contains(B)').parent(); var Z = $('.kmltreetest').find('span.name:contains(Z)').parent(); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); ok(L.hasClass('open'), 'Networklink open state remembered'); ok(L.hasClass('visible')); ok(!X.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(X).getVisibility(), 'Visibility set on kmlObject'); ok(Y.hasClass('open'), 'History remembered in tree widget'); ok(!B.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(B).getVisibility(), 'Visibility set on kmlObject'); ok(!Z.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(Z).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); var Y = $('.kmltreetest').find('span.name:contains(Y)').parent(); Y.find('>.expander').click(); }); L.find('>.expander').click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refreshing with 2 networklinks at root', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('2NLAtRoot.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(E)').parent().find('>.toggler').click(); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); var B = $('.kmltreetest').find('span.name:contains(B)').parent(); $(tree).one('networklinkload', function(){ $(tree).one('networklinkload', function(){ $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); ok(A.hasClass('loaded'), 'History remembered in tree widget'); var B = $('.kmltreetest').find('span.name:contains(B)').parent(); ok(B.hasClass('loaded'), 'History remembered in tree widget'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); B.find('>.expander').click(); }); A.find('>.expander').click(); }); window.tree = tree; ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refreshing with 2 networklinks at root - one has old-school Url tag', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('nlOldStyle.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, restoreState: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var working = $('.kmltreetest').find('span.name:contains(Working)').parent(); var old = $('.kmltreetest').find('span.name:contains(old)').parent(); ok(working.length); ok(old.length); ok(working.hasClass('open')); ok(old.hasClass('open')); $(tree).one('kmlLoaded', function(e, kmlObject){ var working = $('.kmltreetest').find('span.name:contains(Working)').parent(); var old = $('.kmltreetest').find('span.name:contains(old)').parent(); ok(old.hasClass('open')); ok(working.hasClass('open')); ok(working.hasClass('loaded')); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); window.tree = tree; ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('supports open networklinks even when refreshing with state', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('nlOldStyle.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, restoreState: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var working = $('.kmltreetest').find('span.name:contains(Working)').parent(); var old = $('.kmltreetest').find('span.name:contains(old)').parent(); ok(working.length); ok(old.length); ok(working.hasClass('open')); ok(old.hasClass('open')); working.find('>.toggler').click().click(); ok(working.find('>ul>li.visible').length > 1) $(tree).one('kmlLoaded', function(e, kmlObject){ var working = $('.kmltreetest').find('span.name:contains(Working)').parent(); var old = $('.kmltreetest').find('span.name:contains(old)').parent(); ok(old.hasClass('open')); ok(working.hasClass('open')); ok(working.hasClass('loaded')); ok(working.find('>ul>li.visible').length > 1) tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); window.tree = tree; ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('state tracking can be turned off', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(E)').parent().find('>.toggler').click(); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var E = $('.kmltreetest').find('span.name:contains(E)').parent(); ok(E.hasClass('visible')); ok(tree.lookup(E).getVisibility()); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('restore state using localStorage', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(E)').parent().find('>.toggler').click(); var E = $('.kmltreetest').find('span.name:contains(E)').parent(); ok(!E.hasClass('visible')); tree.destroy(); $('.kmltreetest').remove(); $(document.body).append('<div class="kmltreetest"></div>'); var tree2 = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), restoreStateOnRefresh: false, restoreState: true, bustCache: false }); $(tree2).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var E = $('.kmltreetest').find('span.name:contains(E)').parent(); ok(!E.hasClass('visible')); ok(!tree2.lookup(E).getVisibility()); tree2.destroy(); $('.kmltreetest').remove(); start(); }); tree2.load(true); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('multiple items with the same name supported', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('same-name test.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var show = $('.kmltreetest').find('span.name:contains(show)'); equals(show.length, 1, 'Item after two networklinks of the same name rendered.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('support for opening networklinks with relative paths', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('same-name test.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var firstNL = $($('.kmltreetest').find('span.name:contains(same name)')[0]).parent(); $(tree).one('networklinkload', function(){ tree.destroy(); $('.kmltreetest').remove(); start(); }); firstNL.find('.expander').click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('toggle behavior', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('toggle-behavior.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var parent = $($('.kmltreetest').find('span.name:contains(untoggled)')[0]).parent(); equals(parent.hasClass('visible'), false, 'Parent not visible'); var toggled = parent.find('>ul>li>span.name:contains(toggled):first').parent(); var untoggled = parent.find('>ul>li>span.name:contains(untoggled)').parent(); equals(toggled.length, 1); equals(untoggled.length, 1); equals(toggled.hasClass('visible'), true, 'toggled visible'); equals(untoggled.hasClass('visible'), false, 'untoggled not visible'); parent.find('>.toggler').click(); equals(toggled.hasClass('visible'), true, 'toggled visible'); equals(untoggled.hasClass('visible'), false, 'untoggled not visible'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayDocumentRoot option - false', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('pmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var doc = $($('.kmltreetest').find('span.name:contains(pmark.kml)')[0]).parent(); equals(doc.length, 0, 'Document root not shown'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayDocumentRoot option - auto - on', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('pmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: 'auto' }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var doc = $($('.kmltreetest').find('span.name:contains(pmark.kml)')[0]).parent(); equals(doc.length, 1, 'Document root not shown'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayDocumentRoot option - auto - off', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('clickEvents.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: 'auto' }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var doc = $($('.kmltreetest').find('span.name:contains(clickEvents.kml)')[0]).parent(); equals(doc.length, 0, 'Document root not shown'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayDocumentRoot option - true', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('clickEvents.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var doc = $($('.kmltreetest').find('span.name:contains(clickEvents.kml)')[0]).parent(); equals(doc.length, 1, 'Document root not shown'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('balloonopen event', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('clickEvents.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).one('balloonopen', function(e, b, kmlObject){ equals(b.getType(), 'GEFeatureBalloon'); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(Click Me)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // first test that kmltree can differenciate between popup types earthAsyncTest('displayEnhancedContent option - uses different methods for unsafe vs safe content', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals(balloon.getType(), 'GEFeatureBalloon'); equals($('#kmltree-balloon-iframe').length, 0, 'Basic popup not loaded into iframe.'); $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals(balloon.getType(), 'GEHtmlDivBalloon'); equals($('#kmltree-balloon-iframe').length, 1, 'Enhanced popup displayed in iframe sandbox.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); $('.kmltreetest').find('span.name:contains(no dynamic content)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayEnhancedContent option - is optional and turned off by default', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals(balloon.getType(), 'GEFeatureBalloon'); equals($('#kmltree-balloon-iframe').length, 0, 'No extra iframes since enhanced content is not shown.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayEnhancedContent option - sandboxedBalloonCallback works', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, sandboxedBalloonCallback: function(){ parent.postMessage('hi there', '*'); } }); $(window).bind('message', function(e){ var e = e.originalEvent; if(e.data.match(/width/)){ // just standard message passing for kmltree return; }else{ $(window).unbind('message'); equals(e.data, 'hi there'); tree.destroy(); $('.kmltreetest').remove(); start(); } }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals(balloon.getType(), 'GEHtmlDivBalloon'); equals($('#kmltree-balloon-iframe').length, 1, 'Enhanced popup displayed in iframe sandbox.'); }); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // test that a custom iframeSandbox option can be used earthAsyncTest('displayEnhancedContent option - custom iframeSandbox url', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, iframeSandbox: 'http://underbluewaters-try-unsafe-popups.googlecode.com/hg/src/iframe.html' }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals($('#map3d iframe[src="http://underbluewaters-try-unsafe-popups.googlecode.com/hg/src/iframe.html"]').length, 1); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); tree.load(true); }); // test that the size is correct earthAsyncTest('displayEnhancedContent option - dynamic height', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ ok($('#kmltree-balloon-iframe').height() > 200); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(large)') .click(); }); tree.load(true); }); // test that window.location type balloons get a default size earthAsyncTest('displayEnhancedContent option - content that sets window.location gets default balloon dimensions', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals($('#kmltree-balloon-iframe').height(), 450); equals($('#kmltree-balloon-iframe').width(), 530); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(window.location)') .click(); }); tree.load(true); }); // test that the default size can be changed earthAsyncTest('displayEnhancedContent option - unknownIframeDimensionsDefault setting', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, unknownIframeDimensionsDefault: {height: 45, width:53} }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals($('#kmltree-balloon-iframe').height(), 45); equals($('#kmltree-balloon-iframe').width(), 53); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(window.location)') .click(); }); tree.load(true); }); // unknownIframeDimensionsDefault as callable earthAsyncTest('displayEnhancedContent option - unknownIframeDimensionsDefault can be a callable', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, unknownIframeDimensionsDefault: function(kmlObject){ if(kmlObject.getType() === 'KmlPlacemark'){ return {height: 45, width:53}; }else{ return {height: 450, width:530}; } } }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals($('#kmltree-balloon-iframe').height(), 45); equals($('#kmltree-balloon-iframe').width(), 53); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(window.location)') .click(); }); tree.load(true); }); // test that remote and inline css is employed earthAsyncTest('displayEnhancedContent option - remote and inline css works as expected.', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, sandboxedBalloonCallback: function(){ setTimeout(function(){ // wait for remote css to load // - it's okay that this is async var message = ''; if($('#clock').css('text-decoration') === 'underline'){ message += 'inline css okay'; }else{ message += 'inline css failed'; } if($('#clock').css('background-color') === 'rgb(255, 0, 0)' || $('#clock').css('background-color') === 'red'){ message += ', remote css okay'; }else{ message += ', remote css failed'; } parent.postMessage(message, '*'); }, 500); } }); $(window).bind('message', function(e){ var e = e.originalEvent; if(e.data.match(/width/)){ // just standard message passing for kmltree return; }else{ $(window).unbind('message'); equals(e.data, 'inline css okay, remote css okay'); tree.destroy(); $('.kmltreetest').remove(); start(); } }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // test that remote and inline javascript is employed, and in the right // order earthAsyncTest('displayEnhancedContent option - remote and inline js works as expected.', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, iframeSandbox: 'http://underbluewaters-try-unsafe-popups.googlecode.com/hg/src/iframe.html', sandboxedBalloonCallback: function(){ var message = ''; if(typeof pv === 'object'){ message += 'remote js okay'; }else{ message += 'remote js failed'; } if(typeof window.copy_of_pv === 'object'){ message += ', inline js okay'; }else{ message += ', inline js failed'; } parent.postMessage(message, '*'); } }); $(window).bind('message', function(e){ var e = e.originalEvent; if(e.data.match(/width/)){ // just standard message passing for kmltree return; }else{ $(window).unbind('message'); equals(e.data, 'remote js okay, inline js okay'); tree.destroy(); $('.kmltreetest').remove(); start(); } }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // test that content can't get access to parent iframe's data - need to deploy? // TODO: change path to files earthAsyncTest("displayEnhancedContent option - sandboxed content shouldn't be able to access parent cookies and session info.", function(ge, gex){ document.cookie = 'somevalue'; $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, sandboxedBalloonCallback: function(){ if(window.stolenCookies){ var message = 'failed. cookie data stolen.'; }else{ var message = 'okay. cookie data not accessible.'; } parent.postMessage(message, '*'); } }); $(window).bind('message', function(e){ var e = e.originalEvent; if(e.data.match(/width/)){ // just standard message passing for kmltree return; }else{ $(window).unbind('message'); equals(e.data, 'okay. cookie data not accessible.'); tree.destroy(); $('.kmltreetest').remove(); start(); } }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(cookie)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // Make sure multiple instances of kmltree don't clobber each other's // popup window handling events earthAsyncTest("displayEnhancedContent option - multiple kmltrees can exist side-by-side.", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); $(document.body).append('<div class="kmltreetest2"></div>'); var tree1 = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); var tree2 = kmltree({ url: example('hi-js.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest2'), displayDocumentRoot: true, displayEnhancedContent: true, unknownIframeDimensionsDefault: {height: 330, width:330}, iframeSandbox: 'http://underbluewaters-try-unsafe-popups.googlecode.com/hg/src/iframe.html' }); var waiting = 2 var loaded = function(){ waiting--; if(waiting === 0){ $(tree1).one('balloonopen', function(e, balloon, kmlObject){ ok($('#kmltree-balloon-iframe').height() < 330); $(tree2).one('balloonopen', function(e, balloon, kmlObject){ ok($('#kmltree-balloon-iframe').height() > 200); tree1.destroy(); tree2.destroy(); $('.kmltreetest').remove(); $('.kmltreetest2').remove(); start(); }); $('.kmltreetest2').find('span.name:contains(Rotorua)') .click(); }); $('.kmltreetest').find('span.name:contains(large)') .click(); } } $(tree1).one('kmlLoaded', loaded); $(tree2).one('kmlLoaded', loaded); tree1.load(true); tree2.load(true); }); // combo example for expanded networklinks earthAsyncTest('displayEnhancedContent option - expanded networklinks can display sandboxed content too', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ // this example contains some other networklinks that automatically load, so wait until they are done setTimeout(function(){ $(tree).one('networklinkload', function(e, node, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ ok($('#kmltree-balloon-iframe').length === 1); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(enhanced content)').click() }); $('.kmltreetest').find('span.name:contains(networklink off)').parent().find('>.expander').click(); }, 1000); }); tree.load(true); }); earthAsyncTest('kmltreeManager - getOwner', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); $(document.body).append('<div class="kmltreetest2"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); var tree2 = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest2'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(){ $(tree2).one('kmlLoaded', function(e, kmlObject){ setTimeout(function(){ // Wait for networklink to load var hello = tree2.lookup($('.hello')); var jalama = ge.getElementByUrl('http://underbluewaters-try-better-selection-api.googlecode.com/hg/examples/kml/selection_3.kml#JAL'); equals(kmltreeManager.getOwner(jalama), tree, 'Jalama placemark belongs to tree 1. It is within an unexpanded networklink.'); equals(kmltreeManager.getOwner(hello), tree2, 'Hello placemark is within tree2'); tree.destroy(); tree2.destroy(); $('.kmltreetest').remove(); $('.kmltreetest2').remove(); start(); }, 2000); }); tree2.load(true); }); tree.load(true); }); })();
0corrina-kmltreeclone
tests/kmltree.js
JavaScript
bsd
121,528
(function(){ google.load("earth", "1"); // earthTest and earthAsyncTest // ============================ // // Use earthTest rather than QUnit::test for testing functionality that // requires an instance of the Google Earth Plugin and/or the // earth-api-utility-library. // // Test functions will be called with two arguments, the plugin instance // and the utility library. Here is an example: // // earthTest('Test grid', 1, function(ge, gex){ // equals(ge.getOptions().getGridVisibility(), true, // 'Grid should be visible.'); // }); // // For asynchronous tests, use earthAsyncTest as a replacement for // QUnit::testAsync: // // earthAsyncTest('Test parse kml', 1, function(ge, gex){ // $.get('/path/to/kml', function(data){ // var doc = ge.parseKml(data); // equals(doc.getName(), 'My Name'); // start(); // }); // }); // // When testing using asynchronous calls and the Earth Plugin it's // important to fill in the `expected` argument. Otherwise it can be // difficult to pin down which test caused an error. // // See the following for more information on using QUnit: // http://docs.jquery.com/QUnit // window.earthTest = function(name, expected, callback, async){ if ( arguments.length === 2 ) { callback = expected; expected = 0; } var new_function = function(){ if(ge && gex){ if(!async){ start(); } callback(ge, gex); }else{ initializePlugin(function(){ if(!async){ start(); } callback(ge, gex); }); } } asyncTest(name, expected, new_function); } window.earthAsyncTest = function(name, expected, callback){ if ( arguments.length === 2 ) { callback = expected; expected = 0; } earthTest(name, expected, callback, true); } var ge; var gex; function initializePlugin(callback){ var map = $(document.body).append('<div id="map3d"></div>'); $('#map3d').css({width:'400px', height: '200px', 'position': 'absolute', 'top': '-200px', 'right': '0px'}); google.earth.createInstance('map3d', function(plugin){ ge = plugin; gex = new GEarthExtensions(ge); callback(); }, googleEarthFailureCallback); } function googleEarthFailureCallback(){ alert('failed to load google earth plugin.'); } module('Custom Earth Test Cases'); var reference_to_first_google_earth_instance; earthAsyncTest('earthAsyncTest works', 2, function(ge, gex){ ok(typeof ge === 'object' || typeof ge === 'function', 'Google Earth Plugin initialized'); reference_to_first_google_earth_instance = ge; setTimeout(function(){ start(); ok(true === true, 'Additional asynchronous events can be run'); }, 1000); }); earthTest('only loads once', 1, function(ge, gex){ ok(ge === reference_to_first_google_earth_instance, 'Google Earth Plugin should initialize only once.'); }); })();
0corrina-kmltreeclone
tests/qunit_extensions.js
JavaScript
bsd
3,536
module('enableGoogleLayersControl'); (function(){ // given the name of a file within examples/kml, creates an absolute url // to it, appending ?r=revision if necessary function example(filename){ var url = '../examples/kml/' + filename; // var url = 'http://kmltree.googlecode.com/hg/examples/kml/' + filename; var r = getParameterByName('r'); if(r !== ''){ url = url + '?r=' + r; } return url; } var layers = {}; function Layer(name, initialState, type, layer_name_or_test, async){ this.name = name; this.initialState = initialState; this.layerName = layer_name_or_test; if(type === 'option'){ if(layer_name_or_test){ this.optionName = layer_name_or_test; }else{ this.optionName = name.replace(' ', ''); } } this.type = type; this.test = layer_name_or_test; this.async = async; } Layer.prototype.getEarthState = function(ge, tree, element){ switch(this.type){ case 'layer': return ge.getLayerRoot().getLayerById( ge[this.layerName]).getVisibility(); break; case 'option': return ge.getOptions()['get'+this.optionName+'Visibility'](); break; default: // special return this.test(ge); } } $.expr[":"].econtains = function(obj, index, meta, stack){ return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase(); } Layer.prototype.testState = function(ge, tree, element, initial){ var node = element.find( 'span.name:econtains('+this.name+')').parent(); equals(node.length, 1, 'Found node representing layer '+this.name); var kmlObject = tree.lookup(node); var earthState = this.getEarthState(ge, tree, element); // Check the status of the layer visibility ok((!!earthState === (this.initialState === initial)), 'GE State - Layer ' + this.name + ' should have ' + (initial ? 'an initial ' : 'a') + ' state = ' + (this.initialState === initial)); // Check the status of the node representing the layer in the loaded // kml file ok((!!kmlObject.getVisibility() === (this.initialState === initial)), 'Tree Node kmlObject - Layer ' + this.name + ' should have ' + (initial ? 'an initial' : 'a') + ' state = ' + (this.initialState === initial)); // Check the toggle state of the ui ok((node.hasClass('visible') === (this.initialState === initial)), 'Toggle state of UI matches DOM. Toggle state should be = ' + (this.initialState === initial)); }; Layer.prototype.testInitialState = function(ge, tree, element){ this.testState(ge, tree, element, true); }; Layer.prototype.testOpposingState = function(ge, tree, element){ this.testState(ge, tree, element, false); }; function Runner(url){ this.url = url; this.layers = []; }; Runner.prototype.test = function(type, name, initial_state, name_or_test, async){ this.layers.push(new Layer(name, initial_state, type, name_or_test, async)); }; Runner.prototype.testOption = function(name, initial_state, name_or_test){ this.test('option', name, initial_state, name_or_test); }; Runner.prototype.testLayer = function(name, initial_state, name_or_test){ this.test('layer', name, initial_state, name_or_test); }; Runner.prototype.testSpecial = function(name, initial_state, name_or_test, async){ this.test('special', name, initial_state, name_or_test, async); }; Runner.prototype.run = function(){ var layers = this.layers; var url = this.url; for(var i = 0; i < this.layers.length; i++) (function(i){ var layer = layers[i]; earthAsyncTest(layer.name, function(ge, gex){ var layer = layers[i]; $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example(url), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: true, supportItemIcon: true }); enableGoogleLayersControl(tree, ge); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); layer.testState(ge, tree, $('.kmltreetest'), true); var node = $('.kmltreetest').find('span.name:econtains('+layer.name+')').parent(); node.find('> .toggler').click(); if(layer.async){ setTimeout(function(){ layer.testState(ge, tree, $('.kmltreetest'), false); tree.destroy(); $('.kmltreetest').remove(); start(); }, 1000); }else{ layer.testState(ge, tree, $('.kmltreetest'), false); tree.destroy(); $('.kmltreetest').remove(); start(); } }); ok(tree !== false, 'Tree initialized'); tree.load(); }); })(i); }; Runner.prototype.runRefreshTest = function(){ var that = this; earthAsyncTest('Refresh test on '+this.url, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example(that.url), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: true, supportItemIcon: true, refreshWithState: true }); enableGoogleLayersControl(tree, ge); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); for(var i = 0; i < that.layers.length; i++){ var layer = that.layers[i]; layer.testState(ge, tree, $('.kmltreetest'), true); var node = $('.kmltreetest').find('span.name:econtains('+layer.name+')').parent(); node.find('> .toggler').click(); if(!layer.async){ layer.testState(ge, tree, $('.kmltreetest'), false); } } $(tree).one('kmlLoaded', function(e, kmlObject){ for(var i = 0; i < that.layers.length; i++){ var layer = that.layers[i]; if(!layer.async){ layer.testState(ge, tree, $('.kmltreetest'), false); } } tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(); }); }; var r = new Runner('displayOptions.kml'); r.testOption('Scale Legend', false); r.testOption('Status Bar', true); r.testOption('Overview Map', false); r.testOption('Atmosphere', true); r.testSpecial('Street View', true, function(ge){ return ge.getNavigationControl().getStreetViewEnabled(); }); r.testLayer('3d Terrain and Ocean Surface', true, 'LAYER_TERRAIN'); r.testSpecial('Sun', false, function(ge){ return ge.getSun().getVisibility(); }); r.testSpecial('Historical Imagery', false, function(ge){ return ge.getTime().getHistoricalImageryEnabled(); }, true); r.testSpecial('Navigation Controls', true, function(ge){ return ge.getNavigationControl().getVisibility() === ge.VISIBILITY_SHOW; }); r.run(); r.runRefreshTest(); var r = new Runner('includedLayers.kml'); r.testLayer('Roads', false, 'LAYER_ROADS'); r.testLayer('3d Trees', false, 'LAYER_TREES'); r.testLayer('Borders and Labels', false, 'LAYER_BORDERS'); r.testLayer('3d Buildings', false, 'LAYER_BUILDINGS'); r.testLayer('Low Resolution 3d Buildings', false, 'LAYER_BUILDINGS_LOW_RESOLUTION'); r.run(); r.runRefreshTest(); })()
0corrina-kmltreeclone
tests/googleLayers.js
JavaScript
bsd
8,884
module('micro-templating'); test("list template", 1, function(){ template = [ "<ul>", "<% for (var i=0; i < users.length; i++) { %>", "<li><%= users[i].name %></li>", "<% } %>", "</ul>" ]; template = template.join(""); list_users = tmpl(template); data = {users: [{name:'me'}, {name: 'myself'}]} equals(list_users(data), "<ul><li>me</li><li>myself</li></ul>"); });
0corrina-kmltreeclone
tests/tmpl.js
JavaScript
bsd
445
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>kmltree Test Suite</title> <!-- You will need these 4 files included in your test case --> <link rel="stylesheet" href="http://js-ci-tools.appspot.com/qunit/qunit.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../dist/kmltree.css" type="text/css" media="screen" title="no title" charset="utf-8"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <!-- <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRQPjtdHQ3xdBuNAR-KDFOW1mqdVsRRmZhmrl-MOSGS44M9Gug9FdssEgQ"></script> --> <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAbEBR9v0lqBFdTfOcbe5WjRSwtTT5GAxiJqzQ69gC1VuJs9XrFRSHtkp9BFyAR6_lVVfY3MBP3uA7Mg"></script> <script src="http://geojs.googlecode.com/svn/trunk/dist/geo.pack.js" type="text/javascript" charset="utf-8"></script> <script src="http://earth-api-utility-library.googlecode.com/svn/trunk/extensions/dist/extensions.pack.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" src="http://js-ci-tools.appspot.com/qunit/qunit.js"></script> <script src="http://js-ci-tools.appspot.com/js/logger.js" type="text/javascript" charset="utf-8"></script> <script src="qunit_extensions.js" type="text/javascript" charset="utf-8"></script> <script src="../dist/kmltree.min.js" type="text/javascript" charset="utf-8"></script> <!-- Tests --> <script src="../tests/tmpl.js" type="text/javascript" charset="utf-8"></script> <script src="../tests/kmldom.js" type="text/javascript" charset="utf-8"></script> <script src="../tests/kmltree.js" type="text/javascript" charset="utf-8"></script> <script src="../tests/googleLayers.js" type="text/javascript" charset="utf-8"></script> <script> $(document).ready(function(){ }); </script> </head> <body> <h1 id="qunit-header">kmltree Test Suite</h1> <h2 id="qunit-banner"></h2> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> </body> </html>
0corrina-kmltreeclone
tests/index.html
HTML
bsd
2,352
require 'rake/clean' CLEAN.include('dist/kmltree.css', 'dist/kmltree.min.js', 'dist/kmltree.js', 'dist/images', 'src/_sprites.sass', 'sprites-url') CLOBBER.include('compiler') SRC = FileList[ 'src/kmltreeManager.js', 'src/base64.js', 'src/tmpl.js', 'src/kmldom.js', 'src/URI.js', 'src/kmltree.js', 'src/googleLayers.js'] task :default => ["kmltree.tar.gz"] file "kmltree.tar.gz" => ["dist/kmltree.css", "dist/kmltree.min.js", "dist/images"] do sh "cp -r dist kmltree" sh "tar -pczf kmltree.tar.gz kmltree" sh "rm -rf kmltree" end file "dist/kmltree.css" => ["clean", "src/main.sass", "src/_sprites.sass"] do sh "sass src/main.sass dist/kmltree.css" sh "sed 's:/sprites-url/::' dist/kmltree.css > out" rm "dist/kmltree.css" mv "out", "dist/kmltree.css" end file "src/_sprites.sass" => ['config/sprite.yml'] do sh "sprite" end file "dist/kmltree.min.js" => ['dist/kmltree.js', 'compiler/compiler.jar'] do cmd = "java -jar compiler/compiler.jar " cmd << "--js dist/kmltree.js " cmd << "--js_output_file dist/kmltree.min.js " cmd << "--create_source_map ./kmltree.map" sh cmd end file "compiler/compiler.jar" do mkdir "compiler" cd "compiler" url = "http://closure-compiler.googlecode.com/files/compiler-latest.zip" sh "curl -O #{url}" sh "unzip compiler-latest.zip" cd "../" end file "dist/kmltree.js" do cmd = 'cat' SRC.each do |f| cmd << " #{f}" end cmd << " > dist/kmltree.js" sh cmd end file "dist/images" => ["src/_sprites.sass"] do sh "cp -r src/sprites-url/images dist/" sh "rm -rf src/sprites-url" sh "cp src/images/ajax-loader.gif dist/images/" sh "cp src/images/networklink-loading-animated.gif dist/images/" end
0corrina-kmltreeclone
Rakefile
Ruby
bsd
1,690
<?/* PHP */?> <?/* end of PHP */?>
03-k64
trunk/index.php
PHP
gpl2
35
/* JS */
03-k64
trunk/js/main.js
JavaScript
gpl2
8
/* CSS */
03-k64
trunk/css/main.css
CSS
gpl2
9
#!/bin/sh # Parameters passed: # $1: full path to the installation package (xxx.pkg) # $2: full path to destination (/) # $3: mountpoint of destination volume (/) # $4: root directory for current system folder (/) # Uninstall previous null driver if [ -d /System/Library/Extensions/ez430rf2500.kext ] then rm -rf /System/Library/Extensions/ez430rf2500.kext fi exit 0
100jed-lukemccurlie
package/Resources/postflight
Shell
gpl2
371
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf360 {\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset0 LucidaGrande;} {\colortbl;\red255\green255\blue255;} {\*\listtable{\list\listtemplateid1\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid1\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid1} {\list\listtemplateid2\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid101\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid2} {\list\listtemplateid3\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid201\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid3}} {\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}{\listoverride\listid2\listoverridecount0\ls2}{\listoverride\listid3\listoverridecount0\ls3}} \paperw11900\paperh16840\margl1440\margr1440\vieww13920\viewh11680\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\qc\pardirnatural \f0\b\fs34 \cf0 Welcome to the MSP430 LaunchPad toolchain installer! \b0\fs24 \ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural \cf0 \ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural \fs28 \cf0 \ul \ulc0 Please read on to know what this installer is doing to your computer\ulnone . Scroll all the way down for what's new.\ \ This package automates the process of installing the GCC toolchain for the MSP430 LaunchPad development board. The following software will be installed (hit \f1\b \uc0\u8984 - \f0 I \b0 for details):\ \ \pard\tx220\tx720\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\li720\fi-720\ql\qnatural\pardirnatural \ls1\ilvl0\cf0 {\listtext \'95 } \b gcc-4.5.3 \b0 GNU C/C++ Compiler\ \pard\tx220\tx720\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\li720\fi-720\ql\qnatural\pardirnatural \ls1\ilvl0 \b \cf0 {\listtext \'95 }binutils-2.21.1 \b0 GNU binutils \b \ {\listtext \'95 }gdb-7.2a \b0 GNU Debugger\ \ls1\ilvl0 \b {\listtext \'95 }msp430-libc-20110612 \b0 MSP430 standard C library\ \ls1\ilvl0 \b {\listtext \'95 }msp430mcu-20110613 \b0 MSP430 specs\ {\listtext \'95 } \b mspdebug 0.17 \b0 and libusb\ \pard\tx560\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural \cf0 \ A proper VCP driver is required to communicate with the LaunchPad. See: {\field{\*\fldinst{HYPERLINK "http://www.43oh.com/2011/10/launchpad-osx-usb-cdc-vcp-driver-released/"}}{\fldrslt http://www.43oh.com/2011/10/launchpad-osx-usb-cdc-vcp-driver-released/}}. \b You have to install this driver separately \b0 .\ \ The older ez430rf2500.kext driver is no longer required for mspdebug to properly recognize the LaunchPad board, so it will be automatically removed upon install (if you ever installed it, that is).\ \ Both the toolchain and mspdebug will be installed in /usr/local. In addition, the installer will add the path to the toolchain binaries to your /etc/profile.\ \ Multiple versions of the toolchain can peacefully coexist. A symlink named /usr/local/msp430-toolchain switches among toolchains.\ \ This package does not provide an easy way to uninstall. If you wish to remove the toolchain, google for "lsbom uninstall" and follow the procedure while optionally shrieking curses upon Apple's immature packaging system.\ \ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\qc\pardirnatural \b\fs34 \cf0 What's new: \b0\fs24 \ \pard\tx560\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural \fs28 \cf0 \ version 20111101:\ \pard\tx220\tx720\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\li720\fi-720\ql\qnatural\pardirnatural \ls2\ilvl0\cf0 {\listtext \'95 }latest uniarch build. \ \pard\tx560\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural \cf0 version 20101112:\ \pard\tx220\tx720\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\li720\fi-720\ql\qnatural\pardirnatural \ls3\ilvl0\cf0 {\listtext \'95 }mspdebug no longer needs replugging to detect the board (upgrade to git's commit 3b4989b1 - Oct-28, 2010).}
100jed-lukemccurlie
package/Resources/Welcome.rtf
Rich Text Format
gpl2
4,718
#!/bin/sh set -e # Force root if [ $EUID -ne 0 ]; then echo "You must be root" exit 1 fi TOOLCHAIN_VERSION=20110716 PREFIX=/usr/local/msp430-uniarch-$TOOLCHAIN_VERSION PACKAGE_ROOT=package/PackageRoot # Add new gcc to path export PATH=$PREFIX/bin:$PATH : <<ENDREM Use these to wrap around code you want to comment out, in case some step failed and you want to resume execution at some point. ENDREM # Download mspgcc4 patches wget http://downloads.sourceforge.net/project/mspgcc/mspgcc/mspgcc-$TOOLCHAIN_VERSION.tar.bz2 tar xjf mspgcc-$TOOLCHAIN_VERSION.tar.bz2 # Install binutils wget ftp://ftp.gnu.org/pub/gnu/binutils/binutils-2.21.1.tar.bz2 tar xjf binutils-2.21.1.tar.bz2 cd binutils-2.21.1 patch -p1 < ../mspgcc-$TOOLCHAIN_VERSION/msp430-binutils-2.21.1-20110716.patch cd .. mkdir -p BUILD/binutils cd BUILD/binutils ../../binutils-2.21.1/configure \ --target=msp430 \ --prefix=$PREFIX make make install cd ../.. # Install gcc wget ftp://ftp.gnu.org/pub/gnu/gcc/gcc-4.5.3/gcc-4.5.3.tar.bz2 tar xjf gcc-4.5.3.tar.bz2 cd gcc-4.5.3 patch -p1 < ../mspgcc-$TOOLCHAIN_VERSION/msp430-gcc-4.5.3-20110706.patch cd .. mkdir -p BUILD/gcc cd BUILD/gcc ../../gcc-4.5.3/configure \ --target=msp430 \ --enable-languages=c,c++ \ --prefix=$PREFIX make make install cd ../.. # Install gdb wget ftp://ftp.gnu.org/pub/gnu/gdb/gdb-7.2a.tar.gz tar xzf gdb-7.2a.tar.gz cd gdb-7.2 patch -p1 < ../mspgcc-$TOOLCHAIN_VERSION/msp430-gdb-7.2-20110103.patch cd .. mkdir -p BUILD/gdb cd BUILD/gdb ../../gdb-7.2/configure \ --target=msp430 \ --prefix=$PREFIX make make install cd ../.. # Install mcu MCU_VERSION=`cat mspgcc-$TOOLCHAIN_VERSION/msp430mcu.version` wget http://sourceforge.net/projects/mspgcc/files/msp430mcu/msp430mcu-$MCU_VERSION.tar.bz2 tar xjf msp430mcu-$MCU_VERSION.tar.bz2 cd msp430mcu-$MCU_VERSION export MSP430MCU_ROOT=`pwd` sh scripts/install.sh $PREFIX cd .. # Install libc LIBC_VERSION=`cat mspgcc-$TOOLCHAIN_VERSION/msp430-libc.version` wget http://sourceforge.net/projects/mspgcc/files/msp430-libc/msp430-libc-$LIBC_VERSION.tar.bz2 tar xjf msp430-libc-$LIBC_VERSION.tar.bz2 cd msp430-libc-$LIBC_VERSION/src rm -rf Build make PREFIX=$PREFIX make PREFIX=$PREFIX install cd ../.. # Install mspdebug wget http://downloads.sourceforge.net/project/mspdebug/mspdebug-0.17.tar.gz tar xvf mspdebug-0.17.tar.gz cd mspdebug-0.17 patch -p1 < ../mspdebug-0.17.patch make make install ## Create package # Toolchain rm -rf $PACKAGE_ROOT mkdir $PACKAGE_ROOT mkdir -p $PACKAGE_ROOT/$PREFIX cp -a $PREFIX/ $PACKAGE_ROOT/$PREFIX # Mspdebug mkdir -p $PACKAGE_ROOT/usr/local/bin mkdir -p $PACKAGE_ROOT/usr/local/share/man/man1 cp -p /usr/local/bin/mspdebug $PACKAGE_ROOT/usr/local/bin cp -p /usr/local/share/man/man1/mspdebug.1 $PACKAGE_ROOT/usr/local/share/man/man1 # Libs mkdir -p $PACKAGE_ROOT/usr/local/lib for i in charset.alias libelf* libgmp* libiconv* libmpc* libmpfr* libnet* libusb* do cp -p /usr/local/lib/$i $PACKAGE_ROOT/usr/local/lib done # Paths mkdir -p $PACKAGE_ROOT/private/etc/paths.d mkdir -p $PACKAGE_ROOT/private/etc/manpaths.d echo "/usr/local/msp430-toolchain/bin" >$PACKAGE_ROOT/private/etc/paths.d/msp430-toolchain echo "/usr/local/msp430-toolchain/share/man" >$PACKAGE_ROOT/private/etc/manpaths.d/msp430-toolchain # Symlink ln -s $PREFIX $PACKAGE_ROOT/usr/local/msp430-toolchain # Perms chown -R root:wheel $PACKAGE_ROOT
100jed-lukemccurlie
build.sh
Shell
gpl2
3,371
package constants; import client.Command; public class Constants { public static enum Color{ blue, red, green, cyan, magenta, orange, pink, yellow } // Order of enum important for determining opposites public static enum dir { N, W, E, S }; public static dir oppositeDir(dir d){ if(d== dir.N) return dir.S; else if(d == dir.E) return dir.W; else if(d == dir.W) return dir.E; else return dir.N; } public static Command NOOP = new Command("NoOp"); }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/constants/Constants.java
Java
oos
495
package client; import java.util.LinkedList; import constants.Constants.*; public class Command { static { LinkedList< Command > cmds = new LinkedList< Command >(); for ( dir d : dir.values() ) { cmds.add( new Command( d ) ); } for ( dir d1 : dir.values() ) { for ( dir d2 : dir.values() ) { if ( !Command.isOpposite( d1, d2 ) ) { cmds.add( new Command( "Push", d1, d2 ) ); } } } for ( dir d1 : dir.values() ) { for ( dir d2 : dir.values() ) { if ( d1 != d2 ) { cmds.add( new Command( "Pull", d1, d2 ) ); } } } every = cmds.toArray( new Command[0] ); } public final static Command[] every; private static boolean isOpposite( dir d1, dir d2 ) { return d1.ordinal() + d2.ordinal() == 3; } public String cmd; public dir dir1; public dir dir2; public Command( dir d ) { cmd = "Move"; dir1 = d; } public Command(String s) { if (s.toLowerCase().equals("noop")) cmd = "NoOp"; cmd = "NoOp"; // Are there others? } public Command( String s, dir d1, dir d2 ) { cmd = s; dir1 = d1; dir2 = d2; } public String toString() { if ( dir1 == null ) return cmd; else if ( dir2 == null) return cmd + "(" + dir1 + ")"; return cmd + "(" + dir1 + "," + dir2 + ")"; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/Command.java
Java
oos
1,265
package client; public enum Action { MoveEast, MoveWest, MoveNorth, MoveSouth, PushNW, PushW, PushSW, PushS, PushSE, PushE, PushNE, PushN, PullNW, PullW, PullSW, PullS, PullSE, PullE, PullNE, PullN, NoOp }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/Action.java
Java
oos
252
package client.planners; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Random; import utils.FindFreeSpaces; import utils.GoalPriority; import constants.Constants; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.State; public class GoalCountPlanner implements Planner { Level level; Random rand; HashMap<String, ArrayList<String>> closedSet; private static final String name = "GoalCountPlanner"; @Override public String getName() { return name; } public GoalCountPlanner(Level l) { this.level = l; rand = new Random(); GoalPriority.createGoalPrioritization(level, true); // FindFreeSpaces.FindSpaces(level); } public void makePlan() { State firstState = new State(); closedSet = new HashMap<String, ArrayList<String>>(); { ArrayList<String> newList = new ArrayList<String>(); String[] startIdentifier = getIdentifierStringForState(firstState); newList.add(startIdentifier[1]); closedSet.put(startIdentifier[0], newList); } for (Agent a : level.agents) { firstState.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : level.boxes) { firstState.boxes.add(new BoxInState(b, b.getAtField())); } PriorityQueue<State> stateQueue = new PriorityQueue<State>(); stateQueue.add(firstState); State currentState = stateQueue.poll(); while (currentState != null && !allBoxesAtGoals(currentState)) { ArrayList<ArrayList<Command>> c = getCommandsForCurrentState(currentState); ArrayList<State> newStatesFromCommands = getNewStatesFromCommands( currentState, c); for (State state : newStatesFromCommands) { String[] identifierString = getIdentifierStringForState(state); // System.err.println(identifierString[0] + "\t" + identifierString[1]); if (closedSet.keySet().contains(identifierString[0])) { if (closedSet.get(identifierString[0]).contains( identifierString[1])) { continue; // This means that we already have met this // state. We continue to the next possible // state. } else { closedSet.get(identifierString[0]).add( identifierString[1]); } } else { ArrayList<String> newList = new ArrayList<String>(); newList.add(identifierString[1]); closedSet.put(identifierString[0], newList); } state.parent = currentState; stateQueue.add(state); } currentState = stateQueue.poll(); } System.err.println("Number of explored agent states: " + closedSet.size()); int counter = 0; for (ArrayList<String> agentState : closedSet.values()) { counter += agentState.size(); } System.err.println("Number of combined states: " + counter); ArrayList<ArrayList<Command>> commands = new ArrayList<ArrayList<Command>>(); if (currentState == null) { System.err.println("Level cannot be solved!"); System.exit(0); } while (currentState != null) { commands.add(currentState.commandFromParent); currentState = currentState.parent; } Collections.reverse(commands); for (ArrayList<Command> arrayList : commands) { int agentIndex = 0; for (int i = 0; i < arrayList.size(); i++) { Command command = arrayList.get(i); level.agents.get(agentIndex).commandQueue.add(command); agentIndex++; } } } private ArrayList<ArrayList<Command>> getCommandsForCurrentState( State currentState) { ArrayList<ArrayList<Command>> returnCommands = new ArrayList<ArrayList<Command>>(); for (AgentInState a : currentState.agents) { ArrayList<Command> cmds = addPossibleCommandsForAgent(a, currentState); returnCommands.add(cmds); } return returnCommands; } private ArrayList<State> getNewStatesFromCommands(State currentState, ArrayList<ArrayList<Command>> c) { ArrayList<State> returnStates = new ArrayList<State>(); // Code here int index = 0; for (ArrayList<Command> arrayList : c) { for (Command command : arrayList) { State newState = new State(); addCommandToState(command, currentState.agents.get(index), newState, currentState); newState.commandFromParent.add(command); newState.heuristicValue = getHeuristicEstimate(newState); for (int i = 0; i < c.size(); i++) { if (i != index) { for (Command commandOfOtherAgent : c.get(i)) { addCommandToState(commandOfOtherAgent, currentState.agents.get(i), newState, currentState); // BE SURE THAT ORDER CORRESPONDS TO AGENTS! newState.commandFromParent.add(commandOfOtherAgent); } } } returnStates.add(newState); } index++; } return returnStates; } private int getHeuristicEstimate(State newState) { int count = 0; ArrayList<Box> usedBoxes = new ArrayList<Box>(); for (Goal g : level.goals) { BoxInState bestBox = newState.boxes.get(0); for (BoxInState b : newState.boxes) { if (!usedBoxes.contains(b.b) && g.getId() == Character.toLowerCase(b.b.getId()) && heuristicDistance(b.f, g) < heuristicDistance(bestBox.f, g) ){ bestBox = b; usedBoxes.add(b.b); } } if ( !(bestBox.f instanceof Goal && ((Goal) bestBox.f).getId() == Character.toLowerCase(bestBox.b.getId()))) { count += heuristicDistance(bestBox.f, g); //TODO Make this work with multi-agents count += heuristicDistance(newState.agents.get(0).f, bestBox.f); } } // try { // Thread.sleep(500); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // count -= (noOfGoalsFulfilled(newState) * 5); // System.err.println(Arrays.toString(getIdentifierStringForState(newState))); // System.err.println(count); return count; } private int heuristicDistance(Field a, Field goal) { return heuristicDistanceManhattan(a, goal); } private int heuristicDistanceEuclid(Field a, Field goal) { int h = (int) Math.sqrt(Math.pow(Math.abs(a.x - goal.x), 2) + Math.pow(Math.abs(a.y - goal.y), 2)); return h; } // Manhattan distance private int heuristicDistanceManhattan(Field a, Field goal) { int h = (int) Math.abs(a.x - goal.x) + Math.abs(a.y - goal.y); return h; } private void addCommandToState(Command command, AgentInState aPos, State newState, State currentState) { for (BoxInState bPos : currentState.boxes) { newState.boxes.add(new BoxInState(bPos.b, bPos.f)); } if (command.cmd.equals("Move")) { newState.agents.add(new AgentInState(aPos.a, aPos.f.neighbours[command.dir1.ordinal()])); } else if (command.cmd.equals("Pull")) { for (BoxInState bPos : newState.boxes) { if (aPos.f.neighbours[command.dir2.ordinal()] == bPos.f) { bPos.f = aPos.f; newState.agents.add(new AgentInState(aPos.a, aPos.f.neighbours[command.dir1.ordinal()])); } } } else if (command.cmd.equals("Push")) { for (BoxInState bPos : newState.boxes) { if (aPos.f.neighbours[command.dir1.ordinal()] == bPos.f) { // newState.boxes.add(new BoxPosInState(bPos.b, // bPos.f.neighbours[command.dir2.ordinal()])); newState.agents.add(new AgentInState(aPos.a, bPos.f)); bPos.f = bPos.f.neighbours[command.dir2.ordinal()]; } } } } public ArrayList<Command> addPossibleCommandsForAgent(AgentInState aPos, State currentState) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); Field agentLocationInPlan = aPos.f; // Commented because we are not interested in move commands at current // time. for (dir direction : dir.values()) { if (neighbourFreeInState( agentLocationInPlan.neighbours[direction.ordinal()], currentState)) { possibleCommands.add(new Command(direction)); } // Find possible pull and push commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction if (d != direction && neighbourIsBoxOfSameColourInState( agentLocationInPlan.neighbours[d.ordinal()], currentState, aPos) && neighbourFreeInState( agentLocationInPlan.neighbours[direction .ordinal()], currentState)) { possibleCommands.add(new Command("Pull", direction, d)); } // We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && neighbourIsBoxOfSameColourInState( agentLocationInPlan.neighbours[d.ordinal()], currentState, aPos) && neighbourFreeInState( agentLocationInPlan.neighbours[d.ordinal()].neighbours[direction .ordinal()], currentState)) { possibleCommands.add(new Command("Push", d, direction)); } } } return possibleCommands; } private boolean allBoxesAtGoals(State currentState) { boolean[] boxAtGoalArray = new boolean[level.goals.size()]; int index = 0; for (Goal g : level.goals) { for (BoxInState bPos : currentState.boxes) { if (bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { boxAtGoalArray[index] = true; } } index++; } boolean returnBool = true; for (boolean b : boxAtGoalArray) { if (!b) return false; } return returnBool; } private int noOfGoalsFulfilled(State currentState){ boolean[] boxAtGoalArray = new boolean[level.goals.size()]; int index = 0; for (Goal g : level.goals) { for (BoxInState bPos : currentState.boxes) { if (bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { boxAtGoalArray[index] = true; } } index++; } int counter = 0; for (boolean b : boxAtGoalArray) { if (b) counter++; } return counter; } private boolean neighbourFreeInState(Field f, State s) { if (f == null) return false; boolean fieldFree = true; for (AgentInState aPos : s.agents) { if (aPos.f == f) fieldFree = false; } for (BoxInState bPos : s.boxes) { if (bPos.f == f) fieldFree = false; } return fieldFree; } private boolean neighbourIsBoxOfSameColourInState(Field f, State s, AgentInState a) { if (f == null) return false; for (BoxInState bPos : s.boxes) { if (bPos.f == f && bPos.b.getColor() == a.a.getColor()) { return true; } } return false; } private String[] getIdentifierStringForState(State s) { String[] returnString = new String[2]; AgentInState[] agentArray = new AgentInState[s.agents.size()]; for (int i = 0; i < s.agents.size(); i++) { agentArray[i] = s.agents.get(i); } Arrays.sort(agentArray); String agentString = ""; for (AgentInState aPos : s.agents) { agentString += aPos.f.x + "." + aPos.f.y + aPos.a.getColor(); } BoxInState[] boxArray = new BoxInState[s.boxes.size()]; for (int i = 0; i < s.boxes.size(); i++) { boxArray[i] = s.boxes.get(i); } Arrays.sort(boxArray); String boxString = ""; for (BoxInState box : boxArray) { boxString += box.f.x + "."+ box.f.y + box.b.getId(); } returnString[0] = agentString; returnString[1] = boxString; return returnString; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/planners/GoalCountPlanner.java
Java
oos
11,388
package client.planners; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Random; import java.util.Set; import constants.Constants.dir; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import client.Desire; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class ProgressionWithHeuristic implements Planner { Level level; Random rand; private static final String name = "ProgressionPlannerWithHeurustic"; @Override public String getName() { return name; } public ProgressionWithHeuristic(Level l) { this.level = l; rand = new Random(); } public void makePlan() { System.err.println("Make plan!"); State firstState = Utils.getState(level.agents, level.boxes); PriorityQueue<State> stateQueue = new PriorityQueue<State>(); HashMap<ArrayList<Field>, ArrayList<ArrayList<Field>>> closedSet = new HashMap<ArrayList<Field>, ArrayList<ArrayList<Field>>>(); stateQueue.add(firstState); ArrayList<Field> agentPositions = new ArrayList<Field>(); for (AgentInState a : firstState.agents) { agentPositions.add(a.f); } ArrayList<Field> boxPositions = new ArrayList<Field>(); for (BoxInState b : firstState.boxes) { boxPositions.add(b.f); } closedSet.put(agentPositions, new ArrayList<ArrayList<Field>>()); closedSet.get(agentPositions).add(boxPositions); State currentState = stateQueue.poll(); while (currentState != null && !Utils.allGoalsHasBoxes(currentState,level)) { //Start by finding the possible actions. ArrayList<State> newStates = findPossibleActions(currentState); for (State state : newStates) { ArrayList<Field> tempAgentPositions = new ArrayList<Field>(); for (AgentInState a : state.agents) tempAgentPositions.add(a.f); ArrayList<Field> tempBoxPositions = new ArrayList<Field>(); for (BoxInState b : state.boxes) tempBoxPositions.add(b.f); //Pruning of states. if (closedSet.containsKey(tempAgentPositions)) { if (closedSet.get(tempAgentPositions).contains(tempBoxPositions)) { continue; } else{ closedSet.get(tempAgentPositions).add(tempBoxPositions); } } else{ closedSet.put(tempAgentPositions, new ArrayList<ArrayList<Field>>()); closedSet.get(tempAgentPositions).add(tempBoxPositions); } stateQueue.add(state); } currentState = stateQueue.poll(); } if (currentState == null) return; ArrayList<State> states = new ArrayList<State>(); while (currentState != null) { states.add(states.size(), currentState); currentState = currentState.parent; } Collections.reverse(states); for (State state : states) { for (ActionSequence actionSequence : state.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { System.err.println(command.toString()); level.agents.get(0).commandQueue.add(command); //Should be changed to work with multi-agents } } } } private ArrayList<State> findPossibleActions(State currentState){ ArrayList<State> returnStates = new ArrayList<State>(); for (AgentInState a : currentState.agents) { for (BoxInState b : currentState.boxes) { //Continue if the agent does not match the box or the box is at it's goal if (b.b.getColor() != a.a.getColor() || (b.f instanceof Goal && Character.toLowerCase(b.b.getId()) == ((Goal) b.f).getId() )) continue; ArrayList<Field> blockedFields = new ArrayList<Field>(); for (AgentInState agent : currentState.agents) { if(agent != a) blockedFields.add(agent.f); } for (BoxInState box : currentState.boxes) { blockedFields.add(box.f); } for (dir d : dir.values()) { if(b.f.neighbours[d.ordinal()] != null){ //The following line will not find a path to adjacent boxes. MoveActionSequence moveAction = Utils.findRoute(level, a.f, b.f.neighbours[d.ordinal()], blockedFields); if (moveAction != null) { //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(b.f); for (Goal goal : level.goals) { if(Utils.boxFitsGoal(b.b, goal)){ for (dir goalNeighbourDir : dir.values()) { Field goalNeighbour = goal.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbour != null) { GoalActionSequence routeToGoal = Utils.findGoalRoute(level, a.a, b.b, b.f.neighbours[d.ordinal()], goalNeighbour, b.f, goal, blockedFields); if (routeToGoal != null) { //If we get here, we have found a route to the goal. State newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); newState.parent = currentState; for (AgentInState agent : currentState.agents) { if(agent != a) newState.agents.add(agent); else newState.agents.add(new AgentInState(agent.a, goalNeighbour)); } for (BoxInState box : currentState.boxes) { if(box != b) newState.boxes.add(box); else newState.boxes.add(new BoxInState(box.b, goal)); } returnStates.add(newState); } } } } } blockedFields.add(b.f); } } } } } return returnStates; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/planners/ProgressionWithHeuristic.java
Java
oos
6,251
package client.planners; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Random; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class PrioritizedGoalPlanner implements Planner { Level level; Random rand; PriorityQueue<State> stateQueue; HashMap<String, ArrayList<String>> closedSet; boolean clearedBox = false; boolean goalPriosSet = false; private static final String name = "AStarPlanner"; @Override public String getName() { return name; } public PrioritizedGoalPlanner(Level l) { this.level = l; rand = new Random(); } public void makePlan() { System.err.println("make plan"); long timestamp1 = System.currentTimeMillis(); // Hardcode the goal priorities. int t = 10; if (!goalPriosSet) { for (Goal g : level.goals) g.priority = t--; } goalPriosSet = true; // Sort the goals such that we iterate best goals first. Collections.sort(level.goals); stateQueue = new PriorityQueue<State>(); closedSet = new HashMap<String, ArrayList<String>>(); // Find eligible boxes to first goal //int nextGoalindex for (Goal g : level.goals) { for (Box b : Utils.getBoxesInLevel(level.boxes, g.getId())) { for (Agent a : Utils.getAgents(level.agents, b.getColor())) { ArrayList<State> firstStates = Utils.getStateFromLevel( level.agents, level.boxes, b.getAtField()); for (State state : firstStates) { state.heuristicValue = level.goals.size() * 2; state.goal.agent = new AgentInState(a, a.getAtField()); state.goal.box = new BoxInState(b, b.getAtField()); state.goal.boxToPos = g; state.goal.nextGoalIndex = 1; state.goal.isMoveToBoxGoal = true; stateQueue.add(state); } } } } State currentState = stateQueue.poll(); ArrayList<Field> agentPositions = new ArrayList<Field>(); for (AgentInState a : currentState.agents) { agentPositions.add(a.f); } String boxPositions = ""; for (BoxInState b : currentState.boxes) { boxPositions += b.f.toString() + b.b.getId(); } closedSet.put(agentPositions.toString(), new ArrayList<String>()); closedSet.get(agentPositions.toString()).add(boxPositions); // Start the search while (currentState != null && !Utils.allGoalsHasBoxes(currentState, level)) { // The goal of the state is to get to a box. if (currentState.goal.isMoveToBoxGoal) { // System.err.println("Move: " +currentState.goal.nextGoalIndex+ " Try move agent to " + currentState.goal.agentToPos); AgentInState agent = currentState.goal.agent; BoxInState box = currentState.goal.box; ArrayList<Field> blockedFields = getBlockedField(currentState, agent); MoveActionSequence routeToGoal = Utils.findRoute(level, agent.f, currentState.goal.agentToPos, blockedFields); if (routeToGoal == null) { clearPath(agent, currentState); currentState = stateQueue.poll(); continue; } // System.err.println("Completed move " + currentState.goal.nextGoalIndex); // System.err.println("Move agent successfully to " + currentState.goal.agentToPos); completedMoveToBox(currentState, agent, box, routeToGoal, currentState.goal.boxToPos, currentState.goal.isClearPathGoal); } else { AgentInState agent = currentState.goal.agent; BoxInState box = currentState.goal.box; ArrayList<Field> blockedFields = getBlockedField(currentState, agent, box); // The stateGoal has a box and an agent. As well as the positions they should move to. GoalActionSequence routeToGoal = Utils.findGoalRoute(level, currentState.goal.agent.a, currentState.goal.box.b, currentState.goal.agent.f, currentState.goal.agentToPos, currentState.goal.box.f, currentState.goal.boxToPos, blockedFields); if (routeToGoal == null) { // Try to clear a path currentState = stateQueue.poll(); continue; } int nextGoalIndex = currentState.goal.nextGoalIndex; if (!currentState.goal.isClearPathGoal) { System.err.println("Goal: " +currentState.goal.nextGoalIndex+ " Push agent to " + currentState.goal.agentToPos + " and box "+ currentState.goal.box.b.getId() +" to " + currentState.goal.boxToPos); if (nextGoalIndex >= level.goals.size()) { System.err.println("Goal count exceeded"); State goalState = new State(); goalState.actionSequencesFromParent.add(routeToGoal); goalState.parent = currentState; currentState = goalState; break; } } else{ // System.err.println("Completed push " + currentState.goal.nextGoalIndex); } completeGoal(nextGoalIndex, currentState, routeToGoal); } currentState = stateQueue.poll(); } // System.err.println(currentState.parent.agents.get(0).f.toString()); // for (BoxInState b : currentState.parent.boxes) { // System.err.println(b.f.toString()); // } long timestamp2 = System.currentTimeMillis(); System.err.println("Done in " + (timestamp2-timestamp1)/1000.0 + " seconds"); System.err.println("States left: " + stateQueue.size()); System.err.println("Cleared box " + clearedBox); ArrayList<Command> commands = new ArrayList<Command>(); int counter = 0; while (currentState != null) { counter++; for (ActionSequence as : currentState.actionSequencesFromParent) { Collections.reverse(as.getCommands()); for (Command c : as.getCommands()) { commands.add(c); } } currentState = currentState.parent; } System.err.println("Sequences " + counter); Collections.reverse(commands); for (Command command : commands) { level.agents.get(0).commandQueue.add(command); } } private void completeGoal(int nextGoalIndex, State currentState, GoalActionSequence routeToGoal) { int index; if (currentState.goal.isClearPathGoal) { index = nextGoalIndex-1; } else { index= nextGoalIndex; } // We have found a route to the goal. Find next states to check. for (Box b : Utils.getBoxesInLevel(level.boxes, level.goals.get(index).getId())) { BoxInState boxInState = findBoxInCompletedState(currentState, b); if (boxInState.f instanceof Goal && Utils.boxFitsGoal(boxInState.b, (Goal) boxInState.f)) continue; for (Agent a : Utils.getAgents(level.agents, b.getColor())) { ArrayList<State> newStates = Utils.getState( currentState.agents, currentState.boxes, currentState.goal.box.b, currentState.goal.boxToPos, a, currentState.goal.agentToPos, boxInState.f); for (State newState : newStates) { newState.goal.box = boxInState; newState.goal.boxToPos = level.goals.get(index); newState.goal.isClearPathGoal = false;//currentState.goal.isClearPathGoal; if (!addState(newState)) continue; newState.actionSequencesFromParent.add(routeToGoal); newState.parent = currentState; if (currentState.goal.isClearPathGoal){ newState.heuristicValue = newState.parent.heuristicValue+1; newState.goal.nextGoalIndex = nextGoalIndex; } else{ newState.goal.nextGoalIndex = nextGoalIndex+1; newState.heuristicValue = newState.parent.heuristicValue-2; } newState.goal.agent = new AgentInState(a, currentState.goal.agentToPos); newState.goal.isMoveToBoxGoal = true; stateQueue.add(newState); } } } } private void completedMoveToBox( State currentState, AgentInState agent, BoxInState boxInState, MoveActionSequence routeToGoal, Field boxToPos, boolean isClearPath) { ArrayList<State> newStates = Utils.getState(currentState.agents, currentState.boxes, agent.a, routeToGoal.getEndField(), boxToPos); for (State newState : newStates) { newState.goal.box = boxInState; newState.goal.boxToPos = boxToPos; newState.goal.isClearPathGoal = isClearPath; if (!addState(newState)) continue; newState.goal.nextGoalIndex = currentState.goal.nextGoalIndex; newState.actionSequencesFromParent.add(routeToGoal); newState.parent = currentState; if (isClearPath) { newState.heuristicValue = newState.parent.heuristicValue + 1; } else{ newState.heuristicValue = newState.parent.heuristicValue - 1; } newState.goal.agent = new AgentInState(agent.a, routeToGoal.getEndField()); newState.goal.isMoveToBoxGoal = false; stateQueue.add(newState); } } private BoxInState findBoxInCompletedState(State currentState, Box box) { BoxInState boxInState = currentState.goal.box; for (BoxInState b : currentState.boxes) { if(b.b == boxInState.b && box == b.b){ return new BoxInState(box, currentState.goal.boxToPos); } else if (b.b == box) { return b; } } return null; } private boolean addState(State newState) { ArrayList<Field> tempAgentPositions = new ArrayList<Field>(); // for (AgentInState a : newState.agents) tempAgentPositions.add(a.f); tempAgentPositions.add(newState.goal.agentToPos); String key = newState.goal.isClearPathGoal + " " + tempAgentPositions.toString(); String tempBoxPositions = ""; // ArrayList<Field> tempBoxPositions = new ArrayList<Field>(); for (BoxInState b : newState.boxes) { if (newState.goal.box == null || newState.goal.box.b != b.b) { tempBoxPositions += b.f.toString() + b.b.getId(); } else { // System.err.println("This one " + newState.goal.boxToPos.toString()); tempBoxPositions += newState.goal.boxToPos.toString() + b.b.getId(); } } if (closedSet.containsKey(key)) { if (closedSet.get(key).contains(tempBoxPositions)) { return false; } else { closedSet.get(key).add(tempBoxPositions); } } else { closedSet.put(key, new ArrayList<String>()); closedSet.get(key).add(tempBoxPositions); } // System.err.println("Adding state " + key + " " + tempBoxPositions.toString()); return true; } private ArrayList<Field> getBlockedField(State currentState, AgentInState agent) { ArrayList<Field> blockedFields = new ArrayList<Field>(); for (AgentInState a : currentState.agents) { if (agent.f != a.f) blockedFields.add(a.f); } for (BoxInState box : currentState.boxes) { blockedFields.add(box.f); } return blockedFields; } private ArrayList<Field> getBlockedField(State currentState, AgentInState agent, BoxInState box) { ArrayList<Field> blockedFields = new ArrayList<Field>(); for (AgentInState a : currentState.agents) { if (agent.f != a.f) blockedFields.add(a.f); } for (BoxInState b : currentState.boxes) { if (box.f != b.f) blockedFields.add(b.f); } return blockedFields; } private void clearPath(AgentInState agent, State currentState) { MoveActionSequence requiredClear = Utils.findRoute(level, agent.f, currentState.goal.agentToPos); int index = 0; for (Field firstBoxAtField : requiredClear.fields) { BoxInState boxInState = Utils.getBoxAtField(currentState, firstBoxAtField); if (Utils.isFieldClear(currentState, firstBoxAtField) && boxInState == null) { index++; continue; } Field agentToField; if (index == 0) agentToField = agent.f; else agentToField = requiredClear.fields.get(index - 1); ArrayList<Field> blockedFields = getBlockedField(currentState, agent, boxInState); MoveActionSequence routeToGoal = Utils.findRoute(level, agent.f, agentToField, blockedFields); if (routeToGoal == null) { return; } for (Field freeField : Utils .findFreeField(level, blockedFields)) { completedMoveToBox(currentState, agent, boxInState, routeToGoal, freeField, true); } break; } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/planners/PrioritizedGoalPlanner.java
Java
oos
12,165
package client.planners; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.PriorityQueue; import java.util.Random; import agent.objectives.DockABox; import agent.objectives.GoalABox; import agent.objectives.Objective; import agent.planners.AgentPlanner; import agent.planners.AgentProgressionPlanner; import utils.GoalPriority; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import constants.Constants.Color; import constants.Constants.dir; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class ClientPlanner implements Planner { Level level; Random rand; public boolean firstRun = true; private static final String name = "ClientPlanner"; @Override public String getName() { return name; } public ClientPlanner(Level l) { this.level = l; rand = new Random(); } public void makePlan() { // System.err.println("Make plan!"); AgentPlanner planner = new AgentProgressionPlanner(level); int agentsNeedsPlans = 0; for (Agent agent : level.agents) { if(agent.objectives.isEmpty()) agentsNeedsPlans++; } if(agentsNeedsPlans == level.agents.size() && !Utils.allGoalsHasBoxes(level)) firstRun = true; if (firstRun) { GoalPriority.createGoalPrioritization(level, true); for (Agent a : level.agents) { a.priority = 99; a.planner = planner; a.possibleBoxesToGoals = Utils.findPossibleBoxes(level, a); } // Find goals in order and find an agent to goal it for (Goal g : level.goals) { for (Agent a : level.agents) { for (Box b : a.possibleBoxesToGoals.keySet()) { Goal goal = null; if (a.possibleBoxesToGoals.containsKey(b) && Utils.boxFitsGoal(b, g)){ //add goal with lowest priority goal = GoalPriority.FindGoalWithHighestPriority(a, b, level); if(a.objectives == null) a.objectives.addFirst(new GoalABox(b, goal)); else{ Objective o = a.objectives.peek(); if(o instanceof GoalABox && ((GoalABox) o).goal.getPriority() > goal.getPriority()){ a.objectives.addFirst(new GoalABox(b, goal)); } else{ a.objectives.addLast(new GoalABox(b, goal)); } } if(a.priority > goal.priority) a.priority = goal.priority; } } } } firstRun = false; } for (Agent a : level.agents) { if(a.objectives.isEmpty()){ Goal goal_highest_priority = Utils.allOfAgentGoalsHasBoxes(a, level); if(goal_highest_priority != null){ //Find route to goal Collection<Field> blockedFields = null; ArrayList<Box> boxesInTheWay = null; boxesInTheWay = Utils.findRouteCountBoxesInTheWay(level, a, a.getAtField(), new Field(goal_highest_priority.x, goal_highest_priority.y), blockedFields); //remove boxes in the way boxesInTheWayLoop : for (Box box : boxesInTheWay) { if(box.getId() == a.getId()){ //make DockABox thing Objective o = new DockABox(box.getAtField(), box, 15); a.objectives.addFirst(o); break boxesInTheWayLoop; } } } } a.planAndExecute(level); } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/planners/ClientPlanner.java
Java
oos
3,702
package client.planners; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Random; import utils.FOMAUtils; import utils.PrioriGoalUtils; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.FieldBlockedChange; import datastructures.FieldInState; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class FOMAPrioritizedGoalPlanner implements Planner { Level level; Random rand; PriorityQueue<State> stateQueue; HashMap<String, ArrayList<String>> closedSet; boolean clearedBox = false; boolean goalPriosSet = false; private static final String name = "AStarPlanner"; @Override public String getName() { return name; } public FOMAPrioritizedGoalPlanner(Level l) { this.level = l; rand = new Random(); } public void makePlan() { System.err.println("make plan"); long timestamp1 = System.currentTimeMillis(); // Hardcode the goal priorities. int t = 20; if (!goalPriosSet) { for (Goal g : level.goals) g.priority = t--; } goalPriosSet = true; // Sort the goals such that we iterate best goals first. Collections.sort(level.goals); ArrayList<ArrayList<Command>> agentCommands = new ArrayList<ArrayList<Command>>(); for (Agent a : level.agents) { State currentState = planForAgent(a,agentCommands); ArrayList<Command> commands = new ArrayList<Command>(); while (currentState != null) { for (ActionSequence as : currentState.actionSequencesFromParent) { Collections.reverse(as.getCommands()); for (Command c : as.getCommands()) { commands.add(c); } } currentState = currentState.parent; } Collections.reverse(commands); agentCommands.add(commands); for (Command command : commands) { a.commandQueue.add(command); } } long timestamp2 = System.currentTimeMillis(); System.err.println("Plans made in " + (timestamp2 - timestamp1) / 1000.0 + " seconds"); } private State planForAgent(Agent currentAgent, ArrayList<ArrayList<Command>> agentCommands){ Object[] setup = setupPlan(currentAgent); State currentState = (State) setup[0]; ArrayList<Goal> agentGoals = (ArrayList<Goal>) setup[1]; FOMAUtils.mergeState(level,currentState, agentCommands); System.err.println("NEW STATE"); while (currentState != null && !Utils.allGoalsAtHasBoxes(currentState, level, agentGoals)) { // The goal of the state is to get to a box. // System.err.println(stateQueue.size()); // System.err.println("New state"); currentState.printFieldChanges(); if (currentState.goal.isMoveToBoxGoal) { AgentInState agent = currentState.goal.agent; BoxInState box = currentState.goal.box; ArrayList<FieldInState> blockedFields = PrioriGoalUtils.getBlockedFields(currentState); MoveActionSequence routeToGoal = FOMAUtils.findRoute(level, agent.f, currentState.goal.agentToPos, blockedFields, currentState.indexOfCommands); if (routeToGoal == null) { clearPath(agent, currentState); currentState = stateQueue.poll(); continue; } // System.err.println("Found route to " + routeToGoal.getEndField()); completedMoveToBox(currentState, agent, box, routeToGoal, currentState.goal.boxToPos, currentState.goal.isClearPathGoal); } else { AgentInState agent = currentState.goal.agent; BoxInState box = currentState.goal.box; ArrayList<FieldInState> blockedFields = PrioriGoalUtils.getBlockedFields(currentState); // The stateGoal has a box and an agent. As well as the positions they should move to. GoalActionSequence routeToGoal = FOMAUtils.findGoalRoute(level, currentState, blockedFields); if (routeToGoal == null) { // Try to clear a path System.err.println("No route to goal"); currentState = stateQueue.poll(); continue; } // System.err.println("Route to goal " + currentState.goal.isClearPathGoal + " " + currentState.goal.nextGoalIndex + " " + agentGoals.size()); int nextGoalIndex = currentState.goal.nextGoalIndex; if (!currentState.goal.isClearPathGoal && nextGoalIndex >= agentGoals.size()) { System.err.println("Goal count exceeded"); State goalState = new State(); goalState.actionSequencesFromParent.add(routeToGoal); goalState.parent = currentState; currentState = goalState; break; } completeGoal(nextGoalIndex, currentState, routeToGoal, agentGoals); } currentState = stateQueue.poll(); } if(currentState == null) System.err.println("State space explored"); return currentState; } private void completeGoal(int nextGoalIndex, State currentState, GoalActionSequence routeToGoal, ArrayList<Goal> goals) { int index; if (currentState.goal.isClearPathGoal) { index = nextGoalIndex - 1; } else { index = nextGoalIndex; } // We have found a route to the goal. Find next states to check. for (Box b : Utils.getBoxesInLevel(level.boxes, goals.get(index) .getId())) { BoxInState boxInState = Utils.findBoxInCompletedState(currentState, b); if (boxInState.f instanceof Goal && Utils.boxFitsGoal(boxInState.b, (Goal) boxInState.f)) continue; for (Agent a : Utils.getAgents(level.agents, b.getColor())) { ArrayList<State> newStates = FOMAUtils.getStateFromCompletedGoal(currentState, a, boxInState.f, routeToGoal); for (State newState : newStates) { newState.goal.box = boxInState; newState.goal.boxToPos = goals.get(index); newState.goal.isClearPathGoal = false;// currentState.goal.isClearPathGoal; if (!addState(newState)) continue; newState.actionSequencesFromParent.add(routeToGoal); newState.parent = currentState; if (currentState.goal.isClearPathGoal) { newState.heuristicValue = newState.parent.heuristicValue + 1; newState.goal.nextGoalIndex = nextGoalIndex; } else { newState.goal.nextGoalIndex = nextGoalIndex + 1; newState.heuristicValue = newState.parent.heuristicValue - 2; } newState.goal.agent = new AgentInState(a, currentState.goal.agentToPos); newState.goal.isMoveToBoxGoal = true; stateQueue.add(newState); } } } } private void completedMoveToBox(State currentState, AgentInState agent, BoxInState boxInState, MoveActionSequence routeToGoal, Field boxToPos, boolean isClearPath) { ArrayList<State> newStates = FOMAUtils.getStateFromCompletedMove(currentState, agent.a, routeToGoal, boxToPos); for (State newState : newStates) { newState.goal.box = boxInState; newState.goal.boxToPos = boxToPos; newState.goal.isClearPathGoal = isClearPath; newState.indexOfCommands = currentState.indexOfCommands + routeToGoal.getCommands().size(); if (!addState(newState)) continue; newState.goal.nextGoalIndex = currentState.goal.nextGoalIndex; newState.actionSequencesFromParent.add(routeToGoal); newState.parent = currentState; if (isClearPath) { newState.heuristicValue = newState.parent.heuristicValue + 1; } else { newState.heuristicValue = newState.parent.heuristicValue - 1; } newState.goal.agent = new AgentInState(agent.a, routeToGoal.getEndField()); newState.goal.isMoveToBoxGoal = false; stateQueue.add(newState); } } private boolean addState(State newState) { ArrayList<Field> tempAgentPositions = new ArrayList<Field>(); // for (AgentInState a : newState.agents) tempAgentPositions.add(a.f); tempAgentPositions.add(newState.goal.agentToPos); String key = newState.goal.isClearPathGoal + " " + tempAgentPositions.toString(); String tempBoxPositions = ""; // ArrayList<Field> tempBoxPositions = new ArrayList<Field>(); for (BoxInState b : newState.boxes) { if (newState.goal.box == null || newState.goal.box.b != b.b) { tempBoxPositions += b.f.toString() + b.b.getId(); } else { // System.err.println("This one " + // newState.goal.boxToPos.toString()); tempBoxPositions += newState.goal.boxToPos.toString() + b.b.getId(); } } if (closedSet.containsKey(key)) { if (closedSet.get(key).contains(tempBoxPositions)) { return false; } else { closedSet.get(key).add(tempBoxPositions); } } else { closedSet.put(key, new ArrayList<String>()); closedSet.get(key).add(tempBoxPositions); } // System.err.println("Adding state " + key + " " + // tempBoxPositions.toString()); return true; } private void clearPath(AgentInState agent, State currentState) { MoveActionSequence requiredClear = Utils.findRoute(level, agent.f, currentState.goal.agentToPos); if (requiredClear == null) { return; } int index = 0; for (Field firstBoxAtField : requiredClear.fields) { BoxInState boxInState = Utils.getBoxAtField(currentState, firstBoxAtField); if (Utils.isFieldClear(currentState, firstBoxAtField) && boxInState == null) { index++; continue; } Field agentToField; if (index == 0) agentToField = agent.f; else agentToField = requiredClear.fields.get(index - 1); ArrayList<Field> blockedFields = PrioriGoalUtils.getBlockedFields(currentState, agent, boxInState); MoveActionSequence routeToGoal = Utils.findRoute(level, agent.f, agentToField, blockedFields); if (routeToGoal == null) { return; } for (Field freeField : Utils.findFreeField(level, blockedFields)) { completedMoveToBox(currentState, agent, boxInState, routeToGoal, freeField, true); } break; } } private Object[] setupPlan(Agent currentAgent) { Object[] stateAndGoals = new Object[2]; stateQueue = new PriorityQueue<State>(); ArrayList<Goal> returnGoals = new ArrayList<Goal>(); int nextGoalIndex = 1; boolean firstStateSet = false; for(Goal g : level.goals){ for (Box b : Utils.getBoxesWithId(level.boxes, g.getId())) { if (b.getColor() != currentAgent.getColor()) continue; if (!firstStateSet) { ArrayList<State> firstStates = FOMAUtils.getStateFromLevel( level.agents, level.boxes, level.fields, b.getAtField()); for (State state : firstStates) { state.heuristicValue = level.goals.size() * 2; state.goal.agent = new AgentInState(currentAgent, currentAgent.getAtField()); state.goal.box = new BoxInState(b, b.getAtField()); state.goal.boxToPos = g; state.goal.nextGoalIndex = nextGoalIndex; state.indexOfCommands = 0; state.goal.isMoveToBoxGoal = true; stateQueue.add(state); } firstStateSet = true; } if (!returnGoals.contains(g)) { returnGoals.add(g); nextGoalIndex++; } } } State currentState = stateQueue.poll(); ArrayList<Field> agentPositions = new ArrayList<Field>(); for (AgentInState a : currentState.agents) { agentPositions.add(a.f); } String boxPositions = ""; for (BoxInState b : currentState.boxes) { boxPositions += b.f.toString() + b.b.getId(); } closedSet = new HashMap<String, ArrayList<String>>(); closedSet.put(agentPositions.toString(), new ArrayList<String>()); closedSet.get(agentPositions.toString()).add(boxPositions); stateAndGoals[0] = currentState; stateAndGoals[1] = returnGoals; return stateAndGoals; } //Here we want to resolve any conflicts private void validatePlan(ArrayList<ArrayList<ActionSequence>> agentSequences) { } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/planners/FOMAPrioritizedGoalPlanner.java
Java
oos
11,802
package client.planners; public interface Planner { public String getName(); public void makePlan(); }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/planners/Planner.java
Java
oos
119
package client.planners; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Random; import java.util.Set; import utils.AStarField; import constants.Constants.dir; import client.Command; import client.Desire; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; public class SimplePlanner implements Planner { Level level; Random rand; private static final String name = "SimplePlanner"; @Override public String getName() { return name; } public SimplePlanner(Level l) { this.level = l; rand = new Random(); } public void makePlan() { ArrayList<Desire> desires = findDesires(); findIntentions(desires); decideCommands(); } private ArrayList<Desire> findDesires() { ArrayList<Desire> returnDesires = new ArrayList<Desire>(); for (Agent a : level.agents) { if (!getToBoxDesireCompleted(a)) { for (Box b : level.boxes) { //System.err.println("adding box goal with " + b.getId()); if (a.getColor() == b.getColor() && !(b.getAtField() instanceof Goal && ((Goal) b .getAtField()).getId() == b.getId())) { returnDesires.add(new Desire(a, b)); } } } else { for (Goal g : level.goals) { // System.err.println("adding goal goal with " + g.getId()); if (g.getId() == a.desire.box.getId() && g.object == null) { System.err.println("adding desire "+ g.x + "." + g.y); returnDesires.add(new Desire(a, a.desire.box, g)); } } } a.desire = null; } return returnDesires; } private void findIntentions(ArrayList<Desire> desires) { ArrayList<Desire> chosenIntentions = new ArrayList<Desire>(); //Assign new intentions. for (Agent a : level.agents) { a.desire = null; } //Shuffle desires. Should be removed in later stages. Collections.shuffle(desires); for (Desire d : desires) { boolean agentAlreadyInIntentions = false; for (Desire desire : chosenIntentions) { if (desire.agent == d.agent || desire.box == d.box || (desire.goal != null && desire.goal == d.goal)) { agentAlreadyInIntentions = true; } } if (!agentAlreadyInIntentions) { d.agent.desire = d; chosenIntentions.add(d); } } } // A-star to the goal field for each agent. private void decideCommands() { for (int i = 0; i < level.agents.size(); i++) { Agent a = level.agents.get(i); Field goal; //TODO is this ok? if (a.desire == null) return; if (a.desire.goal != null) goal = a.desire.goal; else goal = a.desire.box.getAtField(); // This is the new, incomplete code Andreas and Johan are making for // branching. if (a.desire.goal != null) { Box b = null; while (!findBranchingRoute(a, b)) moveObstacle(a, b); continue; } // HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<AStarField> closedSet = new HashSet<AStarField>(); AStarField start = new AStarField(a.getAtField()); start.g = 0; start.f = start.g + heuristicEstimate(start.field, goal); openSet.add(start); AStarField curField = null; outerloop: while (!openSet.isEmpty()) { curField = openSet.poll(); // Check if we are next to the goal. for (dir d : dir.values()) { if (curField.field.neighbours[d.ordinal()] != null && curField.field.neighbours[d.ordinal()] .equals(goal)) { break outerloop; } } closedSet.add(curField); for (dir d : dir.values()) { if (a.neighbourFree(curField.field, d)) { int tentativeGScore = curField.g + 1; AStarField neighbourInClosedSet = null; for (AStarField aClosed : closedSet) { if (aClosed.field .equals(curField.field.neighbours[d .ordinal()])) neighbourInClosedSet = aClosed; } if (neighbourInClosedSet != null && tentativeGScore >= neighbourInClosedSet.g) { continue; } AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field.equals(curField.field.neighbours[d .ordinal()])) neighbourInClosedSet = aOpen; } boolean nInOpenSet = (neighbourInOpenSet != null); if (neighbourInOpenSet == null || tentativeGScore < neighbourInOpenSet.g) { neighbourInOpenSet = new AStarField( curField.field.neighbours[d.ordinal()]); neighbourInOpenSet.g = tentativeGScore; neighbourInOpenSet.f = neighbourInOpenSet.g + heuristicEstimate( neighbourInOpenSet.field, goal); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); if (!nInOpenSet) openSet.add(neighbourInOpenSet); } } } } ArrayList<Command> commands = new ArrayList<Command>(); while (cameFrom.get(curField) != null) { commands.add(curField.c); curField = cameFrom.get(curField); } while (!commands.isEmpty()) { a.commandQueue.add(commands.remove(commands.size() - 1)); } } } private int heuristicEstimate(Field a, Field goal) { return heuristicEstimateManhattan(a, goal); } private int heuristicEstimateEuclid(Field a, Field goal) { int h = (int) Math.sqrt(Math.pow(Math.abs(a.x - goal.x), 2) + Math.pow(Math.abs(a.y - goal.y), 2)); return h; } // Manhattan distance private int heuristicEstimateManhattan(Field a, Field goal) { int h = (int) Math.abs(a.x - goal.x) + Math.abs(a.y - goal.y); return h; } // Determines if an agent had a goal of getting to a box and completed this // goal. private boolean getToBoxDesireCompleted(Agent a) { for (dir d : dir.values()) { if (a.desire != null && a.desire.goal == null && a.getAtField().neighbours[d.ordinal()] != null && a.getAtField().neighbours[d.ordinal()] .equals(a.desire.box.getAtField())) return true; } return false; } private boolean getBoxToGoalDesireCompleted(Agent a){ if (a.desire != null && a.desire.goal != null && a.desire.box.getAtField() == a.desire.goal) return true; return false; } // We know that the agent a has a box. Now we want to move the box to the // goal. private boolean findBranchingRoute(Agent a, Box obstacle) { dir boxDir = null; BacktrackTree root = new BacktrackTree(a.desire.box.getAtField(), a.getAtField(), null); BacktrackTree currentNode = null; Set<BacktrackTree> closedSet = new HashSet<BacktrackTree>(); LinkedList<BacktrackTree> queue = new LinkedList<BacktrackTree>(); // prune looped states (if agent and box ends up in a state already explored) HashMap<Field, ArrayList<Field>> exploredStates = new HashMap<Field, ArrayList<Field>>(); //adding initial state to list set of explored states: ArrayList<Field> tempList = new ArrayList<Field>(); tempList.add(a.desire.box.getAtField()); exploredStates.put(a.getAtField(), tempList); //Add a closed set. queue.add(root); currentNode = queue.pop(); while (currentNode.boxLocation != a.desire.goal) { boxDir = Agent.getBoxDirection(currentNode.agentLocation,currentNode.boxLocation); ArrayList<Command> foundCommands = a .addPossibleCommandsForDirection(boxDir, currentNode.agentLocation, currentNode.boxLocation); for (Command command : foundCommands) { Field boxLocation = null; Field agentLocation = null; if (command.cmd.equals("Push")) { agentLocation = currentNode.boxLocation; boxLocation = currentNode.boxLocation.neighbours[command.dir2 .ordinal()]; } else { boxLocation = currentNode.agentLocation; agentLocation = currentNode.agentLocation.neighbours[command.dir1 .ordinal()]; } // Do we already have a way to get to this state? if (exploredStates.containsKey(agentLocation)) { if (exploredStates.get(agentLocation).contains(boxLocation)) continue; else { // the agent has been here before but without the box in same location exploredStates.get(agentLocation).add(boxLocation); } } else { // neither the agent or the box has been here before. Update DS and create node in BTtree: ArrayList<Field> tempListe = new ArrayList<Field>(); tempListe.add(boxLocation); exploredStates.put(agentLocation, tempListe); } BacktrackTree bt = new BacktrackTree(boxLocation, agentLocation, command); bt.parent = currentNode; boolean setupInClosedSet = false; for (BacktrackTree closedTree : closedSet) { if (closedTree.agentLocation.x == bt.agentLocation.x && closedTree.agentLocation.y == bt.agentLocation.y && closedTree.boxLocation.x == bt.boxLocation.x && closedTree.boxLocation.y == bt.boxLocation.y) { setupInClosedSet = true; } } if (!setupInClosedSet) { queue.add(bt); closedSet.add(bt); } } if (queue.isEmpty()) { //TODO: we have searched to the end without finding a solution. Move boxes to get access to goals return false; } currentNode = queue.pop(); } ArrayList<Command> commands = new ArrayList<Command>(); while (currentNode.parent != null) { commands.add(currentNode.action); currentNode = currentNode.parent; } Collections.reverse(commands); for (Command command : commands) { a.commandQueue.add(command); } return true; } /* * find the route with fewest obstacles first, but consider all routes */ private void moveObstacle(Agent a, Box b) { // 1. By using a* find routes to the goal ignoring, but counting boxes (that the agent can move) // 2. queue the routes to goal and save then along with the boxes required to be removed (PriorityQueue on count(Boxes)) // 3. while there is no solution: take the top element in the queue and move the obstacles using "findFreeField" and "findBranchingRoute" } /* * Find a field where a box not ready for goal can be put. * We need to consider the current plan (route to goal for last desire's box) and choose a field not on that route * If there are less "free" fields than required we are f*ed */ private Field findFreeField(Agent a) { return null; } private class BacktrackTree { public BacktrackTree parent; public Field boxLocation; public Field agentLocation; Command action; public BacktrackTree(Field boxLocation, Field agentLocation, Command action) { super(); this.boxLocation = boxLocation; this.agentLocation = agentLocation; this.action = action; } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/planners/SimplePlanner.java
Java
oos
10,820
package client.planners; import java.util.Random; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import aStar.Pathfinding; public class AStarPlanner implements Planner { Level level; Random rand = new Random(); private static final String name = "AStarPlanner"; @Override public String getName() { return name; } public AStarPlanner(Level l) { this.level = l; } public void makePlan() { // assign each agent (in this case 1) some goals (to begin with 1 box to 1 goal) Agent agent = level.agents.get(0); //Box box = level.boxes.get(0); Goal goal = level.goals.get(0); // set agent cmd queue agent.commandQueue = Pathfinding.commandsForAgentToField(level, agent, goal); // should make agent walk to goal... } // functions to deal with conflicts among agents... }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/planners/AStarPlanner.java
Java
oos
928
package client; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Goal; public class Desire { public Agent agent; public Box box; public Goal goal; boolean completed; public Desire(Agent a, Box b) { this.agent = a; this.box = b; } public Desire(Agent a, Box b, Goal g) { this.agent = a; this.box = b; this.goal = g; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/Desire.java
Java
oos
369
package client.messages; import java.util.List; import LevelObjects.Field; public class MoveRequest extends Message { // when can the agent move again public int WaitUntil; // what fields are blocked in the period public List<Field> blokedFields; }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/messages/MoveRequest.java
Java
oos
276
package client.messages; public class Response extends Message { // Is the agent able to help? public boolean Acknowledged; // The original message public Message OriginalRequest; }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/messages/Response.java
Java
oos
201
package client.messages; import LevelObjects.Agent; public abstract class Message { public Agent fromAgent; public Agent toAgent; }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/messages/Message.java
Java
oos
149
package client.messages; import LevelObjects.Box; public class MoveBoxRequest extends MoveRequest { // What box needs to be moved public Box box; // Should the box be removed from a goal to enable a solution public boolean removeFromGoal; }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/messages/MoveBoxRequest.java
Java
oos
266
package client; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map.Entry; import java.util.concurrent.LinkedBlockingQueue; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIManager; public class GuiClient extends JFrame { private static ActionListener listener = new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { CommandButton c = ( (CommandButton) e.getSource() ); buttonSend( c.t, c.cmd ); } }; // Receiver and Transmitter are not needed for most planners, but may lead to (negligible) speed up as you do not synchronize each // action with the server private class ServerReceiver extends Thread { private GuiClient gui; public ServerReceiver( GuiClient g ) { gui = g; } public void run() { try { BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); while ( true ) { String msg = reader.readLine(); if ( msg == null ) throw new IOException( "End of server messages" ); gui.AddCommunication( "<IN> " + msg ); } } catch ( IOException e ) { gui.AddInformation( e.toString() ); } } } private class ServerTransmitter extends Thread { private GuiClient gui; private LinkedBlockingQueue< String > outbound = new LinkedBlockingQueue< String >(); public ServerTransmitter( GuiClient g ) { gui = g; } public void run() { try { while ( true ) { String msg = outbound.take(); System.out.println( msg ); gui.AddCommunication( "<OUT> " + msg ); } } catch ( InterruptedException e ) { gui.AddInformation( e.toString() ); } } } private class CommandButton extends JButton { public final String cmd; public final ServerTransmitter t; public CommandButton( ServerTransmitter t, String label, String cmd ) { super( label ); this.t = t; this.cmd = cmd; this.addActionListener( listener ); } } public static void buttonSend( ServerTransmitter st, String cmd ) { st.outbound.add( cmd ); } private final String nl = System.getProperty( "line.separator" ); private JTextArea communication = new JTextArea(); private JTextArea information = new JTextArea(); private JPanel fixed = new JPanel(); private JPanel custom = new JPanel(); private JPanel comm = new JPanel(); private JPanel info = new JPanel(); private int msgNo; private int agents; private ServerReceiver receiver; private ServerTransmitter transmitter; private class GBC extends GridBagConstraints { public GBC( int x, int y ) { this( x, y, 1 ); } public GBC( int x, int y, int spanx ) { this.insets = new Insets( 0, 3, 0, 3 ); this.gridx = x; this.gridy = y; this.gridwidth = spanx; this.fill = GridBagConstraints.NONE; } public GBC( int x, int y, int spanx, int sep ) { this.insets = new Insets( sep, 3, sep, 3 ); this.gridx = x; this.gridy = y; this.gridwidth = spanx; this.fill = GridBagConstraints.HORIZONTAL; this.weightx = 0; } } public GuiClient( String[] customs ) throws IOException { super( "02285 Toy Client" ); System.err.println("Hello from GuiClient"); readMap(); // Get agent count receiver = new ServerReceiver( this ); transmitter = new ServerTransmitter( this ); communication.setEditable( false ); communication.setFont( new Font( "Monospaced", Font.PLAIN, 11 ) ); information.setEditable( false ); information.setFont( new Font( "Monospaced", Font.PLAIN, 11 ) ); // Fixed Buttons panel JSeparator sep1 = new JSeparator( JSeparator.HORIZONTAL ); JSeparator sep2 = new JSeparator( JSeparator.HORIZONTAL ); HashMap< String, GBC > buts = new HashMap< String, GBC >(); fixed.setLayout( new GridBagLayout() ); buts.put( "Move(N)", new GBC( 3, 0 ) ); buts.put( "Move(W)", new GBC( 2, 1 ) ); buts.put( "Move(E)", new GBC( 4, 1 ) ); buts.put( "Move(S)", new GBC( 3, 2 ) ); fixed.add( new JLabel( "Navigation" ), new GBC( 2, 1, 3 ) ); fixed.add( sep1, new GBC( 0, 3, 7, 10 ) ); int yoff = 4; buts.put( "Push(N,N)", new GBC( 3, yoff + 1 ) ); buts.put( "Push(N,W)", new GBC( 2, yoff + 1 ) ); buts.put( "Push(W,N)", new GBC( 1, yoff + 2 ) ); buts.put( "Push(W,W)", new GBC( 1, yoff + 3 ) ); buts.put( "Push(W,S)", new GBC( 1, yoff + 4 ) ); buts.put( "Push(S,W)", new GBC( 2, yoff + 5 ) ); buts.put( "Push(N,E)", new GBC( 4, yoff + 1 ) ); buts.put( "Push(E,N)", new GBC( 5, yoff + 2 ) ); buts.put( "Push(E,E)", new GBC( 5, yoff + 3 ) ); buts.put( "Push(E,S)", new GBC( 5, yoff + 4 ) ); buts.put( "Push(S,E)", new GBC( 4, yoff + 5 ) ); buts.put( "Push(S,S)", new GBC( 3, yoff + 5 ) ); fixed.add( new JLabel( "Push" ), new GBC( 2, yoff + 3, 3 ) ); fixed.add( sep2, new GBC( 0, yoff + 7, 7, 10 ) ); yoff = 12; buts.put( "Pull(N,S)", new GBC( 3, yoff + 1 ) ); buts.put( "Pull(N,W)", new GBC( 2, yoff + 1 ) ); buts.put( "Pull(W,N)", new GBC( 1, yoff + 2 ) ); buts.put( "Pull(W,E)", new GBC( 1, yoff + 3 ) ); buts.put( "Pull(W,S)", new GBC( 1, yoff + 4 ) ); buts.put( "Pull(S,W)", new GBC( 2, yoff + 5 ) ); buts.put( "Pull(S,N)", new GBC( 3, yoff + 5 ) ); buts.put( "Pull(N,E)", new GBC( 4, yoff + 1 ) ); buts.put( "Pull(E,N)", new GBC( 5, yoff + 2 ) ); buts.put( "Pull(E,W)", new GBC( 5, yoff + 3 ) ); buts.put( "Pull(E,S)", new GBC( 5, yoff + 4 ) ); buts.put( "Pull(S,E)", new GBC( 4, yoff + 5 ) ); fixed.add( new JLabel( "Pull" ), new GBC( 2, yoff + 3, 3 ) ); for ( Entry< String, GBC > e : buts.entrySet() ) { fixed.add( new CommandButton( transmitter, e.getKey(), "[" + Multify( e.getKey() ) + "]" ), e.getValue() ); } // Custom Panel GridBagConstraints c = new GridBagConstraints(); c.gridy++; custom.setLayout( new GridBagLayout() ); if ( customs.length == 0 ) customs = new String[] { "", "" }; for ( int i = 0; i < customs.length; i++ ) { JButton but = new JButton( "Command " + i ); final JTextField input = new JTextField( customs[i] ); but.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { buttonSend( transmitter, input.getText() ); } } ); c = new GridBagConstraints(); c.gridy = i; c.fill = GridBagConstraints.HORIZONTAL; custom.add( but, c ); c.weightx = 0.80; c.gridx = 1; custom.add( input, c ); } // Communication panel comm.setLayout( new GridBagLayout() ); comm.setMinimumSize(new Dimension(200, 250)); c = new GridBagConstraints(); c.ipadx = 5; comm.add( new JLabel( "Communication Done" ), c ); c.gridy = 1; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; comm.add( new JScrollPane( communication, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ), c ); // Information panel info.setLayout( new GridBagLayout() ); comm.setMinimumSize(new Dimension(200, 100)); c = new GridBagConstraints(); c.ipadx = 5; info.add( new JLabel( "Client Information (e.g. Exceptions)" ), c ); c.gridy = 1; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; info.add( new JScrollPane( information, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ), c ); // Add components to main frame setLayout( new GridBagLayout() ); c = new GridBagConstraints(); c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets( 3, 3, 3, 3 ); add( fixed, c ); c.gridy = 1; add( custom, c ); c.gridy = 2; c.weighty = 0.8; c.fill = GridBagConstraints.BOTH; add( comm, c ); c.gridy = 3; c.weighty = 0.2; add( info, c ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setMinimumSize( new Dimension( 525, 820 ) ); setLocation( 800, 120 ); receiver.start(); transmitter.start(); this.pack(); setVisible( true ); } public void AddCommunication( String m ) { // Append is thread safe.. communication.append( msgNo + ":\t" + m + nl ); synchronized ( this ) { communication.setCaretPosition( communication.getText().length() ); msgNo++; } } public void AddInformation( String m ) { // Append is thread safe.. information.append( m + nl ); synchronized ( this ) { information.setCaretPosition( information.getText().length() ); } } /** * Turns Cmd into Cmd,Cmd,Cmd (..) based on number of agents * * @param cmd * @return Multified cmd */ private String Multify( String cmd ) { String s = ""; for ( int i = 0; i < agents - 1; i++ ) { s += cmd + ","; } return s + cmd; } private void readMap() throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); agents = 0; String line; // Read lines specifying colors while ( ( line = in.readLine() ).matches( "^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$" ) ) { // Skip } // Read lines specifying level layout // By convention levels are ended with an empty newline while ( !line.equals( "" ) ) { for ( int i = 0; i < line.length(); i++ ) { char id = line.charAt( i ); if ( '0' <= id && id <= '9' ) agents++; } line = in.readLine(); if ( line == null ) break; } } public static void main( String[] args ) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); new GuiClient( args ); } catch ( Exception e ) { e.printStackTrace(); } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/GuiClient.java
Java
oos
9,836
package client; import java.util.Arrays; import java.util.Scanner; public class Output { private static Scanner scan = new Scanner(System.in); /*public Output() { scan = new Scanner(System.in); }*/ public static boolean[] Send(Command[] commands) { // System.err.println("Sending: [" + Arrays.toString(commands) + "]"); String sendString = Arrays.toString(commands); sendString = sendString.replaceAll("null", "NoOp"); System.out.println(sendString); System.out.flush(); String feedback = scan.nextLine(); // [false, false] String[] elements = feedback.substring(1, feedback.length()-1).split(", "); boolean[] result = new boolean[elements.length]; int i = 0; for (String s : elements) result[i++] = Boolean.parseBoolean(s); return result; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/Output.java
Java
oos
821
package client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import constants.Constants.Color; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; public class Parser { // Flaws in current implementation: // - fields outside walls are created. A simple search could easily remove them, but they don't seem to be in the way, yet. public static Level readLevel() throws IOException { Level l = new Level(); //FileReader fR = new FileReader("src/levels/FOMAbispebjerg.lvl"); //BufferedReader in = new BufferedReader(fR); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Read lines specifying colors Map<Character,Color> colors = new HashMap<Character,Color>(); String line; Color color; while ((line = in.readLine()).matches("^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$")) { line = line.replaceAll("\\s", ""); color = Color.valueOf(line.split(":")[0]); for (String id : line.split(":")[1].split(",")) colors.put(id.charAt(0), color); } // Read level layout ArrayList<String> rawLevel = new ArrayList<String>(); while (!line.equals("")) { rawLevel.add(line); line = in.readLine(); } // Set size of field map int maxWidth = 0; for (int y=1; y<rawLevel.size()-1; y++) { if (rawLevel.get(y).length() > maxWidth) { maxWidth = rawLevel.get(y).length(); } } l.setFieldMap(new Field[maxWidth][rawLevel.size()]); // Read lines specifying level layout (skipping the border) for (int y=0; y<rawLevel.size(); y++) { for (int x=0; x<rawLevel.get(y).length(); x++) { char id = rawLevel.get(y).charAt(x); if ('+' == id) continue; // skip if wall Field f; if ('0' <= id && id <= '9') { f = new Field(x,y); Agent a = new Agent(id, colors.get(id), f); l.agents.add(a); f.setObject(a); } else if ('A' <= id && id <= 'Z') { f = new Field(x,y); Box b = new Box(id, colors.get(id), f); l.boxes.add(b); f.setObject(b); } else if ('a' <= id && id <= 'z') { f = new Goal(id,x,y); l.goals.add((Goal)f); } else { f = new Field(x,y); } l.fields.add(f); l.fieldMap[x][y] = f; // Field links if(x!=0 && l.fieldMap[x-1][y] != null){ if (rawLevel.get(y).charAt(x-1) != '+') LinkFieldsHorizontal(f, l.fieldMap[x-1][y]); // link left } if(y!=0 && l.fieldMap[x][y-1] != null){ if (rawLevel.get(y-1).charAt(x) != '+') LinkFieldsVertical(f, l.fieldMap[x][y-1]); // link up (negative y) } } } //THE AGENTS NEED TO BE SORTED Collections.sort(l.agents, new Comparator<Agent>() { @Override public int compare(Agent a1, Agent a2) { int a1Id = Integer.parseInt(""+a1.getId()); int a2Id = Integer.parseInt(""+a2.getId()); return a1Id-a2Id; } }); return l; } private static void LinkFieldsHorizontal(Field east, Field west) { east.neighbours[dir.W.ordinal()] = west; west.neighbours[dir.E.ordinal()] = east; } private static void LinkFieldsVertical(Field south, Field north) { south.neighbours[dir.N.ordinal()] = north; north.neighbours[dir.S.ordinal()] = south; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/Parser.java
Java
oos
3,549
package client.clients; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; import client.Command; import client.Output; import client.Parser; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; public class SmartRandomWalkClient { private static Random rand = new Random(); private Level level; public SmartRandomWalkClient() throws IOException { level = Parser.readLevel(); /*// prints level, badly System.err.println("level.field_map.length: "+level.field_map.length); //System.err.println("level.field_map[y].length: "+level.field_map[y].length); for (int y = 0; y < level.field_map.length; y++) { for (int x = 0; x < level.field_map[y].length; x++) { Field f = level.field_map[x][y]; if (f != null) { if (f instanceof Goal) { System.err.println(((Goal) f).getId() + " Coords: [" + f.x + ":" + f.y + "]"); } } } }*/ } private BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // move some of this to I/O class ! public boolean update() throws IOException { Command[] commands = new Command[level.agents.size()]; //Store the commands and complete them, if server gives true. for (int i = 0; i < level.agents.size(); i++) { commands[i] = level.agents.get(i).act(); } boolean[] result = Output.Send(commands); for (int i = 0; i < result.length; i++) { if(result[i]) completeCommand(commands[i], level.agents.get(i)); } return true; } private void completeCommand(Command c, Agent a){ if (c.cmd.equals("Move")) completeMove(c,a); else if (c.cmd.equals("Pull")) completePull(c, a, (Box) a.getAtField().neighbours[c.dir2.ordinal()].object); else if (c.cmd.equals("Push")) completePush(c, a, (Box) a.getAtField().neighbours[c.dir1.ordinal()].object); } private void completeMove(Command c, Agent a) { a.getAtField().object = null; a.getAtField().neighbours[c.dir1.ordinal()].object = a; a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); } private void completePull(Command c, Agent a, Box o) { // Box moves to Agents' previous field o.getAtField().setObject(null); o.setAtField(a.getAtField()); a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } private void completePush(Command c, Agent a, Box o) { //Agent moves to Box's previous field a.getAtField().setObject(null); a.setAtField(o.getAtField()); o.setAtField(o.getAtField().neighbours[c.dir2.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } public static void main( String[] args ) { try { SmartRandomWalkClient client = new SmartRandomWalkClient(); while ( client.update() ); } catch ( Exception e ) { e.printStackTrace(); } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/clients/SmartRandomWalkClient.java
Java
oos
2,909
package client.clients; import java.io.IOException; import javax.swing.text.StyledEditorKit.BoldAction; import agent.objectives.DockABox; import agent.objectives.Objective; import constants.Constants; import constants.Constants.dir; import utils.Communication; import utils.Timer; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; import client.Command; import client.Output; import client.Parser; import client.planners.AStarPlanner; import client.planners.ClientPlanner; import client.planners.FOMAPrioritizedGoalPlanner; import client.planners.GoalCountPlanner; import client.planners.Planner; import client.planners.PrioritizedGoalPlanner; import client.planners.ProgressionPlanner; import client.planners.ProgressionPlannerWithGoalPriority; import client.planners.SimplePlanner; public class Client { private static Level level; private static Planner planner; private static boolean timer; public static int stepCount = 0; public static boolean[] agentsFailed; public Client(String plannerName) throws IOException { level = Parser.readLevel(); planner = getPlanner(plannerName, level); } public static void main(String[] args) { try { String plannerName = "simple"; // DEFAULT timer = true; if (args.length==1) plannerName = args[0]; else if (args.length==2 && args[1].toLowerCase().equals("notimer")) timer = false; Timer t1 = new Timer(); t1.takeTime(); Client client = new Client(plannerName); agentsFailed = new boolean[level.agents.size()]; t1.stop(); // System.err.println("Level parsed. Time taken: " + t1.toString()); System.err.println( "Hello from " + planner.getName()); while (client.update()) ; } catch (Exception e) { e.printStackTrace(); } } private static Planner getPlanner(String name, Level l) { //TODO: consider reflection if (name.toLowerCase().contains("compet")) { // if (l.agents.size()==1) // return new ProgressionPlanner(l); // else return new ClientPlanner(l); } else if (name.toLowerCase().contains("star")) { return new AStarPlanner(l); } else if (name.toLowerCase().contains("goal") && name.toLowerCase().contains("count")) { return new GoalCountPlanner(l); } else if (name.toLowerCase().contains("withgoalpriority")) { return new ProgressionPlannerWithGoalPriority(l); } else if (name.toLowerCase().contains("goal") && name.toLowerCase().contains("priori") && name.toLowerCase().contains("foma")) { return new FOMAPrioritizedGoalPlanner(l); } else if (name.toLowerCase().contains("client")) { return new ClientPlanner(l); } else if (name.toLowerCase().contains("goal") && name.toLowerCase().contains("priori")) { return new PrioritizedGoalPlanner(l); } else if (name.toLowerCase().contains("progr")) { return new ProgressionPlanner(l); } else if (name.toLowerCase().contains("simple")) { return new SimplePlanner(l); } return new SimplePlanner(l); } public boolean update() throws IOException { Command[] commands = new Command[level.agents.size()]; // Get commands from agents' commandQueue loadCommands(commands); // Check if all agents have no commands left. If true, plan new commands. boolean noOps = true; for (int i = 0; i < commands.length; i++) { if (commands[i] != null) noOps = false; } if (noOps) { // System.err.println("No ops !"); Timer t = new Timer(); planner.makePlan(); t.stop(); // System.err.println("Plan calculated. Time taken: " + t.toString()); loadCommands(commands); } // Send commands to server, receive results boolean[] result = Output.Send(commands); // Let all commands accepted by the server update the level state boolean failed = false; boolean conflictFound = false; Agent conflictingAgent = null; for (int i = 0; i < result.length; i++) { if(conflictingAgent != null){ if(conflictingAgent.getId() == level.agents.get(i).getId()){ //if the other agent wins, do what he says.. Agent a = level.agents.get(i); Command c = commands[i]; flushAgentCommands(level.agents.get(i), c); } } if (result[i]){ completeCommand(commands[i], level.agents.get(i)); } else { System.err.println("Conflict!!!!! " + i); Agent a = level.agents.get(i); Command c = commands[i]; //if (c.cmd.toLowerCase().equals("move")) if (c.cmd.toLowerCase().equals("move") || c.cmd.toLowerCase().equals("pull"))// agent moves { Object o = a.getAtField().neighbours[c.dir1.ordinal()].object; if (o == null) { Field agents_desired_field = a.getAtField().neighbours[c.dir1.ordinal()]; if(!Utils.CheckIfAnAgentWasOnThisFieldLastTurn(level, agents_desired_field)) removeField(agents_desired_field); } else if(o instanceof Box) { //A box is in the way. find which box Box otherBox = (Box)o; if(otherBox.getColor() == a.getColor()){ Objective newObjective = new DockABox(new Field(3, 6), otherBox, 15); a.objectives.addFirst(newObjective); } //Find an agent to move the box conflictingAgent = Communication.FindAgentToMoveBox(otherBox, level); a.obstacle = o; } else if(o instanceof Agent){ a.obstacle = o; } } else { //We are pushing and should look at the next field.. Object o = a.getAtField().neighbours[c.dir1.ordinal()].neighbours[c.dir1.ordinal()].object; if (o == null) { Field agents_desired_field = a.getAtField().neighbours[c.dir2.ordinal()]; if(!Utils.CheckIfAnAgentWasOnThisFieldLastTurn(level, agents_desired_field)) removeField(agents_desired_field); } else if(o instanceof Agent || o instanceof Box) { a.obstacle = o; } } flushAgentCommands(level.agents.get(i), c); //TODO: if there is no box or agent on the desired place it is a hidden obstacle -> remove it from graph updateBeliefs(commands[i], level.agents.get(i)); failed = true; } } agentsFailed = result; stepCount++; return true; } /** * Removes a field from the graph * @param field the field to be dereferenced. */ private void removeField(Field field) { for (dir direction : dir.values()) { Field neighbour = field.neighbours[direction.ordinal()]; neighbour.neighbours[Constants.oppositeDir(direction).ordinal()] = null; } } /** * Restores the agents objective from last iteration and the command queue from the error * @param agent * @param failedCommand The command on which the program failed */ private void flushAgentCommands(Agent agent, Command failedCommand) { agent.commandsNotCompleted.add(Constants.NOOP); agent.commandsNotCompleted.add(Constants.NOOP); agent.commandsNotCompleted.add(failedCommand); Command c; while ((c = agent.commandQueue.poll()) != null) agent.commandsNotCompleted.add(c); agent.objectives.addFirst(agent.tempObjective); agent.tempObjective = null; } private static void loadCommands(Command[] commands) { for (int i = 0; i < level.agents.size(); i++) { level.agents.get(i).lastLocation = level.agents.get(i).getAtField(); commands[i] = level.agents.get(i).commandQueue.poll(); } } private static void updateBeliefs(Command c, Agent a) { // TODO } // updates level by completing an agent command private static void completeCommand(Command c, Agent a) { if (c != null) { if (c.cmd.equals("Move")) completeMove(c, a); else if (c.cmd.equals("Pull")) completePull(c,a, (Box) a.getAtField().neighbours[c.dir2.ordinal()].object); else if (c.cmd.equals("Push")) completePush(c,a, (Box) a.getAtField().neighbours[c.dir1.ordinal()].object); } } private static void completeMove(Command c, Agent a) { a.getAtField().object = null; a.getAtField().neighbours[c.dir1.ordinal()].object = a; a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); } private static void completePull(Command c, Agent a, Box o) { // Box moves to Agents' previous field o.getAtField().setObject(null); o.setAtField(a.getAtField()); a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } private static void completePush(Command c, Agent a, Box o) { // Agent moves to Box's previous field a.getAtField().setObject(null); a.setAtField(o.getAtField()); o.setAtField(o.getAtField().neighbours[c.dir2.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/clients/Client.java
Java
oos
8,940
package client.clients; import java.io.*; import java.util.*; import client.Command; public class RandomWalkClient { private static Random rand = new Random(); public class Agent { // We don't actually use these for Randomly Walking Around private char id; private String color; Agent( char id, String color ) { this.id = id; this.color = color; } public String act() { return Command.every[rand.nextInt( Command.every.length )].toString(); } } private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); private List< Agent > agents = new ArrayList< Agent >(); public RandomWalkClient() throws IOException { readMap(); } private void readMap() throws IOException { Map< Character, String > colors = new HashMap< Character, String >(); String line, color; // Read lines specifying colors while ( ( line = in.readLine() ).matches( "^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$" ) ) { line = line.replaceAll( "\\s", "" ); color = line.split( ":" )[0]; for ( String id : line.split( ":" )[1].split( "," ) ) colors.put( id.charAt( 0 ), color ); } // Read lines specifying level layout while ( !line.equals( "" ) ) { for ( int i = 0; i < line.length(); i++ ) { char id = line.charAt( i ); if ( '0' <= id && id <= '9' ) agents.add( new Agent( id, colors.get( id ) ) ); } line = in.readLine(); } } public boolean update() throws IOException { String jointAction = "["; for ( int i = 0; i < agents.size() - 1; i++ ) jointAction += agents.get( i ).act() + ","; System.out.println( jointAction + agents.get( agents.size() - 1 ).act() + "]" ); System.out.flush(); // Disregard these for now, but read or the server stalls when outputbuffer gets filled! String percepts = in.readLine(); if ( percepts == null ) return false; return true; } public static void main( String[] args ) { // Use stderr to print to console System.err.println( "Hello from RandomWalkClient. I am sending this using the error outputstream" ); try { RandomWalkClient client = new RandomWalkClient(); while ( client.update() ) ; } catch ( IOException e ) { // Got nowhere to write to probably } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/client/clients/RandomWalkClient.java
Java
oos
2,239
package datastructures; import java.util.ArrayList; import java.util.Collection; import java.util.List; import client.Command; import LevelObjects.Box; import LevelObjects.Field; public class MoveActionSequence extends ActionSequence { private Field startField; private Field endField; public List<Box> boxesInTheWay; public MoveActionSequence(Field from, Field to, ArrayList<Command> commands) { startField = from; endField = to; super.commands = commands; } public Field getStartField() { return startField; } public void setStartField(Field startField) { this.startField = startField; } public Field getEndField() { return endField; } public void setEndField(Field endField) { this.endField = endField; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/MoveActionSequence.java
Java
oos
790
package datastructures; import LevelObjects.Field; public class MoveBoxActionSequence extends ActionSequence { private Field agentLocation; private Field boxLocation; private Field targetLocation; public Field getAgentLocation() { return agentLocation; } public void setAgentLocation(Field agentLocation) { this.agentLocation = agentLocation; } public Field getBoxLocation() { return boxLocation; } public void setBoxLocation(Field boxLocation) { this.boxLocation = boxLocation; } public Field getTargetLocation() { return targetLocation; } public void setTargetLocation(Field targetLocation) { this.targetLocation = targetLocation; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/MoveBoxActionSequence.java
Java
oos
701
package datastructures; import LevelObjects.Field; public class GoalActionSequence extends ActionSequence { private Field agentStartLocation; private Field agentEndField; private Field boxStartLocation; private Field boxEndLocation; public Field getBoxStartLocation() { return boxStartLocation; } public void setBoxStartLocation(Field boxStartLocation) { this.boxStartLocation = boxStartLocation; } public Field getBoxEndLocation() { return boxEndLocation; } public void setBoxEndLocation(Field boxEndLocation) { this.boxEndLocation = boxEndLocation; } public Field getAgentEndField() { return agentEndField; } public void setAgentEndField(Field agentEndField) { this.agentEndField = agentEndField; } public Field getAgentStartLocation() { return agentStartLocation; } public void setAgentStartLocation(Field agentStartLocation) { this.agentStartLocation = agentStartLocation; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/GoalActionSequence.java
Java
oos
965
package datastructures; public class FieldBlockedChange { public int time; public boolean changeToBlocked; public FieldBlockedChange(int time, boolean c){ this.time = time; this.changeToBlocked = c; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/FieldBlockedChange.java
Java
oos
217
package datastructures; import java.util.ArrayList; import LevelObjects.Agent; import LevelObjects.Field; public class FieldInState extends ObjectInState { public ArrayList<FieldBlockedChange> blockedTimeChangeIndexes; public FieldInState(Field f) { super(); this.f = f; blockedTimeChangeIndexes = new ArrayList<FieldBlockedChange>(); } public FieldInState(Field f, ArrayList<FieldBlockedChange> blockedTimeIndexes) { super(); this.f = f; this.blockedTimeChangeIndexes = blockedTimeIndexes; } public boolean changesStatusInFuture(int timeStep){ for (FieldBlockedChange blockedTime : blockedTimeChangeIndexes) { if (blockedTime.time >= timeStep && blockedTime.changeToBlocked == true) { return true; } } return false; } public boolean freeInInterval(int start, int end){ // System.err.println("Checking " + this.f.toString() + " intervals: " + start + "-" +end); // for (FieldBlockedChange fb : blockedTimeChangeIndexes) { // System.err.print(fb.time+ " "); // } boolean previous = false; for (FieldBlockedChange blockedTime : blockedTimeChangeIndexes) { if (blockedTime.time > start && blockedTime.time <= end) { // System.err.println("HEEER"); return false; } previous = blockedTime.changeToBlocked; if(blockedTime.time > end){ return !previous; } } return !previous; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/FieldInState.java
Java
oos
1,376
package datastructures; import java.util.ArrayList; import LevelObjects.Field; import client.Command; public abstract class ActionSequence { private ActionSequence parent; public ArrayList<Field> fields; public ActionSequence getParent() { return parent; } public void setParent(ActionSequence parent) { this.parent = parent; } protected ArrayList<Command> commands; public ArrayList<Command> getCommands() { return commands; } public void setCommands(ArrayList<Command> commands) { this.commands = commands; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/ActionSequence.java
Java
oos
574
package datastructures; import LevelObjects.Agent; import LevelObjects.Field; public class AgentInState extends ObjectInState { public Agent a; public AgentInState(Agent a, Field f) { super(); this.a = a; this.f = f; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/AgentInState.java
Java
oos
237
package datastructures; import java.util.ArrayList; import LevelObjects.Goal; import client.Command; public class State implements Comparable<State> { public int g; public int f; public ArrayList<AgentInState> agents; public ArrayList<BoxInState> boxes; public ArrayList<FieldInState> fields; public State parent; public ArrayList<Command> commandFromParent; public int heuristicValue; public StateGoal goal; //Used for merging states. We know which step we are in, and all commands from this step should be used for merging. public int indexOfCommands; //Should be FOMA compatible public ArrayList<ActionSequence> actionSequencesFromParent; public State() { agents = new ArrayList<AgentInState>(); boxes = new ArrayList<BoxInState>(); fields = new ArrayList<FieldInState>(); commandFromParent = new ArrayList<Command>(); actionSequencesFromParent = new ArrayList<ActionSequence>(); } @Override public int compareTo(State o) { return this.heuristicValue - o.heuristicValue; } public void printFieldChanges(){ for (FieldInState f : fields) { System.err.print(f.f.toString()); for (FieldBlockedChange fb : f.blockedTimeChangeIndexes) { System.err.print(" " + fb.time + " " + fb.changeToBlocked); } System.err.println(); } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/State.java
Java
oos
1,302
package datastructures; import LevelObjects.Box; import LevelObjects.Field; public class BoxInState extends ObjectInState { public Box b; public BoxInState(Box b, Field f) { super(); this.b = b; this.f = f; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/BoxInState.java
Java
oos
233
package datastructures; import LevelObjects.Field; public abstract class ObjectInState implements Comparable<ObjectInState> { public Field f; @Override public int compareTo(ObjectInState o) { if (this.f.x != o.f.y) { return this.f.x-o.f.x; } else{ return this.f.y-o.f.y; } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/ObjectInState.java
Java
oos
307
package datastructures; import java.util.ArrayList; import LevelObjects.*; public class BoxCost { public Box box; public int cost; public ArrayList<GoalCost> goalCosts; public BoxCost() { goalCosts = new ArrayList<GoalCost>(); } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/BoxCost.java
Java
oos
265
package datastructures; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; public class StateGoal { public Field agentToPos; public Field boxToPos; public BoxInState box; public AgentInState agent; public boolean isMoveToBoxGoal; public boolean isClearPathGoal; public int nextGoalIndex; }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/StateGoal.java
Java
oos
330
package datastructures; import LevelObjects.Field; import client.Command; public class GoalSequenceNode implements Comparable<GoalSequenceNode> { public GoalSequenceNode parent; public Field boxLocation; public Field agentLocation; public Command action; public int timeStep; public int f; public int g; public GoalSequenceNode(Field boxLocation, Field agentLocation, Command action) { super(); this.boxLocation = boxLocation; this.agentLocation = agentLocation; this.action = action; } @Override public int compareTo(GoalSequenceNode arg0) { return this.f - arg0.f; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/GoalSequenceNode.java
Java
oos
603
package datastructures; import LevelObjects.*; public class GoalCost { public GoalCost(Goal goal, int cost) { this.cost = cost; this.goal = goal; } public Goal goal; public int cost; }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/datastructures/GoalCost.java
Java
oos
212
package utils; public class Timer { private long _time; public volatile long time; public Timer() { time = 0; _time = System.currentTimeMillis(); } public void takeTime() { time = 0; _time = System.currentTimeMillis(); } public long stop() { time = System.currentTimeMillis() - _time; return time; } public int getElapsedTime() { return (int)(System.currentTimeMillis() - _time); } public void reset() { _time = System.currentTimeMillis(); time = 0; } public String toString() { int elapsed = getElapsedTime(); if (elapsed < 1000) return Integer.toString(elapsed) + " miliseconds"; else if (elapsed < 60000) { int seconds = elapsed/1000; int milis = (int)(elapsed % ((int)(elapsed/1000)*1000)); return Integer.toString(seconds) + "." + Integer.toString(milis) + " seconds"; } else { int minutes = elapsed/60000; int seconds = (int)((((double)elapsed)/60000.0f) % (int)(elapsed/60000)); return Integer.toString(minutes) + " minutes " + Integer.toString(seconds) + " seconds"; } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/Timer.java
Java
oos
1,119
package utils; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import LevelObjects.Field; public class BFS { public enum NodeColour { WHITE, GRAY, BLACK } private static class Node { int data; int distance; Node parent; NodeColour colour; Field field; public Node(int data) { this.data = data; } public String toString() { return "(" + data + ",d=" + distance + ")"; } } Map<Node, List<Node>> nodes; private BFS() { nodes = new HashMap<Node, List<Node>>(); } public static int bfs(Field start_field, Field end_field) { ArrayList<String> fieldList = new ArrayList<String>(); Node start = new Node(0); start.distance = 0; start.parent = null; start.field = start_field; fieldList.add(start.field.toString()); Queue<Node> q = new ArrayDeque<Node>(); q.add(start); while (!q.isEmpty()) { Node u = q.remove(); List<Node> adjacent_u = new ArrayList<Node>(); adjacent_u = getNeighbours(u, fieldList); if (adjacent_u != null) { for (Node v : adjacent_u) { if(v.field.x == end_field.x && v.field.y == end_field.y){ return u.distance + 1; } v.distance = u.distance + 1; v.parent = u; q.add(v); // System.err.println("Field " + v.field + " added to path"); fieldList.add(v.field.toString()); } } } return -1; } public static int bfs(Field start_field, Field end_field, Field blocked_field) { ArrayList<String> fieldList = new ArrayList<String>(); Node start = new Node(0); Node blocked = new Node(0); start.distance = 0; start.parent = null; start.field = start_field; blocked.field = blocked_field; fieldList.add(start.field.toString()); fieldList.add(blocked.field.toString()); Queue<Node> q = new ArrayDeque<Node>(); q.add(start); while (!q.isEmpty()) { Node u = q.remove(); List<Node> adjacent_u = new ArrayList<Node>(); adjacent_u = getNeighbours(u, fieldList); if (adjacent_u != null) { for (Node v : adjacent_u) { if(v.field.x == end_field.x && v.field.y == end_field.y){ return u.distance + 1; } v.distance = u.distance + 1; v.parent = u; q.add(v); // System.err.println("Path found. Field " + v.field + " added to path"); fieldList.add(v.field.toString()); } } } return -1; } private static List<Node> getNeighbours(Node u, ArrayList<String> fieldList){ List<Node> adjacent_u = new ArrayList<Node>(); Node n = null; for (int i = 0; i < 4; i++) { if(u.field.neighbours[i] != null){ Field f = u.field.neighbours[i]; if(!fieldList.contains(f.toString())){ n = new Node(i); n.field = u.field.neighbours[i]; adjacent_u.add(n); } } } return adjacent_u; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/BFS.java
Java
oos
3,792
package utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; public class GoalPriority { /** * Goal prioritization. Checks to see for every goal, how many boxes and goals are disconnected, by placing this goal. * This function can be used at any time. * @param level * @param ignore_goals_completed, if you want to ignore completed goals. * @return a Goal array with the prioritized number in goal.getPriority() */ public static ArrayList<Goal> createGoalPrioritization(Level level, boolean ignore_goals_completed){ // tester(level); Timer t1 = new Timer(); t1.takeTime(); for (Goal goal : level.goals) { //ignore completed goals.. boolean ignore_goal = false; //only enter if completed goals should be ignored if(ignore_goals_completed){ ignore_goal = checkToSeeIfGoalIsOnBox(goal, level); } Timer t2 = new Timer(); t2.takeTime(); if(!(ignore_goal && ignore_goals_completed)){ //first look at fields north and south || east and west are walls or other blocking elements? goals? goals later //If so level has been disconnected //look and see if the disconnect is a problem. int count_free_neighbours = countAdjacentFields(goal); // System.err.println("Goal " + goal.getId() + " has adjacent free fields: " + count_free_neighbours); if(count_free_neighbours == 1){ //Goal only has one Neighbour and should have a low value in goal priority //Know further tests. This is highest priority! } else { List<Field> free_neighbours = getFreeNeighbours(goal); int disconnected_goals = 0; switch(count_free_neighbours){ case 2: goal.setPriority(goal.getPriority() + 1); //Goal only has two Neighbours and has a high posibility of breaking the map into to areas when box on goal //See if path it is possible to get from one neighbour to the other disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; case 3: goal.setPriority(goal.getPriority() + 2); //See if path it is possible to get from one neighbour to the other. There are now 3 neighbours. 0,1,2 disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(2).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; case 4: goal.setPriority(goal.getPriority() + 3); //See if path it is possible to get from one neighbour to the other. There are now 4 neighbours. 0,1,2,3 disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(3).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(0).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(3).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(0).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(3).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; } } } t2.stop(); // System.err.println("Goal " + goal.getId() +" prioritized.. Time taken: " + t2.toString()); } t1.stop(); // System.err.println("Goals prioritized. Time taken: " + t1.toString()); return level.goals; } private static void tester(Level level){ System.err.println("----------TESTER-----------"); Agent agent = level.agents.get(0); System.err.println("----------testing distance-----------"); for (Goal goal : level.goals) { System.err.println("Agent " + agent.getId() + " is " + BFS.bfs(agent.getAtField(), goal.getClone()) + " from goal " + goal.getId()); } System.err.println("----------TESTER-----------"); Field f = new Field(6,3); for (Goal goal : level.goals) { System.err.println("Agent " + agent.getId() + " at " + agent.getAtField() + " is " + BFS.bfs(agent.getAtField(), goal.getClone(), f) + " from goal " + goal.getId() + " at " + goal.getClone() + ". Field " + f + " is blocked"); } System.err.println("---------------------"); } private static int countGoalDisconnectedFromBox(List<Box> boxes, List<Goal> goals, Goal current_goal){ int goals_disconnecting = 0; boolean box_found = false; for (Goal goal : goals) { if(goal != current_goal){ box_found = false; for (Box box : boxes) { if(box.getId() == goal.getId()){ if(BFS.bfs(box.getAtField(), goal.getClone(), current_goal.getClone()) != -1){ box_found = true; } } } if(!box_found){ goals_disconnecting++; } } } return goals_disconnecting; } private static Goal isAgentDisconnectedFromGoal(Agent agent, List<Goal> goals, Goal current_goal){ for (Goal goal : goals) { if(goal != current_goal){ if(BFS.bfs(agent.getAtField(), goal.getClone(), current_goal.getClone()) == -1){ return goal; } } } return null; } private static List<Field> getFreeNeighbours(Goal goal){ List<Field> free_neighbours = new ArrayList<Field>(); for (int i = 0; i < 4; i++) { if(goal.neighbours[i] != null) free_neighbours.add(goal.neighbours[i]); } return free_neighbours; } private static int countAdjacentFields(Goal goal){ int counter = 0; for (int i = 0; i < 4; i++) { if(goal.neighbours[i] != null) counter++; } return counter; } private static boolean checkToSeeIfGoalIsOnBox(Goal goal, Level level){ boolean ignoreGoal =false; for (Box box : level.boxes) { if(goal.getId() == box.getId()){ if(goal.x == box.getAtField().x && goal.y == box.getAtField().y){ ignoreGoal = true; } } } return ignoreGoal; } private static int getDisconnectedGoalsFromBoxes(Field free_neighbours1, Field free_neighbours2, Level level, Goal goal){ int disconnected_goals = 0; //See if the two neighbours 1 and 2 are disconnected with the middle field blocked. if(BFS.bfs(free_neighbours1, free_neighbours2, goal.getClone()) == -1){ //Okay, there is a disconnect.Now count goals disconnected from boxes with the same id. disconnected_goals = countGoalDisconnectedFromBox(level.boxes, level.goals, goal); goal.setPriority(goal.getPriority() + disconnected_goals); } return disconnected_goals; } /** * Finds the goal with the highest priority for the given agent * @param agent: we want to find best goal for * @param level: containing level.goals to search through * @returns Goal goal with the highest priority */ public static Goal FindGoalWithHighestPriority(Agent agent, Box box, Level level) { char id = box.getId(); Goal candidate = null; for (Goal goal : level.goals) { if(goal.getId() == id){ if(candidate != null){ if(candidate.getPriority() > goal.getPriority()) candidate = goal; } else{ candidate = goal; } } } return candidate; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/GoalPriority.java
Java
oos
8,627
package utils; import constants.Constants.dir; import LevelObjects.Field; import client.Command; public class AStarField implements Comparable<AStarField> { public Field field; public int g; public int f; public int h; public Command c; public int timeStep; public AStarField(Field field) { this.field = field; } @Override public int compareTo(AStarField o) { return this.f - o.f; } public Field neighborTo(dir d) { return field.neighbours[d.ordinal()]; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/AStarField.java
Java
oos
526
package utils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import constants.Constants; import constants.Constants.Color; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxCost; import datastructures.BoxInState; import datastructures.GoalActionSequence; import datastructures.GoalCost; import datastructures.GoalSequenceNode; import datastructures.MoveActionSequence; import datastructures.MoveBoxActionSequence; import datastructures.State; import datastructures.StateGoal; public class Utils { /** * * @param f The field * @param d The direction * @return true if the neighboring field in the direction is free */ public static boolean isNeighborFree(Field f, dir d){ return (f.neighbours[d.ordinal()] != null && f.neighbours[d.ordinal()].object == null); } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return a list of commands taking the agent from the from-field to the to-field */ public static MoveActionSequence findRoute(Level l, Field from, Field to, Collection<Field> blockedFields) { HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); AStarField curField = openSet.poll(); while (curField != null) { if (curField.field.equals(to)) break; closedSet.add(curField.field); int tentativeGScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if(blockedFields != null){ if ( neighbor == null || blockedFields.contains(neighbor) || closedSet.contains(neighbor)) continue; } else{ if ( neighbor == null || closedSet.contains(neighbor)) continue; } AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field == neighbor) neighbourInOpenSet = aOpen; } if (neighbourInOpenSet != null && tentativeGScore > neighbourInOpenSet.g) { continue; } else if (neighbourInOpenSet == null ){ neighbourInOpenSet = new AStarField(curField.neighborTo(d)); neighbourInOpenSet.g = tentativeGScore; neighbourInOpenSet.f = neighbourInOpenSet.g + heuristicEstimate(neighbourInOpenSet.field, to, HeuristicType.MANHATTAN); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); openSet.add(neighbourInOpenSet); } } curField = openSet.poll(); } //If currentField is null, we didn't find a path. if (curField == null) return null; ArrayList<Command> commands = new ArrayList<Command>(); ArrayList<Field> fields = new ArrayList<Field>(); while (cameFrom.get(curField) != null) { fields.add(curField.field); commands.add(curField.c); curField = cameFrom.get(curField); } Collections.reverse(commands); Collections.reverse(fields); MoveActionSequence mas = new MoveActionSequence(from, to, commands); mas.fields = fields; return mas; } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return a list of commands taking the agent from the from-field to the to-field */ public static MoveActionSequence findRouteIgnoreObstacles(Level l, Agent agent, Field from, Field to, Collection<Field> blockedFields) { HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (agent.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); AStarField curField = openSet.poll(); while (curField != null) { if (curField.field.equals(to)) break; closedSet.add(curField.field); int tentativeGScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if ( neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field == neighbor) neighbourInOpenSet = aOpen; } if (neighbourInOpenSet != null) continue; neighbourInOpenSet = new AStarField(curField.neighborTo(d)); neighbourInOpenSet.g = tentativeGScore; if (ownBoxFields.contains(curField.field)) neighbourInOpenSet.g = tentativeGScore+50; else if (othersBoxFields.contains(curField.field)) neighbourInOpenSet.g = tentativeGScore+200; neighbourInOpenSet.f = neighbourInOpenSet.g + heuristicEstimate(neighbourInOpenSet.field, to, HeuristicType.MANHATTAN); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); openSet.add(neighbourInOpenSet); } curField = openSet.poll(); } //If currentField is null, we didn't find a path. if (curField == null) return null; ArrayList<Command> commands = new ArrayList<Command>(); ArrayList<Field> fields = new ArrayList<Field>(); while (cameFrom.get(curField) != null) { fields.add(curField.field); commands.add(curField.c); //if (ownBoxFields.contains(curField.f)) curField = cameFrom.get(curField); } Collections.reverse(commands); Collections.reverse(fields); MoveActionSequence mas = new MoveActionSequence(from, to, commands); mas.fields = fields; return mas; } /** * * @param l The level * @param from The field to start from * @param to The field to get to * @return */ public static MoveActionSequence findRoute(Level l, Field from, Field to) { return findRoute(l, from, to, null); } public enum HeuristicType { EUCLID, MANHATTAN } public static int heuristicEstimate(Field a, Field goal, HeuristicType h) { switch (h) { case EUCLID: return heuristicEstimateEuclid(a, goal); case MANHATTAN: return heuristicEstimateManhattan(a, goal); default: return heuristicEstimateManhattan(a, goal); } } public static int heuristicEstimateEuclid(Field a, Field goal) { int h = (int) Math.sqrt(Math.pow(Math.abs(a.x - goal.x), 2) + Math.pow(Math.abs(a.y - goal.y), 2)); return h; } // Manhattan distance public static int heuristicEstimateManhattan(Field a, Field goal) { return Math.abs(a.x - goal.x) + Math.abs(a.y - goal.y); } public static boolean allGoalsHasBoxes(State currentState, Level level) { boolean[] goalFulfilled = new boolean[level.goals.size()]; int index = 0; for (Goal g : level.goals) { for (BoxInState bPos : currentState.boxes) { if (bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { goalFulfilled[index] = true; } } index++; } boolean returnBool = true; for (boolean b : goalFulfilled) { if (!b) return false; } return returnBool; } public static boolean allGoalsHasBoxes(Level level) { int goalsFulfilled = 0; int totalGoals = level.goals.size(); for (Goal goal : level.goals) { for (Box box : level.boxes) { if (box.getAtField() == new Field(goal.x,goal.y) && Character.toLowerCase(box.getId()) == goal.getId()) { goalsFulfilled++; } } } if(goalsFulfilled == totalGoals) return true; else return false; } /** * checks if all goals has been fulfilled for the given agent * @param agent * @param level * @returns null if all goals are fulfilled, otherwise the goal with the highest priority */ public static Goal allOfAgentGoalsHasBoxes(Agent agent, Level level) { // Box current_box_color = a.possibleBoxesToGoals.keySet() int goalsFulfilled = 0; int totalBoxes = 0; Goal highestPriority = null; for (Goal goal : level.goals) { for (Box box : level.boxes) { if (agent.possibleBoxesToGoals.containsKey(box) && Utils.boxFitsGoal(box, goal)){ totalBoxes++; if (box.getAtField() == new Field(goal.x,goal.y) && Character.toLowerCase(box.getId()) == goal.getId()) { goalsFulfilled++; } else { if(highestPriority != null){ if(highestPriority.getPriority() > goal.getPriority()) highestPriority = goal; } else{ highestPriority = goal; } } } } } if(goalsFulfilled <= totalBoxes) return null; return highestPriority; } public static MoveBoxActionSequence findEmptyFieldRoute(Level l, Agent a, Box b, Field freeField, Field agentFromField, Field agentToField, Field boxFromField, Collection<Field> blockedFields) { GoalActionSequence ga = findGoalRoute(l, a, b, agentFromField, agentToField, boxFromField, freeField, blockedFields); if (ga == null) return null; MoveBoxActionSequence mb = new MoveBoxActionSequence(); mb.setAgentLocation(ga.getAgentStartLocation()); mb.setBoxLocation(ga.getBoxStartLocation()); mb.setCommands(ga.getCommands()); mb.setTargetLocation(ga.getBoxEndLocation()); return mb; } public static Field getFreeField(Level l, Agent a, Box b, Field agentFromField, Field boxFromField, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); Field current = boxFromField; Field candidate = current; int depth = 0; while (current != null && depth <= maxDepth) { candidate = current; closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if ( neighbor != null && !blockedFields.contains(neighbor) && !closedSet.contains(neighbor) && (neighbor instanceof Goal && includeGoalFields)) openSet.add(neighbor); } current = openSet.poll(); } return candidate; } public static List<Field> getFreeFields(Field boxFromField, Collection<Field> blockedFields, int maxDepth, int maxReturnedFields, boolean includeGoalFields) { List<Field> l = getFreeFields(boxFromField, blockedFields, maxDepth, includeGoalFields); if (l.size()>maxReturnedFields) return l.subList(0, maxReturnedFields-1); return l; } public static ArrayList<Field> getFreeFields(Field boxFromField, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); Field current = boxFromField; ArrayList<Field> candidates = new ArrayList<Field>(); candidates.add(current); int depth = 0; while (current != null && depth <= maxDepth) { closedSet.add(current); int count = 0; for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if ( neighbor != null && !blockedFields.contains(neighbor) && !closedSet.contains(neighbor) && (neighbor instanceof Goal && includeGoalFields)) { count++; openSet.add(neighbor); } } if (count==0) // a dead end is good! candidates.add(current); current = openSet.poll(); } return candidates; } public static Field getFirstFreeField(Field fromField, Collection<Field> escapeFromFields, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); if (!escapeFromFields.contains(fromField)) escapeFromFields.add(fromField); Field current = fromField; int depth = 0; whileloop: while (current != null && depth <= maxDepth) { closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if (neighbor == null) continue; if (!escapeFromFields.contains(neighbor)) { current = neighbor; break whileloop; } if ( escapeFromFields.contains(neighbor) && !closedSet.contains(neighbor) && !blockedFields.contains(neighbor) && (!(neighbor instanceof Goal) || includeGoalFields)) { openSet.add(neighbor); } } current = openSet.poll(); } return current; } public static Field getFirstFreeFieldkcl(Field fromField, Collection<Field> escapeFromFields, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); if (!escapeFromFields.contains(fromField)) escapeFromFields.add(fromField); Field current = fromField; int depth = 0; whileloop: while (current != null && depth <= maxDepth) { closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if (neighbor == null) continue; if (!escapeFromFields.contains(neighbor)) { current = neighbor; break whileloop; } if ( escapeFromFields.contains(neighbor) && !closedSet.contains(neighbor) && !blockedFields.contains(neighbor) && (!(neighbor instanceof Goal) || includeGoalFields)) { openSet.add(neighbor); } } current = openSet.poll(); } return current; } // We know that the agent a has a box. Now we want to move the box to the // goal. public static GoalActionSequence findGoalRoute(Level l, Agent a, Box b, Field agentFromField, Field agentToField, Field boxFromField, Field boxToField, Collection<Field> blockedFields) { dir boxDir = null; GoalSequenceNode root = new GoalSequenceNode(boxFromField, agentFromField, null); PriorityQueue<GoalSequenceNode> queue = new PriorityQueue<GoalSequenceNode>(); // prune looped states (if agent and box ends up in a state already explored) HashMap<Field, ArrayList<Field>> closedSet = new HashMap<Field, ArrayList<Field>>(); //adding initial state to list set of explored states: ArrayList<Field> tempList = new ArrayList<Field>(); tempList.add(boxFromField); closedSet.put(agentFromField, tempList); int g = 0; root.g = g; root.f = root.g + heuristicEstimateManhattan(boxFromField, boxToField); //Add a closed set. queue.add(root); GoalSequenceNode currentNode = queue.poll(); while (currentNode != null && (currentNode.boxLocation != boxToField || currentNode.agentLocation != agentToField)) { boxDir = Agent.getBoxDirection(currentNode.agentLocation,currentNode.boxLocation); ArrayList<Command> foundCommands = addPossibleBoxCommandsForDirection(boxDir, currentNode.agentLocation, currentNode.boxLocation, blockedFields); for (Command command : foundCommands) { Field boxLocation = null; Field agentLocation = null; if (command.cmd.equals("Push")) { agentLocation = currentNode.boxLocation; boxLocation = currentNode.boxLocation.neighbours[command.dir2 .ordinal()]; } else { boxLocation = currentNode.agentLocation; agentLocation = currentNode.agentLocation.neighbours[command.dir1 .ordinal()]; } // Do we already have a way to get to this state? if (closedSet.containsKey(agentLocation)) { if (closedSet.get(agentLocation).contains(boxLocation)) continue; else // the agent has been here before but without the box in same location closedSet.get(agentLocation).add(boxLocation); } else { // neither the agent or the box has been here before. Update DS and create node in BTtree: ArrayList<Field> tempListe = new ArrayList<Field>(); tempListe.add(boxLocation); closedSet.put(agentLocation, tempListe); } GoalSequenceNode node = new GoalSequenceNode(boxLocation,agentLocation, command); node.parent = currentNode; node.g = node.parent.g+1; node.f = node.g + heuristicEstimateManhattan(boxLocation, boxToField); queue.add(node); } if (queue.isEmpty()) { //TODO: we have searched to the end without finding a solution. Move boxes to get access to goals return null; } currentNode = queue.poll(); } GoalActionSequence returnSequence = new GoalActionSequence(); returnSequence.setAgentStartLocation(currentNode.agentLocation); returnSequence.setBoxStartLocation(currentNode.boxLocation); ArrayList<Command> commands = new ArrayList<Command>(); while (currentNode.parent != null) { commands.add(currentNode.action); currentNode = currentNode.parent; } Collections.reverse(commands); returnSequence.setCommands(commands); return returnSequence; } public static ArrayList<Command> addPossibleBoxCommandsForDirection(dir direction, Field agentLocationInPlan, Field boxLocationInPlan, Collection<Field> blockedFields) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); // Find possible pull commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction if (d != direction && agentLocationInPlan.neighbours[d.ordinal()] != null && !blockedFields.contains(agentLocationInPlan.neighbours[d.ordinal()])) { possibleCommands.add(new Command("Pull", d, direction)); } } // Find possible push commands for (dir d : dir.values()) { // We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && boxLocationInPlan.neighbours[d.ordinal()] != null && !blockedFields.contains(boxLocationInPlan.neighbours[d.ordinal()])) { possibleCommands.add(new Command("Push", direction, d)); } } return possibleCommands; } public static boolean boxFitsGoal(Box b, Goal g){ return (g.getId() == Character.toLowerCase(b.getId())); } public static State getState(ArrayList<Agent> agents, ArrayList<Box> boxes) { State firstState = new State(); for (Agent a : agents) { firstState.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : boxes) { firstState.boxes.add(new BoxInState(b, b.getAtField())); } return firstState; } public static ArrayList<Box> getBoxesWithId(ArrayList<Box> boxes, char id) { ArrayList<Box> boxesWithId = new ArrayList<Box>(); for (Box b : boxes) if (b.getId() == id) boxesWithId.add(b); return boxesWithId; } public static ArrayList<Agent> getAgents( ArrayList<Agent> agents, Color color) { ArrayList<Agent> returnAgents = new ArrayList<Agent>(); for (Agent agent : agents) { if (agent.getColor() == color) { returnAgents.add(agent); } } return returnAgents; } public static boolean isFieldAvailable(Field f, ArrayList<Field> blockedFields) { for (Field field : blockedFields) { if (field == f) return false; } return true; } public static ArrayList<BoxInState> getBoxesInState(ArrayList<BoxInState> boxes, char id) { ArrayList<BoxInState> boxesWithId = new ArrayList<BoxInState>(); for (BoxInState b : boxes) if (b.b.getId() == id) boxesWithId.add(b); return boxesWithId; } public static ArrayList<Box> getBoxesInLevel(ArrayList<Box> boxes, char id) { ArrayList<Box> boxesWithId = new ArrayList<Box>(); for (Box b : boxes) if (b.getId() == id) boxesWithId.add(b); return boxesWithId; } public static ArrayList<AgentInState> getAgentsInState(ArrayList<AgentInState> agents, Color color) { ArrayList<AgentInState> agentsInState = new ArrayList<AgentInState>(); for (AgentInState agentInState : agents) { if (agentInState.a.getColor() == color) agentsInState.add(agentInState); } return agents; } public static ArrayList<State> getState(ArrayList<AgentInState> agents, ArrayList<BoxInState> boxes, Agent agent, Field agentToPos, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (AgentInState a : agents) { if (a.a != agent) firstState.agents.add(a); else firstState.agents.add(new AgentInState(agent, agentToPos)); } for (BoxInState b : boxes) { firstState.boxes.add(b); } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; returnStates.add(firstState); } return returnStates; } public static ArrayList<State> getStateFromLevel(ArrayList<Agent> agents, ArrayList<Box> boxes, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (Agent a : agents) { firstState.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : boxes) { firstState.boxes.add(new BoxInState(b, b.getAtField())); } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; returnStates.add(firstState); } return returnStates; } public static State getStateFromLevel(ArrayList<Agent> agents, ArrayList<Box> boxes) { State state = new State(); for (Agent a : agents) { state.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : boxes) { state.boxes.add(new BoxInState(b, b.getAtField())); } return state; } public static ArrayList<State> getState(ArrayList<AgentInState> agents, ArrayList<BoxInState> boxes, Box box, Field boxPos, Agent agent, Field agentPos, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (AgentInState a : agents) { if (a.a != agent) firstState.agents.add(a); else firstState.agents.add(new AgentInState(agent, agentPos)); } for (BoxInState b : boxes) { if(b.b != box) firstState.boxes.add(b); else { firstState.boxes.add(new BoxInState(box, boxPos)); } } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; returnStates.add(firstState); } return returnStates; } public static boolean isFieldClear(State currentState, Field field) { for (AgentInState a : currentState.agents) { if(a.f == field) return false; } for (BoxInState b : currentState.boxes) { if(b.f == field) return false; } return true; } public static ArrayList<Field> findFreeField(Level level, ArrayList<Field> fields) { ArrayList<Field> returnFields = new ArrayList<Field>(); for (Field field : level.fields) { if(!fields.contains(field)) returnFields.add(field); } return returnFields; } public static BoxInState getBoxAtField(State currentState, Field firstBoxAtField) { for (BoxInState b : currentState.boxes) { if (b.f.equals(firstBoxAtField)) { return b; } } return null; } public static ArrayList<Box> getBoxesWithColor(ArrayList<Box> boxes, Color color) { ArrayList<Box> returnBoxes = new ArrayList<Box>(); for (Box box : boxes) { if (box.getColor() == color) { returnBoxes.add(box); } } return returnBoxes; } public static ArrayList<Goal> getGoalsWithId(ArrayList<Goal> goals, char id) { ArrayList<Goal> returnGoals = new ArrayList<Goal>(); for (Goal goal : goals) { if (goal.getId() == id) { returnGoals.add(goal); } } return returnGoals; } // public static ArrayList<StateGoal> getStateGoalFromField(Field goal) { // // ArrayList<StateGoal> returnGoals = new ArrayList<StateGoal>(); // // for (dir d : dir.values()) { // if (goal.neighbours[d.ordinal()] == null) continue; // // StateGoal stateGoal = new StateGoal(); // // stateGoal.agentToPos = goal.neighbours[d.ordinal()]; // // returnGoals.add(stateGoal); // } // // return returnGoals; // } public static boolean allGoalsAtHasBoxes(State currentState, Level level, ArrayList<Goal> agentGoals) { boolean[] goalFulfilled = new boolean[agentGoals.size()]; int index = 0; for (Goal g : agentGoals) { for (BoxInState bPos : currentState.boxes) { if (bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { goalFulfilled[index] = true; } } index++; } boolean returnBool = true; for (boolean b : goalFulfilled) { if (!b) return false; } return returnBool; } /** * Calculates an a* like heuristic considering the traveled distance and the goal count * @param state * @param level * @return */ public static int CalculateStateHeuristic(State state, Level level) { int goalCountWeight = 5; int gScoreWeight = 1; int numberOfFulfilledGoals = 0; for (Goal g : level.goals) { for (BoxInState bPos : state.boxes) { if ( bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { numberOfFulfilledGoals++; } } } int gScore = 0; // the g score is the cost of travelling here in terms of actionSequences (NOT actions) State parent = state; while(parent != null) { parent = parent.parent; gScore++; } return 1000 - (goalCountWeight*numberOfFulfilledGoals - gScoreWeight * gScore); } public static BoxInState findBoxInCompletedState(State currentState, Box box) { BoxInState boxInState = currentState.goal.box; for (BoxInState b : currentState.boxes) { if (b.b == boxInState.b && box == b.b) { return new BoxInState(box, currentState.goal.boxToPos); } else if (b.b == box) { return b; } } return null; } public static void findPossibleBoxes(){ } /** * Testing to if an agent can reach its boxes * @param level * @param agent * @param boxes * @return BoxInState it can reach */ public static HashMap<Box, BoxCost> findPossibleBoxes(Level level, Agent agent){ HashMap<Box, BoxCost> possibleBoxes = new HashMap<Box, BoxCost>(); for (Box box : level.boxes) { if(agent.getColor() == box.getColor()) { int cost = Utils.findRouteCostIgnoreBoxes(level, agent, agent.getAtField(), box.getAtField(), null); if (cost==-1) continue; if (possibleBoxes.containsKey(box)) { BoxCost bc = possibleBoxes.get(box); bc.box = box; bc.cost = cost; } else { BoxCost bc = new BoxCost(); bc.box = box; bc.cost = cost; possibleBoxes.put(box, bc); } } } if(possibleBoxes.isEmpty()) return possibleBoxes; for (Box box : possibleBoxes.keySet()) { for (Goal goal : level.goals) { if(!boxFitsGoal(box, goal)) continue; int cost = findRouteCostIgnoreBoxes(level, agent, box.getAtField(), (Field)goal, null)-50; //the box itself costs 50 if (cost==-1) continue; possibleBoxes.get(box).goalCosts.add(new GoalCost(goal, cost)); } } return possibleBoxes; } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return The cost of getting to the field. -1 if no route */ public static int findRouteCostIgnoreBoxes(Level l, Agent a, Field from, Field to, Collection<Field> blockedFields) { int cost = -1; HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); HashSet<AStarField> openSetCopy = new HashSet<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (a.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); openSetCopy.add(start); AStarField curField; while (true) { curField = openSet.poll(); // Are we there yet? if (curField.field.equals(to) || curField == null) break; openSetCopy.remove(curField); closedSet.add(curField.field); int gScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if (neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; // Is the neighbor already in the open set? As of uniform cost it can not be possible to find a faster route to it if (openSetCopy.contains(neighbor)) continue; // AStarField neighbourInOpenSet = null; // At some point test if it is faster to use this approach in stead of double openSet. // for (AStarField aOpen : openSet) { // if (aOpen.field == neighbor) continue; // } AStarField neighbourField = new AStarField(curField.neighborTo(d)); neighbourField.g = gScore; if (ownBoxFields.contains(curField.field)) neighbourField.g = gScore+50; else if (othersBoxFields.contains(curField.field)) neighbourField.g = gScore+200; neighbourField.f = neighbourField.g + heuristicEstimate(neighbourField.field, to, HeuristicType.MANHATTAN); neighbourField.c = new Command(d); cameFrom.put(neighbourField, curField); openSet.add(neighbourField); openSetCopy.add(neighbourField); } } if (curField != null) { cost = curField.f; } return cost; } public static ArrayList<Box> findRouteCountBoxesInTheWay(Level l, Agent a, Field from, Field to, Collection<Field> blockedFields) { ArrayList<Box> boxesInTheWay = null; HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); HashSet<AStarField> openSetCopy = new HashSet<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (a.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); openSetCopy.add(start); AStarField curField; while (true) { curField = openSet.poll(); // Are we there yet? if (curField.field.equals(to) || curField == null) break; openSetCopy.remove(curField); closedSet.add(curField.field); int gScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if (neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; // Is the neighbor already in the open set? As of uniform cost it can not be possible to find a faster route to it if (openSetCopy.contains(neighbor)) continue; AStarField neighbourField = new AStarField(curField.neighborTo(d)); neighbourField.g = gScore; boxesInTheWay = new ArrayList<Box>(); if (ownBoxFields.contains(curField.field)){ for (Box box : l.boxes) { if(box.getAtField() == curField.field) boxesInTheWay.add(box); } } else if (othersBoxFields.contains(curField.field)){ for (Box box : l.boxes) { if(box.getAtField() == curField.field) boxesInTheWay.add(box); } } neighbourField.f = neighbourField.g + heuristicEstimate(neighbourField.field, to, HeuristicType.MANHATTAN); neighbourField.c = new Command(d); cameFrom.put(neighbourField, curField); openSet.add(neighbourField); openSetCopy.add(neighbourField); } } return boxesInTheWay; } public static List<Field> getEscapeFieldsFromCommands(Agent a, Collection<Command> commandsNotCompleted) { ArrayList<Field> escapeFields = new ArrayList<Field>(); Field current = a.getAtField(); escapeFields.add(current); for (Command c : commandsNotCompleted) { if (c.cmd.equals("Move") || c.cmd.equals("Pull")) { current = current.neighbours[c.dir1.ordinal()]; } else if (c.cmd.equals("Push")) { current = current.neighbours[c.dir2.ordinal()]; } if (current == null) break; escapeFields.add(current); } return escapeFields; } /** * Checks if an agent was at this location last turn. this can happen on FOMA since actions are synchronous * @param level * @param field * @return */ public static boolean CheckIfAnAgentWasOnThisFieldLastTurn(Level level, Field field){ for (Agent agent : level.agents) { if(agent.lastLocation == field) return true; } return false; } public static Box FindBoxForAgent(Agent agent, Level level) { for (Box box : level.boxes) { if(box.getId() == agent.getId()){ return box; } } return null; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/Utils.java
Java
oos
35,291
package utils; import java.util.ArrayList; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; public class Communication { /** * find agent to move a given box that might be in the way for another agent * @param box * @param level * @return */ public static Agent FindAgentToMoveBox(Box box, Level level){ for (Agent candidate_agent : level.agents) { if(box.getColor() == candidate_agent.getColor()) return candidate_agent; } return null; } public static boolean isObsticalStillInTheWay(Agent agent, Object obstacle, ArrayList<Field> avoidFields){ if(obstacle instanceof Agent){ Agent agent_obstical = (Agent) obstacle; for (Field field : avoidFields) { if(agent_obstical.getAtField().equals(field)) return true; } } else if(obstacle instanceof Box){ Box box_obstical = (Box) obstacle; for (Field field : avoidFields) { if(box_obstical.getAtField().equals(field)) return true; } } return false; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/Communication.java
Java
oos
1,087
package utils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; import client.Command; import datastructures.ActionSequence; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class Moves { public static List<Field> getEscapeFieldsFromCommands(Agent a, Collection<Command> commandsNotCompleted) { ArrayList<Field> escapeFields = new ArrayList<Field>(); Field current = a.getAtField(); escapeFields.add(current); for (Command c : commandsNotCompleted) { if (c.cmd.equals("Move") || c.cmd.equals("Pull")) { current = current.neighbours[c.dir1.ordinal()]; } else if (c.cmd.equals("Push")) { current = current.neighbours[c.dir2.ordinal()]; } if (current == null) break; escapeFields.add(current); } return escapeFields; } public static void MoveABoxToLocation(Agent agent, Box box, Field newLocation, Level level){ GoalActionSequence routeToGoal; // if this is not possible due to box in the way call: //reinsert the objective ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(box.getAtField()); for (Agent tempAgent : level.agents) { if(agent != tempAgent && agent.isNooping) blockedFields.add(agent.getAtField()); } for (Box tempBox : level.boxes) { if(!tempBox.equals(box)) blockedFields.add(tempBox.getAtField()); } State newState = null; boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRouteIgnoreObstacles(level, agent, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = newLocation.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null) continue; routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), newLocation, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/Moves.java
Java
oos
3,015
package utils; import java.util.ArrayList; import LevelObjects.Field; import client.Command; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.FieldInState; import datastructures.State; public class PrioriGoalUtils { public static ArrayList<FieldInState> getBlockedFields(State currentState) { ArrayList<FieldInState> blockedFields = new ArrayList<FieldInState>(); for (FieldInState field : currentState.fields) { if (field.blockedTimeChangeIndexes.size() != 0) { blockedFields.add(field); } } return blockedFields; } public static ArrayList<Field> getBlockedFields(State currentState, AgentInState agent, BoxInState box) { ArrayList<Field> blockedFields = new ArrayList<Field>(); for (AgentInState a : currentState.agents) { if (agent.f != a.f) blockedFields.add(a.f); } for (BoxInState b : currentState.boxes) { if (box.f != b.f) blockedFields.add(b.f); } return blockedFields; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/PrioriGoalUtils.java
Java
oos
990
package utils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Set; import utils.Utils.HeuristicType; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; import client.Command; import constants.Constants; import constants.Constants.dir; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.FieldBlockedChange; import datastructures.FieldInState; import datastructures.GoalActionSequence; import datastructures.GoalSequenceNode; import datastructures.MoveActionSequence; import datastructures.State; import datastructures.StateGoal; public class FOMAUtils { static State state; static int index; static Field agentPos; public static void mergeState(Level level, State currentState, ArrayList<ArrayList<Command>> commands) { state = currentState; if (commands == null) return; int counter = 0; for (ArrayList<Command> commandArray : commands) { System.err.println("MErging agent no " + counter + " size: " + commandArray.size()); index = currentState.indexOfCommands; agentPos = currentState.agents.get(counter).f; for (Command command : commandArray) { completeCommand(command); index++; } counter++; } // state.printFieldChanges(); } private static void completeCommand(Command c) { if (c.cmd.equals("Move")) completeMove(c); else if (c.cmd.equals("Pull")) completePull(c); else if (c.cmd.equals("Push")) completePush(c); } private static void completeMove(Command c) { for (FieldInState field : state.fields) { if (field.f == agentPos) { field.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, false)); for (FieldInState neighbour : state.fields) { if (field.f.neighbours[c.dir1.ordinal()] == neighbour.f) { neighbour.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); agentPos = neighbour.f; break; } } break; } } } private static void completePull(Command c) { for (FieldInState field : state.fields) { if (field.f == agentPos) { field.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, false)); field.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); for (FieldInState neighbour : state.fields) { if (field.f.neighbours[c.dir1.ordinal()] == neighbour.f) { neighbour.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); agentPos = neighbour.f; break; } } break; } } } private static void completePush(Command c) { for (FieldInState field : state.fields) { if (field.f == agentPos) { field.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, false)); for (FieldInState neighbour : state.fields) { if (field.f.neighbours[c.dir1.ordinal()] == neighbour.f) { neighbour.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, false)); neighbour.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); for (FieldInState neighbour2 : state.fields) { if (neighbour.f.neighbours[c.dir2.ordinal()] == neighbour2.f) { neighbour2.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); break; } } agentPos = neighbour.f; break; } } break; } } } public static MoveActionSequence findRoute(Level l, Field from, Field to, Collection<FieldInState> blockedFields, int startTimeStep) { HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); // System.err.println("Finding route form " + from.toString() + " to " + to.toString()); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); AStarField start = new AStarField(from); start.timeStep = startTimeStep; start.g = 0; start.f = start.g + Utils.heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); AStarField curField = openSet.poll(); while (curField != null) { if (curField.field.equals(to)) break; // System.err.println("Current field " + curField.field.toString()); closedSet.add(curField.field); int tentativeGScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if (neighbor == null){ continue; } boolean neighborIsBlockedInStep = isNeighbourBlockedInStep( blockedFields, neighbor, curField.timeStep); if (neighborIsBlockedInStep || closedSet.contains(neighbor)) continue; AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field == neighbor) neighbourInOpenSet = aOpen; } if (neighbourInOpenSet != null && tentativeGScore > neighbourInOpenSet.g) { continue; } else if (neighbourInOpenSet == null) { neighbourInOpenSet = new AStarField(curField.neighborTo(d)); neighbourInOpenSet.timeStep = curField.timeStep++; neighbourInOpenSet.g = tentativeGScore; neighbourInOpenSet.f = neighbourInOpenSet.g + Utils.heuristicEstimate(neighbourInOpenSet.field, to, HeuristicType.MANHATTAN); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); openSet.add(neighbourInOpenSet); } } curField = openSet.poll(); } // If currentField is null, we didn't find a path. if (curField == null) return null; ArrayList<Command> commands = new ArrayList<Command>(); ArrayList<Field> fields = new ArrayList<Field>(); while (cameFrom.get(curField) != null) { fields.add(curField.field); commands.add(curField.c); curField = cameFrom.get(curField); } Collections.reverse(commands); Collections.reverse(fields); MoveActionSequence mas = new MoveActionSequence(from, to, commands); mas.fields = fields; return mas; } private static boolean isNeighbourBlockedInStep( Collection<FieldInState> blockedFields, Field neighbor, int startTimeStep) { for (FieldInState fieldInState : blockedFields) { if (fieldInState.f == neighbor) { if (fieldInState.changesStatusInFuture(startTimeStep)) return true; else{ return fieldInState.blockedTimeChangeIndexes.get(fieldInState.blockedTimeChangeIndexes.size()-1).changeToBlocked; } } } return false; } public static ArrayList<State> getStateFromLevel(ArrayList<Agent> agents, ArrayList<Box> boxes, ArrayList<Field> fields, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); ArrayList<FieldInState> fieldsInState = new ArrayList<FieldInState>(); for (Field field : fields) { FieldInState newField = new FieldInState(field); if (field.object != null) { newField.blockedTimeChangeIndexes.add(new FieldBlockedChange(0,true)); } else{ newField.blockedTimeChangeIndexes.add(new FieldBlockedChange(0,false)); } fieldsInState.add(newField); } for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (Agent a : agents) { firstState.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : boxes) { firstState.boxes.add(new BoxInState(b, b.getAtField())); } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; firstState.fields = fieldsInState; returnStates.add(firstState); } return returnStates; } private static ArrayList<FieldInState> getNewFieldsInState( State currentState, Agent agent, ActionSequence sequence) { ArrayList<FieldInState> returnFields = new ArrayList<FieldInState>(); if (sequence instanceof MoveActionSequence) { MoveActionSequence routeToGoal = (MoveActionSequence) sequence; FieldInState curField = null; for (FieldInState fieldInState : currentState.fields) { FieldInState newField = new FieldInState(fieldInState.f); for (FieldBlockedChange i : fieldInState.blockedTimeChangeIndexes) { newField.blockedTimeChangeIndexes.add(i); } returnFields.add(newField); if (fieldInState.f == routeToGoal.getStartField()) curField = newField; } int timeStep = currentState.indexOfCommands; for (Command c : routeToGoal.getCommands()) { if (c.cmd.equals("Move")) { curField.blockedTimeChangeIndexes.add(new FieldBlockedChange(timeStep+1,false)); for (FieldInState fieldInState : returnFields) { if (fieldInState.f == curField.f.neighbours[c.dir1 .ordinal()]) { curField = fieldInState; break; } } curField.blockedTimeChangeIndexes.add(new FieldBlockedChange(timeStep+1,true)); } timeStep++; } } else{ GoalActionSequence routeToGoal = (GoalActionSequence) sequence; FieldInState curFieldAgent = null; FieldInState curFieldBox = null; for (FieldInState fieldInState : currentState.fields) { FieldInState newField = new FieldInState(fieldInState.f); for (FieldBlockedChange i : fieldInState.blockedTimeChangeIndexes) { newField.blockedTimeChangeIndexes.add(i); } returnFields.add(newField); if (fieldInState.f == routeToGoal.getAgentStartLocation()) curFieldAgent = newField; if (fieldInState.f == routeToGoal.getBoxStartLocation()) curFieldBox = newField; } int timeStep = currentState.indexOfCommands; for (Command c : routeToGoal.getCommands()) { curFieldAgent.blockedTimeChangeIndexes.add(new FieldBlockedChange(timeStep+1,true)); curFieldBox.blockedTimeChangeIndexes.add(new FieldBlockedChange(timeStep+1,true)); if (c.cmd.equals("Push")) { curFieldAgent = curFieldBox; for (FieldInState fieldInState : returnFields) { if (fieldInState.f == curFieldBox.f.neighbours[c.dir2 .ordinal()]) { curFieldBox = fieldInState; break; } } } if (c.cmd.equals("Pull")) { curFieldBox = curFieldAgent; for (FieldInState fieldInState : returnFields) { if (fieldInState.f == curFieldAgent.f.neighbours[c.dir1 .ordinal()]) { curFieldAgent = fieldInState; break; } } } timeStep++; } } return returnFields; } // We know that the agent a has a box. Now we want to move the box to the // goal. // GoalActionSequence routeToGoal = FOMAUtils.findGoalRoute(level, currentState.goal.agent.a, currentState.goal.box.b, // currentState.goal.agent.f, currentState.goal.agentToPos, currentState.goal.box.f, currentState.goal.boxToPos, blockedFields); public static GoalActionSequence findGoalRoute(Level l, State currentState, Collection<FieldInState> blockedFields) { dir boxDir = null; Field boxFromField = currentState.goal.box.f; Field agentFromField = currentState.goal.agent.f; Field boxToField = currentState.goal.boxToPos; Field agentToField = currentState.goal.agentToPos; GoalSequenceNode root = new GoalSequenceNode(boxFromField, agentFromField, null); LinkedList<GoalSequenceNode> queue = new LinkedList<GoalSequenceNode>(); // prune looped states (if agent and box ends up in a state already explored) HashMap<Field, ArrayList<Field>> closedSet = new HashMap<Field, ArrayList<Field>>(); //adding initial state to list set of explored states: ArrayList<Field> tempList = new ArrayList<Field>(); tempList.add(boxFromField); closedSet.put(agentFromField, tempList); //Add a closed set. queue.add(root); GoalSequenceNode currentNode = queue.poll(); currentNode.timeStep = currentState.indexOfCommands; while (currentNode != null && (currentNode.boxLocation != boxToField || currentNode.agentLocation != agentToField)) { boxDir = Agent.getBoxDirection(currentNode.agentLocation,currentNode.boxLocation); ArrayList<Command> foundCommands = addPossibleBoxCommandsForDirection(boxDir, currentNode.agentLocation, currentNode.boxLocation, blockedFields, currentNode.timeStep); for (Command command : foundCommands) { Field boxLocation = null; Field agentLocation = null; if (command.cmd.equals("Push")) { agentLocation = currentNode.boxLocation; boxLocation = currentNode.boxLocation.neighbours[command.dir2 .ordinal()]; } else { boxLocation = currentNode.agentLocation; agentLocation = currentNode.agentLocation.neighbours[command.dir1 .ordinal()]; } // Do we already have a way to get to this state? if (closedSet.containsKey(agentLocation)) { if (closedSet.get(agentLocation).contains(boxLocation)){ continue; } else { // the agent has been here before but without the box in same location closedSet.get(agentLocation).add(boxLocation); } } else { // neither the agent or the box has been here before. Update DS and create node in BTtree: ArrayList<Field> tempListe = new ArrayList<Field>(); tempListe.add(boxLocation); closedSet.put(agentLocation, tempListe); } GoalSequenceNode node = new GoalSequenceNode(boxLocation,agentLocation, command); node.parent = currentNode; node.timeStep = currentNode.timeStep+1; queue.add(node); } if (queue.isEmpty()) { //TODO: we have searched to the end without finding a solution. Move boxes to get access to goals return null; } currentNode = queue.poll(); } GoalActionSequence returnSequence = new GoalActionSequence(); returnSequence.setAgentStartLocation(currentNode.agentLocation); returnSequence.setBoxStartLocation(currentNode.boxLocation); ArrayList<Command> commands = new ArrayList<Command>(); while (currentNode.parent != null) { commands.add(currentNode.action); currentNode = currentNode.parent; } Collections.reverse(commands); returnSequence.setCommands(commands); return returnSequence; } public static ArrayList<State> getStateFromCompletedMove( State currentState, Agent agent, MoveActionSequence routeToGoal, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); ArrayList<FieldInState> fieldsInState = getNewFieldsInState( currentState, agent, routeToGoal); ArrayList<AgentInState> agents = currentState.agents; ArrayList<BoxInState> boxes = currentState.boxes; for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (AgentInState a : agents) { if (a.a != agent) firstState.agents.add(a); else firstState.agents.add(new AgentInState(agent, routeToGoal .getEndField())); } for (BoxInState b : boxes) { firstState.boxes.add(b); } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; firstState.fields = fieldsInState; returnStates.add(firstState); } return returnStates; } public static ArrayList<State> getStateFromCompletedGoal( State currentState, Agent agent, Field goal, GoalActionSequence routeToGoal) { ArrayList<AgentInState> agents = currentState.agents; ArrayList<BoxInState> boxes = currentState.boxes; Field agentPos = currentState.goal.agentToPos; Box box = currentState.goal.box.b; Field boxPos = currentState.goal.boxToPos; ArrayList<State> returnStates = new ArrayList<State>(); ArrayList<FieldInState> fieldsInState = getNewFieldsInState( currentState, agent, routeToGoal); // System.err.println("FieldsInState size " + fieldsInState.size() ); for (FieldInState fieldInState : fieldsInState) { // System.err.print("Field " + fieldInState.f.toString()); // System.err.println(); } for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (AgentInState a : agents) { if (a.a != agent) firstState.agents.add(a); else firstState.agents.add(new AgentInState(agent, agentPos)); } for (BoxInState b : boxes) { if (b.b != box) firstState.boxes.add(b); else { firstState.boxes.add(new BoxInState(box, boxPos)); } } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; firstState.fields = fieldsInState; returnStates.add(firstState); } return returnStates; } public static ArrayList<Command> addPossibleBoxCommandsForDirection(dir direction, Field agentLocationInPlan, Field boxLocationInPlan, Collection<FieldInState> blockedFields, int timeStep) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); // System.err.println("PossibleCommands"); // Find possible pull commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction FieldInState agentNeighbour = null; for (FieldInState f : blockedFields) { if (f.f == agentLocationInPlan.neighbours[d.ordinal()]) { agentNeighbour = f; } } if (d != direction && agentNeighbour != null && agentNeighbour.freeInInterval(timeStep, timeStep+2)) { // System.err.println("Making pull"); possibleCommands.add(new Command("Pull", d, direction)); } } for (dir d : dir.values()) { // We cannot push a box backwards in the agents direction FieldInState boxNeighbour = null; for (FieldInState f : blockedFields) { if (f.f == boxLocationInPlan.neighbours[d.ordinal()]) { boxNeighbour = f; } } // if(boxNeighbour.freeInInterval(timeStep, timeStep+2)) System.err.println("OSTEMADDDD"); if (d != Constants.oppositeDir(direction) && boxNeighbour != null && boxNeighbour.freeInInterval(timeStep, timeStep+2)) { // System.err.println("Making push"); possibleCommands.add(new Command("Push", direction, d)); } } return possibleCommands; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/FOMAUtils.java
Java
oos
18,122
package utils; import java.util.ArrayList; import java.util.List; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; public class FindFreeSpaces { public static void FindSpaces(Level level){ System.err.println("------------------Fields------------------"); List<Field> fields = new ArrayList<Field>(); fields = level.fields; System.err.println("Field: " + fields.size()); for (Box box : level.boxes) { if(box.getAtField() != null){ fields.remove(box.getAtField()); } } System.err.println("Field: " + fields.size()); for (Field field : fields) { // if(fields) // System.err.println("Field: " + field); } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/utils/FindFreeSpaces.java
Java
oos
733
package aStar; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import LevelObjects.*; import client.Command; import constants.Constants.*; public class Pathfinding { // Should be called by planner to find commands for an agent public static Queue<Command> commandsForAgentToField(Level l, Agent a, Field to) { AStar(l,a,a.getAtField(),to); Queue<Command> q = new LinkedList<Command>(); q.add(new Command(dir.N)); q.add(new Command(dir.E)); q.add(new Command(dir.S)); q.add(new Command(dir.W)); return q; } // Should be called by planner to find commands for an agent public static Queue<Command> commandsForAgentAndBoxToFields(Level l, Agent a, Box b, Field aTo, Field bTo) { return new LinkedList<Command>(); } // Is only meant to be used by other functions in this class private static ArrayList<Field> AStar(Level l, Agent a, Field from, Field to) { // Data handling AStarNode[][] nodeMap = new AStarNode[l.fieldMap.length][l.fieldMap[0].length]; PriorityQueue<AStarNode> openSet = new PriorityQueue<AStarNode>(); Set<AStarNode> closedSet = new HashSet<AStarNode>(); // Start node AStarNode start = new AStarNode(from); start.g = 0; start.w = 0; start.h = manhattanDist(start.field, to); start.f = start.g + start.w + start.h; nodeMap[from.x][from.y] = start; openSet.add(start); // A* AStarNode current; while (openSet.size() > 0) { current = openSet.poll(); closedSet.add(current); Field f = current.field; if (f == to) { printNodeMap(nodeMap); return pathFromAStarNode(current); // goal reached } Field n; for (int i=0; i<4; i++) { n = f.neighbours[i]; if (n != null) { int tentative_g = current.g + 1; // check if there's already a node for this neighbour field AStarNode nNode; boolean nNodeIsNew = false; // temp value if (nodeMap[n.x][n.y] != null) { // already created node nNode = nodeMap[n.x][n.y]; if (closedSet.contains(nNode)) { if (tentative_g >= nNode.g) continue; } } else { nNode = new AStarNode(n); nodeMap[n.x][n.y] = nNode; nNodeIsNew = true; } boolean nNodeInOpenSet = false; if (!nNodeIsNew) nNodeInOpenSet = openSet.contains(nNode); // optimize this away ! if (!nNodeInOpenSet || tentative_g < nNode.g) { nNode.field = n; nNode.parent = current; nNode.g = tentative_g; if (nNodeIsNew) { nNode.h = manhattanDist(nNode.field, to); nNode.w = weightOfField(nNode.field, a); } nNode.f = nNode.g + nNode.w + nNode.h; if (!nNodeInOpenSet) openSet.add(nNode); } } } } System.err.println("Simple AStar could not find a path !!!"); return null; } private static void printNodeMap(AStarNode[][] nodeMap) { for (int y=0; y<nodeMap[0].length; y++) { for (int x=0; x<nodeMap.length; x++) { if (nodeMap[x][y] != null) //System.err.print(nodeMap[x][y].f+"\t"); System.err.printf("%3d", nodeMap[x][y].f); else System.err.print("\t"); } System.err.println(); } } private static ArrayList<Field> pathFromAStarNode(AStarNode node) { ArrayList<Field> path = new ArrayList<Field>(); AStarNode current = node; while (current != null) { System.err.println(current.field.x +"x"+ current.field.y + ", g:"+current.g+" w:"+current.w+" h:"+current.h); path.add(current.field); current = current.parent; } Collections.reverse(path); return path; } private static class AStarNode implements Comparable<AStarNode> { AStarNode parent; Field field; int f, g, w, h; public AStarNode(Field f){ field = f; } public int compareTo(AStarNode o) { return f - o.f; } } private static int manhattanDist(Field from, Field to) { return Math.abs(from.x - to.x) + Math.abs(from.y - to.y); } private static int weightOfField(Field f, Agent a) { int weight = 0; if (f instanceof Goal) weight += 1; // Moving over a goal. Should this even give extra weight? Object o = f.object; if (o instanceof Box) { if (((Box) o).getColor() == a.getColor()) weight += 2; // Agent can move box else weight += 20; // Agent can't move box } return weight; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/aStar/Pathfinding.java
Java
oos
4,459
package LevelObjects; import java.io.Serializable; import constants.Constants; import constants.Constants.Color; public class Box implements Comparable<Box> { private char id; // stored as lowercase so we can easily compare with goals private Color color; private Field atField; public Box(char id, Color color, Field atField) { this.id = Character.toLowerCase(id); this.color = color==null ? Color.blue : color; this.atField = atField; } // Getter / Setters public Field getAtField() { return atField; } public void setAtField(Field atField) { this.atField = atField; } public char getId() { return id; } public Color getColor() { return color; } @Override public int compareTo(Box o) { if (this.atField.x != o.atField.y) { return this.atField.x-o.atField.x; } else{ return this.atField.y-o.atField.y; } } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/LevelObjects/Box.java
Java
oos
873
package LevelObjects; import java.awt.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import agent.objectives.*; import agent.planners.AgentPlanner; import utils.Communication; import utils.Moves; import utils.Utils; import constants.Constants; import constants.Constants.Color; import constants.Constants.dir; import client.Command; import client.Desire; import client.planners.Planner; import datastructures.*; public class Agent { private static Random rand = new Random(); // del? private char id; public int number; private Color color; private Field atField; public HashMap<Box, BoxCost> possibleBoxesToGoals = new HashMap<Box, BoxCost>(); public Queue<ActionSequence> actions; public LinkedList<Objective> objectives = new LinkedList<Objective>(); public AgentPlanner planner; public boolean isNooping = false; public int priority; public Queue<Command> commandQueue; public Queue<Command> commandsNotCompleted; public Field lastLocation; public Desire desire; public Objective tempObjective; public Object obstacle; public boolean isTheCauseOfAConflict = false; private Conflict conflict; public Agent(char id, Color color, Field atField) { this.id = id; this.color = color==null ? Color.blue : color; this.atField = atField; this.commandQueue = new LinkedList<Command>(); this.commandsNotCompleted = new LinkedList<Command>(); } public Agent(char id, Color color, Field atField, AgentPlanner planner) { this(id, color, atField); this.planner = planner; } /** * Convert objective to commands and fill them in the commandqueue */ public void planAndExecute(Level level) { isNooping = false; // Check if previous action failed if (obstacle != null) { if (obstacle instanceof Agent) { Agent other = (Agent)obstacle; if (this.priority <= other.priority) { other.commandQueue.clear(); ArrayList<Field> list = new ArrayList<Field>(); list.add(this.getAtField()); other.objectives.addFirst(new Move(Utils.getEscapeFieldsFromCommands(this, commandsNotCompleted), list ,50)); other.obstacle = null; Command c; while ((c = commandsNotCompleted.poll()) != null) commandQueue.add(c); this.objectives.removeFirst(); } else this.commandsNotCompleted.clear(); } else if( obstacle instanceof Box) { //A box is in the way. find which box Box otherBox = (Box)obstacle; if(otherBox.getColor() == this.getColor()){ Objective newObjective = new DockABox(new Field(3, 6), otherBox, 15); this.objectives.addFirst(newObjective); } else { //Find an agent to move the box Agent otherAgent = Communication.FindAgentToMoveBox(otherBox, level); if (this.id<otherAgent.id || otherAgent.commandQueue.isEmpty()) { ArrayList<Field> fieldsToAvoid = new ArrayList<Field>(); fieldsToAvoid.addAll(Moves.getEscapeFieldsFromCommands(this, commandsNotCompleted)); otherAgent.conflict = new Conflict(this, fieldsToAvoid, obstacle, otherBox, this.priority); } } } obstacle = null; return; } // if(this.conflict != null && this.conflict.isPriority() < this.id){ //Another agent has a conflict with this agent if(this.conflict != null && this.conflict.isPriority() <= this.priority){ if(this.conflict.getObstacle() instanceof Box) { //A box is in the way. find which box //Agent has to move the box for another agent Box box = this.conflict.getMoveaBox(); //Get to box if(this.objectives.getFirst() instanceof Move){ //Find a route for the agent and the box. this.commandQueue.clear(); ArrayList<Field> candidates = new ArrayList<Field>(); candidates = Utils.getFreeFields(box.getAtField(),this.conflict.getAvoidFields(),15,false); Queue<Command> commandQueue = null; differentEndLocations: for (Field field : candidates) { Moves.MoveABoxToLocation(this, box, field, level); } } else if(this.objectives.getFirst() instanceof GoalABox){ //Find a route for the agent and the box. this.commandQueue.clear(); ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(this.conflict.getHelpAgent().getAtField()); Field candidates; candidates = Utils.getFirstFreeFieldkcl(box.getAtField(), this.conflict.getAvoidFields(), (Collection<Field>) blockedFields, 25, true); Moves.MoveABoxToLocation(this, box, candidates, level); } else { //Other agent not doing anything - get to the box and move it.. this.commandQueue.clear(); ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(this.conflict.getHelpAgent().getAtField()); for (Box current_box : level.boxes) { blockedFields.add(current_box.getAtField()); } Field candidates; this.conflict.avoidFields.addAll(blockedFields); candidates = Utils.getFirstFreeFieldkcl(box.getAtField(), this.conflict.getAvoidFields(), (Collection<Field>) blockedFields, 25, true); Moves.MoveABoxToLocation(this, box, candidates, level); } } this.conflict = null; } if(!this.commandQueue.isEmpty()){ return; } Objective o = objectives.peek(); if (o==null){ if(!objectives.isEmpty()){ objectives.remove(); } return; } boolean successful = false; if (o instanceof GoalABox) { GoalABox gab = (GoalABox)o; successful = planner.goalABox(this, gab.box, gab.goal); } else if (o instanceof Move) { Move mv = (Move)o; successful = planner.move(this, mv.escapeFromFields, mv.blockedFields, mv.numberOfRounds); } else if (o instanceof DockABox) { DockABox dab = (DockABox)o; successful = planner.dock(this, dab.box, dab.field, dab.blockedFields, dab.numberOfRounds); } else if (o instanceof Move) { Wait mv = (Wait)o; successful = planner.wait(this, mv.numberOfRounds); } if (successful) this.tempObjective = objectives.removeFirst(); } public Field getAtField() { return atField; } public void setAtField(Field atField) { this.atField = atField; } public char getId() { return id; } public Color getColor() { return color; } // Only used by random walk clients. public Command act() { ArrayList<Command> possibleCommands = new ArrayList<Command>(); for (dir d : dir.values()) { randomWalkAddPossibleCommandsForDirection(d, possibleCommands); } if (possibleCommands.size() == 0) possibleCommands.add(new Command(dir.N)); //Dummy command return possibleCommands.get(rand.nextInt(possibleCommands.size())); } private void randomWalkAddPossibleCommandsForDirection(dir direction, ArrayList<Command> possibleCommands){ if (neighbourFree(this.atField,direction)) { possibleCommands.add(new Command(direction)); } else if (neighbourIsBoxOfSameColor(direction)) { //Find possible pull commands for (dir d : dir.values()) { //we cannot pull a box forward in the box's direction if (d != direction && neighbourFree(this.atField,d)){ possibleCommands.add(new Command("Pull",d,direction)); } } //Find possible push commands for (dir d : dir.values()) { //We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && neighbourFree(this.getAtField().neighbours[direction.ordinal()],d)){ possibleCommands.add(new Command("Push",direction,d)); } } } } public ArrayList<Command> addPossibleCommandsForDirection(dir direction, Field agentLocationInPlan, Field boxLocationInPlan) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); /* Commented because we are not interested in move commands at current time. if (neighbourFreeInPlan(agentLocationInPlan, direction, boxLocationInPlan) && this.desire.goal == null) { possibleCommands.add(new Command(direction)); }*/ // Find possible pull commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction if (d != direction && neighbourFreeInPlan(agentLocationInPlan, d)) { possibleCommands.add(new Command("Pull", d, direction)); } } // Find possible push commands for (dir d : dir.values()) { // We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && neighbourFreeInPlan(boxLocationInPlan,d)) { possibleCommands.add(new Command("Push", direction, d)); } } return possibleCommands; } public boolean neighbourFree(Field f, dir d){ //System.err.println(f); return (f.neighbours[d.ordinal()] != null && f.neighbours[d.ordinal()].object == null); } //Checks if neighbour is free in the plan. public boolean neighbourFreeInPlan(Field posInPlan, dir d){ if (neighbourFree(posInPlan, d)) { return true; } //If the neighbour is free in actual state then everything is good. If it is not, we need to check if //it is free in the plan, by checking if the neighbour is the agent's or the box's location. else if(posInPlan.neighbours[d.ordinal()] != null && (posInPlan.neighbours[d.ordinal()] == this.getAtField() || (this.desire != null && posInPlan.neighbours[d.ordinal()] == this.desire.box.getAtField()))){ return true; } return false; } private boolean neighbourIsBoxOfSameColor(dir d){ return (this.getAtField().neighbours[d.ordinal()] != null && this.getAtField().neighbours[d.ordinal()].object instanceof Box && ((Box) this.getAtField().neighbours[d.ordinal()].object).getColor() == this.color); } //Find the box's direction, relative to the agent, if they are on adjacent fields. public static dir getBoxDirection(Field agentField, Field boxField){ if (boxField == null) return null; for (dir d : dir.values()) { if (agentField.neighbours[d.ordinal()] != null && agentField.neighbours[d.ordinal()] == boxField) { return d; } } return null; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/LevelObjects/Agent.java
Java
oos
10,171
package LevelObjects; import java.util.ArrayList; public class Level { public ArrayList<Agent> agents = new ArrayList<Agent>(); public ArrayList<Box> boxes = new ArrayList<Box>(); public ArrayList<Field> fields = new ArrayList<Field>(); public ArrayList<Goal> goals = new ArrayList<Goal>(); public Field[][] fieldMap; public Field[][] getFieldMap() { return fieldMap; } public void setFieldMap(Field[][] field_map) { this.fieldMap = field_map; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/LevelObjects/Level.java
Java
oos
472
package LevelObjects; import java.util.Comparator; import constants.Constants.dir; public class Field implements Comparator<Field> { // Order of directions. /*public static enum dir { N, W, E, S };*/ // Example: neighbours[Constants.Constants.dir.N] public Field[] neighbours = new Field[4]; public int x; //Increases from left to right. public int y; //Increases downwards public Object object; //Can be null (free), or box or agent. public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public Field(int x, int y){ this.x = x; this.y = y; this.object = null; } public Field(int x, int y, Object object){ this.x = x; this.y = y; this.object = object; } public Field neighborTo(dir d) { return neighbours[d.ordinal()]; } public boolean isNeighborFree(dir d){ return (neighbours[d.ordinal()] != null && neighbours[d.ordinal()].object == null); } @Override public int compare(Field arg0, Field arg1) { if (arg0.x==arg1.x && arg0.y == arg1.y) return 0; else return (Math.abs(arg0.x-arg1.x) + Math.abs(arg0.y-arg1.y)); } @Override public String toString(){ return "" + this.x + "." + this.y; } public Field getClone(){ return new Field(this.x, this.y); } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/LevelObjects/Field.java
Java
oos
1,301
package LevelObjects; import java.util.ArrayList; public class Conflict { private Agent helpAgent; private Object obstacle; private Box moveaBox; private int priority; public ArrayList<Field> avoidFields = new ArrayList<Field>(); public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle) { super(); this.helpAgent = helpAgent; this.avoidFields = avoidFields; this.obstacle = obstacle; } public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle, Box moveaBox) { super(); this.helpAgent = helpAgent; this.obstacle = obstacle; this.avoidFields = avoidFields; this.moveaBox = moveaBox; } public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle, Box moveaBox, int priority) { super(); this.helpAgent = helpAgent; this.obstacle = obstacle; this.avoidFields = avoidFields; this.moveaBox = moveaBox; this.priority = priority; } public Agent getHelpAgent() { return helpAgent; } public void setHelpAgent(Agent helpAgent) { this.helpAgent = helpAgent; } public Box getMoveaBox() { return moveaBox; } public void setMoveaBox(Box moveaBox) { this.moveaBox = moveaBox; } public int isPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public ArrayList<Field> getAvoidFields() { return avoidFields; } public void setAvoidFields(ArrayList<Field> avoidFields) { this.avoidFields = avoidFields; } public Object getObstacle() { return obstacle; } public void setObstacle(Object obstacle) { this.obstacle = obstacle; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/LevelObjects/Conflict.java
Java
oos
1,700
package LevelObjects; public class Goal extends Field implements Comparable<Goal> { private char id; public int priority; public char getId() { return id; } public int getPriority() { return priority; } public void setPriority(int priority){ this.priority = priority; } public Goal(char id, int x, int y) { super(x, y); this.id = id; } public Goal(char id, int x, int y, Object object) { super(x, y, object); this.id = id; } @Override public int compareTo(Goal arg0) { return this.priority - arg0.priority; } public Goal(char id, int x, int y, Object object, int priority) { super(x, y, object); this.id = id; this.priority = priority; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/LevelObjects/Goal.java
Java
oos
701