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 |
|---|---|---|---|---|---|
// var layer = require( "../layer" );
// var timeline =require( "../timeline" );
// var text, fps = "fps: ";
// exports.set = function(){
// text = layer.createText( "default", fps + "0", 4, 470 ).attr( "fill", "#ccc" );
// };
// exports.update = function(){
// text.attr( "text", fps + ( timeline.getFPS() >> 0 ) );
// }; | zzy-code-test | html5/fruitninja/scripts/object/fps.js | JavaScript | gpl2 | 327 |
var layer = require( "../layer" );
var tween = require( "../lib/tween" );
var timeline = require( "../timeline" );
var message = require( "../message" );
var state = require( "../state" );
var exponential = tween.exponential.co;
/**
* "game-over"模块
*/
exports.anims = [];
exports.set = function(){
this.image = layer.createImage( "default", "images/game-over.png", 75, 198, 490, 85 ).hide().scale( 1e-5, 1e-5 );
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1e-5, 1, "show" ],
object: this, onTimeUpdate: this.onZooming, onTimeStart: this.onZoomStart, onTimeEnd: this.onZoomEnd,
recycle: this.anims
});
};
exports.hide = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1, 1e-5, "hide" ],
object: this, onTimeUpdate: this.onZooming, onTimeStart: this.onZoomStart, onTimeEnd: this.onZoomEnd,
recycle: this.anims
});
};
// 显示/隐藏 相关
exports.onZoomStart = function( sz, ez, mode ){
if( mode == "show" )
this.image.show();
};
exports.onZooming = function( time, sz, ez, z ){
this.image.scale( z = exponential( time, sz, ez - sz, 500 ), z );
};
exports.onZoomEnd = function( sz, ez, mode ){
if( mode == "show" )
state( "click-enable" ).on();
else if( mode === "hide" )
this.image.hide();
}; | zzy-code-test | html5/fruitninja/scripts/object/game-over.js | JavaScript | gpl2 | 1,333 |
var rotate = require( "../factory/rotate" );
var tween = require( "../lib/tween" );
exports = rotate.create("images/new-game.png", 244, 231, 195, 195, 1e-5, tween.exponential.co, 500); | zzy-code-test | html5/fruitninja/scripts/object/new-game.js | JavaScript | gpl2 | 185 |
var layer = require( "../layer" );
var tween = require( "../lib/tween" );
var timeline = require( "../timeline" );
var Ucren = require( "../lib/ucren" );
var message = require( "../message" );
var anim = tween.exponential.co;
var back = tween.back.co;
/**
*
*/
var o1, o2, o3, animLength = 500;
var conf1 = { src: "images/x.png", sx: 650, ex: 561, y: 5, w: 22, h: 19 };
var conf2 = { src: "images/xx.png", sx: 671, ex: 582, y: 5, w: 27, h: 26 };
var conf3 = { src: "images/xxx.png", sx: 697, ex: 608, y: 6, w: 31, h: 32 };
var number = 0;
exports.anims = [];
exports.set = function(){
o1 = layer.createImage( "default", conf1.src, conf1.sx, conf1.y, conf1.w, conf1.h ).hide();
o2 = layer.createImage( "default", conf2.src, conf2.sx, conf2.y, conf2.w, conf2.h ).hide();
o3 = layer.createImage( "default", conf3.src, conf3.sx, conf3.y, conf3.w, conf3.h ).hide();
};
exports.reset = function(){
number = 0;
[ [ o1, conf1 ], [ o2, conf2 ], [ o3, conf3 ] ].forEach(function( infx ){
infx[0].attr( "src", infx[1].src.replace( "xf.png", "x.png" ) );
})
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: animLength, data: [ "show", conf1.sx, conf1.ex, conf2.sx, conf2.ex, conf3.sx, conf3.ex ],
object: this, onTimeUpdate: this.onTimeUpdate, onTimeStart: this.onTimeStart, onTimeEnd: this.onTimeEnd,
recycle: this.anims
});
};
exports.hide = function( start ){
timeline.createTask({
start: start, duration: animLength, data: [ "hide", conf1.ex, conf1.sx, conf2.ex, conf2.sx, conf3.ex, conf3.sx ],
object: this, onTimeUpdate: this.onTimeUpdate, onTimeStart: this.onTimeStart, onTimeEnd: this.onTimeEnd,
recycle: this.anims
});
};
exports.showLoseAt = function( x ){
var infx, inf = [
[ o1, conf1 ],
[ o2, conf2 ],
[ o3, conf3 ]
];
createPosShow( x );
infx = inf[ ( ++ number ) - 1 ];
infx[0].attr( "src", infx[1].src.replace( "x.png", "xf.png" ) ).scale( 1e-5, 1e-5 );
this.scaleImage( infx[0] );
if( number == 3 )
message.postMessage( "game.over" );
};
exports.scaleImage = function( image ){
var dur = 500;
image.myOnScaling = image.myOnScaling || function( time, z ){
this.scale( z = back( time, 1e-5, 1 - 1e-5, dur ), z );
};
image.myOnScaleEnd = image.myOnScaleEnd || function(){
this.scale( 1, 1 );
};
timeline.createTask({
start: 0, duration: dur,
object: image, onTimeUpdate: image.myOnScaling, onTimeEnd: image.myOnScaleEnd,
recycle: this.anims
});
};
// 显示/隐藏 相关
exports.onTimeUpdate = function( time, mode, x1s, x1e, x2s, x2e, x3s, x3e ){
o1.attr( "x", anim( time, x1s, x1e - x1s, animLength ) );
o2.attr( "x", anim( time, x2s, x2e - x2s, animLength ) );
o3.attr( "x", anim( time, x3s, x3e - x3s, animLength ) );
};
exports.onTimeStart = function( mode ){
if( mode == "show" )
[ o1, o2, o3 ].invoke( "show" );
};
exports.onTimeEnd = function( mode ){
if( mode == "hide" )
[ o1, o2, o3 ].invoke( "hide" ),
this.reset();
};
function createPosShow( x ){
var image = layer.createImage( "default", "images/lose.png", x - 27, 406, 54, 50 ).scale( 1e-5, 1e-5 );
var duration = 500;
var control = {
show: function( start ){
timeline.createTask({
start: start, duration: duration, data: [ tween.back.co, 1e-5, 1 ],
object: this, onTimeUpdate: this.onScaling, onTimeEnd: this.onShowEnd
// recycle: anims
});
},
hide: function( start ){
timeline.createTask({
start: start, duration: duration, data: [ tween.back.ci, 1, 1e-5 ],
object: this, onTimeUpdate: this.onScaling, onTimeEnd: this.onHideEnd
// recycle: anims
});
},
onScaling: function( time, anim, a, b, z ){
image.scale( z = anim( time, a, b - a, duration ), z );
},
onShowEnd: function(){
this.hide( 1500 );
},
onHideEnd: function(){
image.remove();
}
};
control.show( 200 );
} | zzy-code-test | html5/fruitninja/scripts/object/lose.js | JavaScript | gpl2 | 4,220 |
var displacement = require( "../factory/displacement" );
var tween = require( "../lib/tween" );
exports = displacement.create("images/logo.png", 288, 135, 17, -182, 17, 1, tween.exponential.co, 1e3); | zzy-code-test | html5/fruitninja/scripts/object/logo.js | JavaScript | gpl2 | 200 |
var layer = require( "../layer" );
var x = 16, y = 0;
var texts = [];
exports.set = function(){
};
exports.clear = function(){
for(var i = 0, l = texts.length; i < l; i ++)
texts[i].remove();
texts.length = y = 0;
};
exports.log = function(text){
y += 20;
texts.push( layer.createText( "default", text, x, y ) );
}; | zzy-code-test | html5/fruitninja/scripts/object/console.js | JavaScript | gpl2 | 339 |
var layer = require( "../layer" );
var tween = require( "../lib/tween" );
var timeline = require( "../timeline" );
var Ucren = require( "../lib/ucren" );
var image;
var cycleTime = 300;
var sx = 129, sy = 328, ex = 170, ey = 221, sw = 0, sh = 0, ew = 70, eh = 42, dy = 8;
var showAnim = tween.exponential.co;
var jumpAnim = tween.quadratic.ci;
exports.anims = [];
exports.set = function(){
image = layer.createImage( "default", "images/new.png", sx, sy, sw, sh );
};
exports.unset = function(){
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: 500,
data: [ sx, ex, sy, ey, sw, ew, sh, eh ],
object: this, onTimeUpdate: this.onShowing, onTimeStart: this.onShowStart, onTimeEnd: this.onShowEnd,
recycle: this.anims
});
};
exports.hide = function( start ){
this.anims.clear();
timeline.createTask({
start: start, duration: 500,
data: [ ex, sx, ey, sy, ew, sw, eh, sh ],
object: this, onTimeUpdate: this.onShowing,
recycle: this.anims
});
};
exports.jump = function(){
this.anims.clear();
timeline.createTask({ start: 0, duration: -1, object: this, onTimeUpdate: this.onJumping, recycle: this.anims });
};
// 显示相关
exports.onShowStart = function(){
};
exports.onShowing = function( time, sx, ex, sy, ey, sw, ew, sh, eh ){
image.attr({
x: showAnim( time, sx, ex - sx, 500 ),
y: showAnim( time, sy, ey - sy, 500 ),
width: showAnim( time, sw, ew - sw, 500 ),
height: showAnim( time, sh, eh - sh, 500 )
});
};
exports.onShowEnd = function(){
this.jump();
};
// 跳跃相关
exports.onJumping = function(time){
var t = parseInt(time / cycleTime);
time = time % cycleTime;
if( t % 2 ) time = cycleTime - time;
image.attr("y", jumpAnim( time, ey, dy, cycleTime ));
}; | zzy-code-test | html5/fruitninja/scripts/object/new.js | JavaScript | gpl2 | 1,857 |
/**
* this file was compiled by jsbuild 0.9.6
* @date Mon, 16 Jul 2012 18:46:47 UTC
* @author dron
* @site http://ucren.com
*/
void function(global){
var mapping = {}, cache = {};
global.startModule = function(m){
require(m).start();
};
global.define = function(id, func){
mapping[id] = func;
};
global.require = function(id){
if(!/\.js$/.test(id))
id += '.js';
if(cache[id])
return cache[id];
else
return cache[id] = mapping[id]({});
};
}(this);
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\collide.js
*/
define("scripts/collide.js", function(exports){
var fruit = require("scripts/factory/fruit");
var Ucren = require("scripts/lib/ucren");
var fruits = fruit.getFruitInView();
/**
* 碰撞检测
*/
exports.check = function( knife ){
var ret = [], index = 0;
fruits.forEach(function( fruit ){
var ck = lineInEllipse(
knife.slice( 0, 2 ),
knife.slice( 2, 4 ),
[ fruit.originX, fruit.originY ],
fruit.radius
);
if( ck )
ret[ index ++ ] = fruit;
});
return ret;
};
function sqr(x){
return x * x;
}
function sign(n){
return n < 0 ? -1 : ( n > 0 ? 1 : 0 );
}
function equation12( a, b, c ){
if(a == 0)return;
var delta = b * b - 4 * a * c;
if(delta == 0)
return [ -1 * b / (2 * a), -1 * b / (2 * a) ];
else if(delta > 0)
return [ (-1 * b + Math.sqrt(delta)) / (2 * a), (-1 * b - Math.sqrt(delta)) / (2 * a) ];
}
// 返回线段和椭圆的两个交点,如果不相交,返回 null
function lineXEllipse( p1, p2, c, r, e ){
// 线段:p1, p2 圆心:c 半径:r 离心率:e
if (r <= 0) return;
e = e === undefined ? 1 : e;
var t1 = r, t2 = r * e, k;
a = sqr( t2) * sqr(p1[0] - p2[0]) + sqr(t1) * sqr(p1[1] - p2[1]);
if (a <= 0) return;
b = 2 * sqr(t2) * (p2[0] - p1[0]) * (p1[0] - c[0]) + 2 * sqr(t1) * (p2[1] - p1[1]) * (p1[1] - c[1]);
c = sqr(t2) * sqr(p1[0] - c[0]) + sqr(t1) * sqr(p1[1] - c[1]) - sqr(t1) * sqr(t2);
if (!( k = equation12(a, b, c, t1, t2) )) return;
var result = [
[ p1[0] + k[0] * (p2[0] - p1[0]), p1[1] + k[0] * (p2[1] - p1[1]) ],
[ p1[0] + k[1] * (p2[0] - p1[0]), p1[1] + k[1] * (p2[1] - p1[1]) ]
];
if ( !( ( sign( result[0][0] - p1[0] ) * sign( result[0][0] - p2[0] ) <= 0 ) &&
( sign( result[0][1] - p1[1] ) * sign( result[0][1] - p2[1] ) <= 0 ) ) )
result[0] = null;
if ( !( ( sign( result[1][0] - p1[0] ) * sign( result[1][0] - p2[0] ) <= 0 ) &&
( sign( result[1][1] - p1[1] ) * sign( result[1][1] - p2[1] ) <= 0 ) ) )
result[1] = null;
return result;
}
// 判断计算线段和椭圆是否相交
function lineInEllipse( p1, p2, c, r, e ){
var t = lineXEllipse( p1, p2, c, r, e );
return t && ( t[0] || t[1] );
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\control.js
*/
define("scripts/control.js", function(exports){
var Ucren = require("scripts/lib/ucren");
var knife = require("scripts/object/knife");
var message = require("scripts/message");
var state = require("scripts/state");
var canvasLeft, canvasTop;
canvasLeft = canvasTop = 0;
exports.init = function(){
this.fixCanvasPos();
this.installDragger();
this.installClicker();
};
exports.installDragger = function(){
var dragger = new Ucren.BasicDrag({ type: "calc" });
dragger.on("returnValue", function( dx, dy, x, y, kf ){
if( kf = knife.through( x - canvasLeft, y - canvasTop ) )
message.postMessage( kf, "slice" );
});
dragger.on("startDrag", function(){
knife.newKnife();
});
dragger.bind( document.documentElement );
};
exports.installClicker = function(){
Ucren.addEvent(document, "click", function(){
if( state( "click-enable" ).ison() )
message.postMessage( "click" );
});
};
exports.fixCanvasPos = function(){
var de = document.documentElement;
var fix = function(e){
canvasLeft = (de.clientWidth - 640) / 2;
canvasTop = (de.clientHeight - 480) / 2 - 40;
};
fix();
Ucren.addEvent(window, "resize", fix);
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\game.js
*/
define("scripts/game.js", function(exports){
/**
* game logic
*/
var timeline = require("scripts/timeline");
var Ucren = require("scripts/lib/ucren");
var sound = require("scripts/lib/sound");
var fruit = require("scripts/factory/fruit");
var score = require("scripts/object/score");
var message = require("scripts/message");
var state = require("scripts/state");
var lose = require("scripts/object/lose");
var gameOver = require("scripts/object/game-over");
var knife = require("scripts/object/knife");
// var sence = require("scripts/sence");
var background = require("scripts/object/background");
var light = require("scripts/object/light");
var scoreNumber = 0;
var random = Ucren.randomNumber;
var volleyNum = 2, volleyMultipleNumber = 5;
var fruits = [];
var gameInterval;
var snd;
var boomSnd;
// fruit barbette
var barbette = function(){
if( fruits.length >= volleyNum )
return ;
var startX = random( 640 ), endX = random( 640 ), startY = 600;
var f = fruit.create( startX, startY ).shotOut( 0, endX );
fruits.push( f );
snd.play();
barbette();
};
// start game
exports.start = function(){
snd = sound.create( "sound/throw" );
boomSnd = sound.create( "sound/boom" );
timeline.setTimeout(function(){
state( "game-state" ).set( "playing" );
gameInterval = timeline.setInterval( barbette, 1e3 );
}, 500);
};
exports.gameOver = function(){
state( "game-state" ).set( "over" );
gameInterval.stop();
gameOver.show();
// timeline.setTimeout(function(){
// // sence.switchSence( "home-menu" );
// // TODO: require 出现互相引用时,造成死循环,这个问题需要跟进,这里暂时用 postMessage 代替
// message.postMessage( "home-menu", "sence.switchSence" );
// }, 2000);
scoreNumber = 0;
volleyNum = 2;
fruits.length = 0;
};
exports.applyScore = function( score ){
if( score > volleyNum * volleyMultipleNumber )
volleyNum ++,
volleyMultipleNumber += 50;
};
exports.sliceAt = function( fruit, angle ){
var index;
if( state( "game-state" ).isnot( "playing" ) )
return;
if( fruit.type != "boom" ){
fruit.broken( angle );
if( index = fruits.indexOf( fruit ) )
fruits.splice( index, 1 );
score.number( ++ scoreNumber );
this.applyScore( scoreNumber );
}else{
boomSnd.play();
this.pauseAllFruit();
background.wobble();
light.start( fruit );
}
};
exports.pauseAllFruit = function(){
gameInterval.stop();
knife.pause();
fruits.invoke( "pause" );
};
// message.addEventListener("fruit.fallOff", function( fruit ){
// var index;
// if( ( index = fruits.indexOf( fruit ) ) > -1 )
// fruits.splice( index, 1 );
// });
message.addEventListener("fruit.remove", function( fruit ){
var index;
if( ( index = fruits.indexOf( fruit ) ) > -1 )
fruits.splice( index, 1 );
});
message.addEventListener("fruit.fallOutOfViewer", function( fruit ){
if( state( "game-state" ).isnot( "playing" ) )
return ;
if( fruit.type != "boom" )
lose.showLoseAt( fruit.originX );
});
message.addEventListener("game.over", function(){
exports.gameOver();
knife.switchOn();
});
message.addEventListener("overWhiteLight.show", function(){
knife.endAll();
for(var i = fruits.length - 1; i >= 0; i --)
fruits[i].remove();
background.stop();
});
message.addEventListener("click", function(){
state( "click-enable" ).off();
gameOver.hide();
message.postMessage( "home-menu", "sence.switchSence" );
});;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\layer.js
*/
define("scripts/layer.js", function(exports){
/**
* layer manager
*/
var Raphael = require("scripts/lib/raphael");
var Ucren = require("scripts/lib/ucren");
var layers = {};
var zindexs = {
"default": zi(),
"light": zi(),
"knife": zi(),
"fruit": zi(),
"juice": zi(),
"flash": zi(),
"mask": zi()
};
exports.createImage = function( layer, src, x, y, w, h ){
layer = this.getLayer( layer );
return layer.image( src, x, y, w, h );
};
exports.createText = function( layer, text, x, y, fill, size ){
layer = this.getLayer( layer );
if( Ucren.isIe )
y += 2;
return layer.text(x, y, text).attr({
fill: fill || "#fff",
"font-size": size || "14px",
"font-family": "黑体",
"text-anchor": "start"
});
};
exports.getLayer = function( name ){
var p, layer;
name = name || "default";
if( p = layers[name] ){
return p;
}else{
layer = Ucren.makeElement( "div", { "class": "layer", "style": "z-index: " + ( zindexs[name] || 0 ) + ";" } );
Ucren.Element( "extra" ).add( layer );
p = layers[name] = Raphael( layer, 640, 480 );
// if( Ucren.isSafari )
// p.safari();
return p;
}
};
function zi(){
return zi.num = ++ zi.num || 2;
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\main.js
*/
define("scripts/main.js", function(exports){
var timeline = require("scripts/timeline");
var tools = require("scripts/tools");
var sence = require("scripts/sence");
var Ucren = require("scripts/lib/ucren");
var buzz = require("scripts/lib/buzz");
var control = require("scripts/control");
var csl = require("scripts/object/console");
var message = require("scripts/message");
var state = require("scripts/state");
var game = require("scripts/game");
var collide = require("scripts/collide");
var setTimeout = timeline.setTimeout.bind( timeline );
var log = function(){
var time = 1e3, add = 300, fn;
fn = function( text ){
setTimeout( function(){ csl.log( text ); }, time );
time += add;
};
fn.clear = function(){
setTimeout( csl.clear.bind( csl ), time );
time += add;
};
return fn;
}();
exports.start = function(){
[ timeline, sence, control ].invoke( "init" );
log( "正在加载鼠标控制脚本" );
log( "正在加载图像资源" );
log( "正在加载游戏脚本" );
log( "正在加载剧情" );
log( "正在初始化" );
log( "正在启动游戏..." );
log.clear();
setTimeout( sence.switchSence.saturate( sence, "home-menu" ), 3000 );
};
message.addEventListener("slice", function( knife ){
var fruits = collide.check( knife ), angle;
if( fruits.length )
angle = tools.getAngleByRadian( tools.pointToRadian( knife.slice(0, 2), knife.slice(2, 4) ) ),
fruits.forEach(function( fruit ){
message.postMessage( fruit, angle, "slice.at" );
});
});
message.addEventListener("slice.at", function( fruit, angle ){
if( state( "sence-state" ).isnot( "ready" ) )
return ;
if( state( "sence-name" ).is( "game-body" ) ){
game.sliceAt( fruit, angle );
return ;
}
if( state( "sence-name" ).is( "home-menu" ) ){
fruit.broken( angle );
if( fruit.isHomeMenu )
switch( 1 ){
case fruit.isDojoIcon:
sence.switchSence( "dojo-body" ); break;
case fruit.isNewGameIcon:
sence.switchSence( "game-body" ); break;
case fruit.isQuitIcon:
sence.switchSence( "quit-body" ); break;
}
return ;
}
});
var tip = "";
if( !Ucren.isChrome )
tip = "$为了获得最佳流畅度,推荐您使用 <span class='b'>Google Chrome</span> 体验本游戏";
if( !buzz.isSupported() )
tip = tip.replace( "$", "您的浏览器不支持 <audio> 播放声效,且" );
tip = tip.replace( "$", "" );
Ucren.Element( "browser" ).html( tip );;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\message.js
*/
define("scripts/message.js", function(exports){
/**
* a simple message manager
* @author dron
* @date 2012-06-27
*/
var Ucren = require("scripts/lib/ucren");
/**
* send a message
* @param {Any} message,message... message contents
* @param {String} to message address
*/
exports.postMessage = function( message/*, message, message... */, to ){
var messages = [].slice.call( arguments, 0 ),
splitIndex = messages.length - 1;
to = messages[ splitIndex ];
messages.slice( 0, splitIndex );
Ucren.dispatch( to, messages );
};
/**
* bind an message handler
* @param {String} from message address
* @param {Function} fn message handler
*/
exports.addEventListener = function( from, fn ){
Ucren.dispatch( from, fn );
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\sence.js
*/
define("scripts/sence.js", function(exports){
var Ucren = require("scripts/lib/ucren");
var sound = require("scripts/lib/sound");
var fruit = require("scripts/factory/fruit");
var flash = require("scripts/object/flash");
var state = require("scripts/state");
var message = require("scripts/message");
// the fixed elements
var background = require("scripts/object/background");
var fps = require("scripts/object/fps");
// the home page elements
var homeMask = require("scripts/object/home-mask");
var logo = require("scripts/object/logo");
var ninja = require("scripts/object/ninja")
var homeDesc = require("scripts/object/home-desc");
var dojo = require("scripts/object/dojo");
var newGame = require("scripts/object/new-game");
var quit = require("scripts/object/quit");
var newSign = require("scripts/object/new");
var peach, sandia, boom;
// the elements in game body
var score = require("scripts/object/score");
var lose = require("scripts/object/lose");
// the game logic
var game = require("scripts/game");
// the elements in 'developing' module
var developing = require("scripts/object/developing");
var gameOver = require("scripts/object/game-over");
// commons
var message = require("scripts/message");
var timeline = require("scripts/timeline");
var setTimeout = timeline.setTimeout.bind( timeline );
var setInterval = timeline.setInterval.bind( timeline );
var menuSnd;
var gameStartSnd;
// initialize sence
exports.init = function(){
menuSnd = sound.create( "sound/menu" );
gameStartSnd = sound.create( "sound/start" );
[ background, homeMask, logo, ninja, homeDesc, dojo, newSign, newGame, quit, score, lose, developing, gameOver, flash, fps ].invoke( "set" );
setInterval( fps.update.bind( fps ), 500 );
};
// switch sence
exports.switchSence = function( name ){
var curSence = state( "sence-name" );
var senceState = state( "sence-state" );
if( curSence.is( name ) )
return ;
var onHide = function(){
curSence.set( name );
senceState.set( "entering" );
switch( name ){
case "home-menu": this.showMenu( onShow ); break;
case "dojo-body": this.showDojo( onShow ); break;
case "game-body": this.showNewGame( onShow ); break;
case "quit-body": this.showQuit( onShow ); break;
}
}.bind( this );
var onShow = function(){
senceState.set( "ready" );
if( name == "dojo-body" || name == "quit-body" ){
exports.switchSence( "home-menu" );
}
};
senceState.set( "exiting" );
if( curSence.isunset() ) onHide();
else if( curSence.is( "home-menu" ) ) this.hideMenu( onHide );
else if( curSence.is( "dojo-body" ) ) this.hideDojo( onHide );
else if( curSence.is( "game-body" ) ) this.hideNewGame( onHide );
else if( curSence.is( "quit-body" ) ) this.hideQuit( onHide );
};
// to enter home page menu
exports.showMenu = function( callback ){
var callee = arguments.callee;
var times = callee.times = ++ callee.times || 1;
peach = fruit.create( "peach", 137, 333, true );
sandia = fruit.create( "sandia", 330, 322, true );
boom = fruit.create( "boom", 552, 367, true, 2500 );
[ peach, sandia, boom ].forEach(function( f ){ f.isHomeMenu = 1; });
peach.isDojoIcon = sandia.isNewGameIcon = boom.isQuitIcon = 1;
var group = [
[ homeMask, 0 ],
[ logo, 0 ],
[ ninja, 500 ],
[ homeDesc, 1500 ],
[ dojo, 2000 ],
[ newGame, 2000 ],
[ quit, 2000 ],
[ newSign, 2000 ],
[ peach, 2000 ],
[ sandia, 2000 ],
[ boom, 2000 ]
];
group.invoke( "show" );
[ peach, sandia ].invoke( "rotate", 2500 );
menuSnd.play();
setTimeout( callback, 2500 );
};
// to exit home page menu
exports.hideMenu = function( callback ){
[ newSign, dojo, newGame, quit ].invoke( "hide" );
[ homeMask, logo, ninja, homeDesc ].invoke( "hide" );
[ peach, sandia, boom ].invoke( "fallOff", 150 );
menuSnd.stop();
setTimeout( callback, fruit.getDropTimeSetting() );
};
// to enter game body
exports.showNewGame = function( callback ){
score.show();
lose.show();
game.start();
gameStartSnd.play();
setTimeout( callback, 1000 );
};
// to exit game body
exports.hideNewGame = function( callback ){
score.hide();
lose.hide();
gameStartSnd.stop();
setTimeout( callback, 1000 );
};
// to enter dojo mode
exports.showDojo = function( callback ){
developing.show( 250 );
setTimeout( callback, 1500 );
};
// to exit dojo mode
exports.hideDojo = function( callback ){
// TODO:
setTimeout( callback, 1000 );
};
// to enter quit page
exports.showQuit = function( callback ){
developing.show( 250 );
setTimeout( callback, 1500 );
};
// to exit quit page
exports.hideQuit = function( callback ){
// TODO:
setTimeout( callback, 1000 );
};
message.addEventListener("sence.switchSence", function( name ){
exports.switchSence( name );
});;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\state.js
*/
define("scripts/state.js", function(exports){
/**
* a simple state manager
* @author dron
* @date 2012-06-28
*/
var Ucren = require("scripts/lib/ucren");
var timeline = require("scripts/timeline");
/**
* usage:
* state( key ).is( value ) -> determine if the value of key is the given value
* state( key ).isnot( value ) -> determine if the value of key is not given value
* state( key ).ison() -> determine if the value of key is the boolean value 'true'
* state( key ).isoff() -> determine if the value of key is the boolean value 'false'
* state( key ).isunset() -> determine if the value of key is undefined
* state( key ).set( value ) -> set the value of key to a given value
* state( key ).get() -> get the value of key
* state( key ).on() -> set the value of key to boolean value 'true'
* state( key ).off() -> set the value of key to boolean value 'false'
*/
var stack = {};
var cache = {};
exports = function( key ){
if( cache[ key ] )
return cache[ key ];
return cache[ key ] = {
is: function( value ){
return stack[key] === value;
},
isnot: function( value ){
return stack[key] !== value;
},
ison: function(){
return this.is( true );
},
isoff: function(){
return this.isnot( true );
},
isunset: function(){
return this.is( undefined );
},
set: function( value ){
return stack[key] = value;
},
get: function(){
return stack[key];
},
on: function(){
var me = this;
me.set( true );
return {
keep: function( time ){
timeline.setTimeout( me.set.saturate( me, false ), time );
}
}
},
off: function(){
var me = this;
me.set( false );
return {
keep: function( time ){
timeline.setTimeout( me.set.saturate( me, true ), time );
}
}
}
}
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\timeline.js
*/
define("scripts/timeline.js", function(exports){
/**
* a easy timeline manager
* @version 0.9
* @author dron
*/
var Ucren = require("scripts/lib/ucren");
/**
* initialize timeline
*/
exports.init = function(){
var me = this;
me.startTime = now();
me.count = 0;
// var interval = function(){
// me.count ++;
// update( now() );
// requestAnimationFrame( interval );
// };
// interval();
var time = 1;
// if( Ucren.isSafari )
// time = 10;
setInterval( function(){
me.count ++;
update( now() );
}, time );
};
/**
* create a task
* @param {Object} conf the config
* @return {Task} a task instance
*/
exports.createTask = function( conf ){
/* e.g. createTask({
start: 500, duration: 2000, data: [a, b, c,..],
object: module, onTimeUpdate: fn(time, a, b, c,..), onTimeStart: fn(a, b, c,..), onTimeEnd: fn(a, b, c,..),
recycle: []
}); */
var task = createTask(conf);
addingTasks.unshift( task );
adding = 1;
if( conf.recycle )
this.taskList( conf.recycle, task );
return task;
};
/**
* use a array to recycle the task
* @param {Array} queue be use for recycling task
* @param {Task} task a task instance
* @return {Array} this queue
*/
exports.taskList = function( queue, task ){
if( !queue.clear )
queue.clear = function(){
for(var task, i = this.length - 1; i >= 0; i --)
task = this[i],
task.stop(),
this.splice( i, 1 );
return this;
};
if( task )
queue.unshift( task );
return queue;
};
/**
* create a timer for once callback
* @param {Function} fn callback function
* @param {Number} time time, unit: ms
*/
exports.setTimeout = function( fn, time ){
// e.g. setTimeout(fn, time);
return this.createTask({ start: time, duration: 0, onTimeStart: fn });
};
/**
* create a timer for ongoing callback
* @param {Function} fn callback function
* @param {Number} time time, unit: ms
*/
exports.setInterval = function( fn, time ){
// e.g. setInterval(fn, time);
var timer = setInterval( fn, time );
return {
stop: function(){
clearInterval( timer );
}
};
};
/**
* get the current fps
* @return {Number} fps number
*/
exports.getFPS = function(){
var t = now(), fps = this.count / (t - this.startTime) * 1e3;
if(this.count > 1e3)
this.count = 0,
this.startTime = t;
return fps;
};
/**
* @private
*/
var Ucren = require("scripts/lib/ucren");
var tasks = [], addingTasks = [], adding = 0;
var now = function(){
return new Date().getTime();
};
// var requestAnimationFrame = function( glob ){
// return glob.requestAnimationFrame ||
// glob.mozRequestAnimationFrame ||
// glob.webkitRequestAnimationFrame ||
// glob.msRequestAnimationFrame ||
// glob.oRequestAnimationFrame || function( callback ) {
// setTimeout( callback, 1 );
// };
// }( window );
var createTask = function( conf ){
var object = conf.object || {};
conf.start = conf.start || 0;
return {
start: conf.start + now(),
duration: conf.duration == -1 ? 86400000 : conf.duration,
data: conf.data ? [0].concat( conf.data ) : [0],
started: 0,
object: object,
onTimeStart: conf.onTimeStart || object.onTimeStart || Ucren.nul,
onTimeUpdate: conf.onTimeUpdate || object.onTimeUpdate || Ucren.nul,
onTimeEnd: conf.onTimeEnd || object.onTimeEnd || Ucren.nul,
stop: function(){
this.stopped = 1;
}
}
};
var updateTask = function( task, time ){
var data = task.data;
data[0] = time;
task.onTimeUpdate.apply( task.object, data );
};
var checkStartTask = function( task ){
if( !task.started ){
task.started = 1;
task.onTimeStart.apply( task.object, task.data.slice(1) );
updateTask( task, 0 );
}
};
var update = function(time){
var i = tasks.length, t, task, start, duration, data;
// TODO: 三八五时检查一下 tasks 有没有释放完成
// document.title = i;
while( i -- ){
task = tasks[i];
start = task.start;
duration = task.duration;
if( time >= start ){
if( task.stopped ){
tasks.splice( i, 1 );
continue;
}
checkStartTask( task );
if( ( t = time - start ) < duration )
updateTask( task, t );
else
updateTask( task, duration ),
task.onTimeEnd.apply( task.object, task.data.slice(1) ),
tasks.splice( i, 1 );
}
}
if( adding ){
tasks.unshift.apply( tasks, addingTasks );
addingTasks.length = adding = 0;
}
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\tools.js
*/
define("scripts/tools.js", function(exports){
exports.unsetObject = function( object ){
for(var i in object)
if(object.hasOwnProperty(i) && typeof object[i] == "function")
object[i] = function(){};
};
exports.getAngleByRadian = function( radian ){
return radian * 180 / Math.PI;
}
exports.pointToRadian = function( origin, point ){
var PI = Math.PI;
if( point[0] === origin[0] ){
if ( point[1] > origin[1] )
return PI * 0.5;
return PI * 1.5
}else if( point[1] === origin[1] ){
if ( point[0] > origin[0] )
return 0;
return PI;
}
var t = Math.atan( ( origin[1] - point[1] ) / ( origin[0] - point[0] ) );
if( point[0] > origin[0] && point[1] < origin[1] )
return t + 2 * PI;
if( point[0] > origin[0] && point[1] > origin[1] )
return t;
return t + PI;
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\factory\displacement.js
*/
define("scripts/factory/displacement.js", function(exports){
var layer = require("scripts/layer");
var timeline = require("scripts/timeline");
var tween = require("scripts/lib/tween");
/**
* 位移类模块模型
*/
exports.create = function( imageSrc, width, height, origX, origY, targetX, targetY, animMap, animDur ){
var module = {};
var image;
var anim = {};
if( typeof animMap === "function" )
anim.show = anim.hide = animMap;
else
anim = animMap;
var createTask = function( start, duration, sx, sy, ex, ey, anim, mode ){
timeline.createTask({
start: start,
duration: duration,
object: module, data: [ sx, sy, ex, ey, anim, mode ],
onTimeUpdate: module.onTimeUpdate, onTimeStart: module.onTimeStart, onTimeEnd: module.onTimeEnd,
recycle: module.anims
});
};
module.anims = [];
module.set = function(){
image = layer.createImage( "default", imageSrc, origX, origY, width, height );
};
module.show = function( start ){
createTask( start, animDur, origX, origY, targetX, targetY, anim.show, "show" );
};
module.hide = function(){
this.anims.clear();
createTask( 0, animDur, targetX, targetY, origX, origY, anim.hide, "hide" );
};
module.onTimeUpdate = function( time, sx, sy, ex, ey, anim ){
image.attr( {
x: anim( time, sx, ex - sx, animDur ),
y: anim( time, sy, ey - sy, animDur )
} );
};
module.onTimeStart = function(){
};
module.onTimeEnd = function( sx, sy, ex, ey, anim ){
if( anim === "hide" )
image.hide();
};
return module;
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\factory\fruit.js
*/
define("scripts/factory/fruit.js", function(exports){
var layer = require("scripts/layer");
var Ucren = require("scripts/lib/ucren");
var timeline = require("scripts/timeline");
var tween = require("scripts/lib/tween");
var message = require("scripts/message");
var flame = require("scripts/object/flame");
var flash = require("scripts/object/flash");
var juice = require("scripts/factory/juice");
var ie = Ucren.isIe;
var safari = Ucren.isSafari;
/**
* 水果模块模型
*/
var zoomAnim = tween.exponential.co;
var rotateAnim = tween.circular;
var linearAnim = tween.linear;
var dropAnim = tween.quadratic.ci;
var fallOffAnim = tween.quadratic.co;
var random = Ucren.randomNumber;
var min = Math.min;
var average = function( a, b ){ return ( ( a + b ) / 2 ) >> 0; };
var dropTime = 1200, dropXScope = 200, shadowPos = 50;
var infos = {
// type: [ imageSrc, width, height, radius, fixAngle, isReverse, juiceColor ]
boom: [ "images/fruit/boom.png", 66, 68, 26, 0, 0, null ],
peach: [ "images/fruit/peach.png", 62, 59, 37, -50, 0, "#e6c731" ],
sandia: [ "images/fruit/sandia.png", 98, 85, 38, -100, 0, "#c00" ],
apple: [ "images/fruit/apple.png", 66, 66, 31, -54, 0, "#c8e925" ],
banana: [ "images/fruit/banana.png", 126, 50, 43, 90, 0, null ],
basaha: [ "images/fruit/basaha.png", 68, 72, 32, -135, 0, "#c00" ]
};
// TODO: 是否水果全开?
var types = [ "peach", "sandia", "apple", "banana", "basaha" ];
// var types = [ "sandia", "boom" ];
var rotateSpeed = [ 60, 50, 40, -40, -50, -60 ];
var fruitCache = [];
function ClassFruit(conf){
var info = infos[ conf.type ], radius = info[3];
this.type = conf.type;
this.originX = conf.originX;
this.originY = conf.originY;
this.radius = radius;
this.startX = conf.originX;
this.startY = conf.originY;
this.radius = radius;
this.anims = [];
if( this.type === "boom" )
this.flame = flame.create( this.startX - radius + 4, this.startY - radius + 5, conf.flameStart || 0 );
}
ClassFruit.prototype.set = function( hide ){
var inf = infos[ this.type ], radius = this.radius;
this.shadow = layer.createImage( "fruit", "images/shadow.png", this.startX - radius, this.startY - radius + shadowPos, 106, 77 );
this.image = layer.createImage( "fruit", inf[0], this.startX - radius, this.startY - radius, inf[1], inf[2] );
if( hide )
this.image.hide(),
this.shadow.hide();
return this;
};
ClassFruit.prototype.pos = function( x, y ){
var r = this.radius;
this.originX = x;
this.originY = y;
this.image.attr({ x: x -= r, y: y -= r });
this.shadow.attr({ x: x, y: y + shadowPos });
if( this.type === "boom" )
this.flame.pos( x + 4, y + 5 );
if( this.fallOffing && !this.fallOutOfViewerCalled && y > 480 + this.radius )
this.fallOutOfViewerCalled = 1,
message.postMessage( this, "fruit.fallOutOfViewer" );
};
ClassFruit.prototype.show = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1e-5, 1, "show" ],
object: this, onTimeUpdate: this.onScaling, onTimeStart: this.onShowStart,
recycle: this.anims
});
};
ClassFruit.prototype.hide = function( start ){
if( this.type !== "boom" ) // if it is not a boom, it can't to be hide.
return ;
this.anims.clear();
this.flame.remove();
timeline.createTask({
start: start, duration: 500, data: [ 1, 1e-5, "hide" ],
object: this, onTimeUpdate: this.onScaling, onTimeEnd: this.onHideEnd,
recycle: this.anims
});
};
ClassFruit.prototype.rotate = function( start, speed ){
this.rotateSpeed = speed || rotateSpeed[ random( 6 ) ];
timeline.createTask({
start: start, duration: -1,
object: this, onTimeUpdate: this.onRotating,
recycle: this.anims
});
};
ClassFruit.prototype.broken = function( angle ){
if( this.brokend )return;
this.brokend = true;
var index;
if( ( index = fruitCache.indexOf( this ) ) > -1 )
fruitCache.splice( index, 1 );
if( this.type !== "boom" )
flash.showAt( this.originX, this.originY, angle ),
juice.create( this.originX, this.originY, infos[ this.type ][6] ),
this.apart( angle );
else
this.hide();
};
ClassFruit.prototype.pause = function(){
if( this.brokend )
return;
this.anims.clear();
if( this.type == "boom" )
this.flame.remove();
};
// 分开
ClassFruit.prototype.apart = function( angle ){
this.anims.clear();
this.image.hide();
this.shadow.hide();
this.aparted = true;
var inf = infos[ this.type ], preSrc = inf[0].replace( ".png", "" ), radius = this.radius;
var create = layer.createImage.saturate( layer, this.startX - radius, this.startY - radius, inf[1], inf[2] );
angle = ( ( angle % 180 ) + 360 + inf[4] ) % 360;
this.bImage1 = create( "fruit", preSrc + "-1.png" );
this.bImage2 = create( "fruit", preSrc + "-2.png" );
[ this.bImage1, this.bImage2 ].invoke( "rotate", angle );
this.apartAngle = angle;
timeline.createTask({
start: 0, duration: dropTime, object: this,
onTimeUpdate: this.onBrokenDropUpdate, onTimeStart: this.onBrokenDropStart, onTimeEnd: this.onBrokenDropEnd,
recycle: this.anims
});
};
// 抛出
ClassFruit.prototype.shotOut = function(){
var sign = [ -1, 1 ];
return function( start, endX ){
this.shotOutStartX = this.originX;
this.shotOutStartY = this.originY;
this.shotOutEndX = average( this.originX, endX );
this.shotOutEndY = min( this.startY - random( this.startY - 100 ), 200 );
this.fallOffToX = endX;
timeline.createTask({
start: start, duration: dropTime, object: this,
onTimeUpdate: this.onShotOuting, onTimeStart: this.onShotOutStart, onTimeEnd: this.onShotOutEnd,
recycle: this.anims
});
if( this.type != "boom" )
this.rotate( 0, ( random( 180 ) + 90 ) * sign[ random( 2 ) ] );
return this;
};
}();
// 掉落
ClassFruit.prototype.fallOff = function(){
var sign = [ -1, 1 ];
var signIndex = 0;
return function( start, x ){
if( this.aparted || this.brokend )
return ;
this.fallOffing = 1;
var y = 600;
if( typeof x !== "number" )
x = this.originX + random( dropXScope ) * sign[ ( signIndex ++ ) % 2 ];
this.fallTargetX = x;
this.fallTargetY = y;
timeline.createTask({
start: start, duration: dropTime, object: this,
onTimeUpdate: this.onFalling, onTimeStart: this.onFallStart, onTimeEnd: this.onFallEnd,
recycle: this.anims
});
}
}();
ClassFruit.prototype.remove = function(){
var index;
this.anims.clear();
if( this.image )
this.image.remove(),
this.shadow.remove();
if( this.bImage1 )
this.bImage1.remove(),
this.bImage2.remove();
if( this.type === "boom" )
this.flame.remove();
if( ( index = fruitCache.indexOf( this ) ) > -1 )
fruitCache.splice( index, 1 );
for(var name in this)
if( typeof this[name] === "function" )
this[name] = function( name ){
return function(){
throw new Error( "method " + name + " has been removed" );
};
}( name );
else delete this[name];
message.postMessage( this, "fruit.remove" );
};
// 显示/隐藏 相关
ClassFruit.prototype.onShowStart = function(){
this.image.show();
// this.shadow.show();
};
ClassFruit.prototype.onScaling = function( time, a, b, z ){
this.image.scale( z = zoomAnim( time, a, b - a, 500 ), z );
this.shadow.scale( z, z );
};
ClassFruit.prototype.onHideEnd = function(){
this.remove();
};
// 旋转相关
ClassFruit.prototype.onRotateStart = function(){
};
ClassFruit.prototype.onRotating = function( time ){
this.image.rotate( ( this.rotateSpeed * time / 1e3 ) % 360, true );
};
// 裂开相关
ClassFruit.prototype.onBrokenDropUpdate = function( time ){
var radius = this.radius;
this.bImage1.attr({
x: linearAnim( time, this.brokenPosX - radius, this.brokenTargetX1, dropTime ),
y: dropAnim( time, this.brokenPosY - radius, this.brokenTargetY1 - this.brokenPosY + radius, dropTime )
}).rotate( linearAnim( time, this.apartAngle, this.bImage1RotateAngle, dropTime ), true );
this.bImage2.attr({
x: linearAnim( time, this.brokenPosX - radius, this.brokenTargetX2, dropTime ),
y: dropAnim( time, this.brokenPosY - radius, this.brokenTargetY2 - this.brokenPosY + radius, dropTime )
}).rotate( linearAnim( time, this.apartAngle, this.bImage2RotateAngle, dropTime ), true );
};
ClassFruit.prototype.onBrokenDropStart = function(){
this.brokenTargetX1 = -( random( dropXScope ) + 75 );
this.brokenTargetX2 = random( dropXScope + 75 );
this.brokenTargetY1 = 600;
this.brokenTargetY2 = 600;
this.brokenPosX = this.originX;
this.brokenPosY = this.originY;
this.bImage1RotateAngle = - random( 150 ) - 50;
this.bImage2RotateAngle = random( 150 ) + 50;
for(var f, i = fruitCache.length - 1; i >= 0; i --)
if( fruitCache[i] === this )
fruitCache.splice( i, 1 );
};
ClassFruit.prototype.onBrokenDropEnd = function(){
this.remove();
};
// 抛出相关
ClassFruit.prototype.onShotOuting = function( time ){
this.pos(
linearAnim( time, this.shotOutStartX, this.shotOutEndX - this.shotOutStartX, dropTime ),
fallOffAnim( time, this.shotOutStartY, this.shotOutEndY - this.shotOutStartY, dropTime )
);
};
ClassFruit.prototype.onShotOutStart = function(){
// body...
};
ClassFruit.prototype.onShotOutEnd = function(){
this.fallOff( 0, this.fallOffToX );
};
// 掉落相关
ClassFruit.prototype.onFalling = function( time ){
this.pos(
linearAnim( time, this.brokenPosX, this.fallTargetX - this.brokenPosX, dropTime ),
dropAnim( time, this.brokenPosY, this.fallTargetY - this.brokenPosY, dropTime )
);
};
ClassFruit.prototype.onFallStart = function(){
this.brokenPosX = this.originX;
this.brokenPosY = this.originY;
};
ClassFruit.prototype.onFallEnd = function(){
message.postMessage( this, "fruit.fallOff" );
this.remove();
};
exports.create = function( type, originX, originY, isHide, flameStart ){
if( typeof type == "number" ) // 缺省 type
isHide = originY,
originY = originX,
originX = type,
type = getType();
var fruit = new ClassFruit({ type: type, originX: originX, originY: originY, flameStart: flameStart }).set( isHide );
fruitCache.unshift( fruit );
return fruit;
};
exports.getFruitInView = function(){
return fruitCache;
};
exports.getDropTimeSetting = function(){
return dropTime;
};
function getType(){
if( random( 8 ) == 4 )
return "boom";
else
return types[ random( 5 ) ];
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\factory\juice.js
*/
define("scripts/factory/juice.js", function(exports){
/**
* 果汁
*/
var Ucren = require("scripts/lib/ucren");
var layer = require("scripts/layer").getLayer("juice");
var timeline = require("scripts/timeline");
var tween = require("scripts/lib/tween");
var tools = require("scripts/tools");
var random = Ucren.randomNumber;
var dur = 1500;
var anim = tween.exponential.co;
var dropAnim = tween.quadratic.co;
var sin = Math.sin;
var cos = Math.cos;
var switchOn = true;
var num = 10;
if( Ucren.isIe || Ucren.isSafari )
num = 7;
function ClassJuice( x, y, color ){
this.originX = x;
this.originY = y;
this.color = color;
this.distance = random( 200 ) + 100;
this.radius = 10;
this.dir = random( 360 ) * Math.PI / 180;
}
ClassJuice.prototype.render = function(){
this.circle = layer.circle( this.originX, this.originY, this.radius ).attr({
fill: this.color,
stroke: "none"
});
};
ClassJuice.prototype.sputter = function(){
timeline.createTask({
start: 0, duration: dur,
object: this, onTimeUpdate: this.onTimeUpdate, onTimeEnd: this.onTimeEnd
});
};
ClassJuice.prototype.onTimeUpdate = function( time ){
var distance, x, y, z;
distance = anim( time, 0, this.distance, dur );
x = this.originX + distance * cos( this.dir );
y = this.originY + distance * sin( this.dir ) + dropAnim( time, 0, 200, dur );
z = anim( time, 1, -1, dur );
this.circle.attr({ cx: x, cy: y }).scale( z, z );
};
ClassJuice.prototype.onTimeEnd = function(){
this.circle.remove();
tools.unsetObject( this );
};
exports.create = switchOn ? function( x, y, color ){
for(var i = 0; i < num; i ++)
this.createOne( x, y, color );
} : Ucren.nul;
exports.createOne = function( x, y, color ){
if( !color )
return;
var juice = new ClassJuice( x, y, color );
juice.render();
juice.sputter();
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\factory\rotate.js
*/
define("scripts/factory/rotate.js", function(exports){
var layer = require("scripts/layer");
var timeline = require("scripts/timeline");
var Ucren = require("scripts/lib/ucren");
/**
* 旋转类模块模型
*/
exports.create = function( imageSrc, x, y, w, h, z, anim, animDur ){
var module = {}, image;
var rotateDire = [12, -12][Ucren.randomNumber(2)];
var defaultAngle = Ucren.randomNumber(360);
module.anims = [];
module.set = function(){
image = layer.createImage( "default", imageSrc, x, y, w, h ).scale( z, z ).rotate( defaultAngle, true );
};
module.show = function(start){
timeline.createTask({
start: start,
duration: animDur,
object: this,
data: [z, 1],
onTimeUpdate: this.onZooming,
onTimeEnd: this.onShowEnd,
recycle: this.anims
});
};
module.hide = function(start){
this.anims.clear();
timeline.createTask({
start: start,
duration: animDur,
object: this,
data: [ 1, z ],
onTimeUpdate: this.onZooming,
recycle: this.anims
});
};
module.onShowEnd = function(name){
this.anims.clear();
timeline.createTask({
start: 0,
duration: -1,
object: this,
onTimeUpdate: module.onRotating,
recycle: this.anims
});
};
module.onZooming = function(){
var z;
return function( time, a, b ){
image.scale( z = anim( time, a, b - a, animDur ), z );
}
}();
module.onRotating = function(){
var lastTime = 0, an = defaultAngle;
return function( time, name, a, b ){
an = ( an + ( time - lastTime ) / 1e3 * rotateDire ) % 360;
image.rotate( an, true );
lastTime = time;
}
}();
return module;
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\lib\buzz.js
*/
define("scripts/lib/buzz.js", function(exports){
// ----------------------------------------------------------------------------
// Buzz, a Javascript HTML5 Audio library
// v 1.0.x beta
// Licensed under the MIT license.
// http://buzz.jaysalvat.com/
// ----------------------------------------------------------------------------
// Copyright (C) 2011 Jay Salvat
// http://jaysalvat.com/
// ----------------------------------------------------------------------------
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files ( the "Software" ), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ----------------------------------------------------------------------------
var buzz = {
defaults: {
autoplay: false,
duration: 5000,
formats: [],
loop: false,
placeholder: '--',
preload: 'metadata',
volume: 80
},
types: {
'mp3': 'audio/mpeg',
'ogg': 'audio/ogg',
'wav': 'audio/wav',
'aac': 'audio/aac',
'm4a': 'audio/x-m4a'
},
sounds: [],
el: document.createElement( 'audio' ),
sound: function( src, options ) {
options = options || {};
var pid = 0,
events = [],
eventsOnce = {},
supported = buzz.isSupported();
// publics
this.load = function() {
if ( !supported ) {
return this;
}
this.sound.load();
return this;
};
this.play = function() {
if ( !supported ) {
return this;
}
this.sound.play();
return this;
};
this.togglePlay = function() {
if ( !supported ) {
return this;
}
if ( this.sound.paused ) {
this.sound.play();
} else {
this.sound.pause();
}
return this;
};
this.pause = function() {
if ( !supported ) {
return this;
}
this.sound.pause();
return this;
};
this.isPaused = function() {
if ( !supported ) {
return null;
}
return this.sound.paused;
};
this.stop = function() {
if ( !supported ) {
return this;
}
this.setTime( this.getDuration() );
this.sound.pause();
return this;
};
this.isEnded = function() {
if ( !supported ) {
return null;
}
return this.sound.ended;
};
this.loop = function() {
if ( !supported ) {
return this;
}
this.sound.loop = 'loop';
this.bind( 'ended.buzzloop', function() {
this.currentTime = 0;
this.play();
});
return this;
};
this.unloop = function() {
if ( !supported ) {
return this;
}
this.sound.removeAttribute( 'loop' );
this.unbind( 'ended.buzzloop' );
return this;
};
this.mute = function() {
if ( !supported ) {
return this;
}
this.sound.muted = true;
return this;
};
this.unmute = function() {
if ( !supported ) {
return this;
}
this.sound.muted = false;
return this;
};
this.toggleMute = function() {
if ( !supported ) {
return this;
}
this.sound.muted = !this.sound.muted;
return this;
};
this.isMuted = function() {
if ( !supported ) {
return null;
}
return this.sound.muted;
};
this.setVolume = function( volume ) {
if ( !supported ) {
return this;
}
if ( volume < 0 ) {
volume = 0;
}
if ( volume > 100 ) {
volume = 100;
}
this.volume = volume;
this.sound.volume = volume / 100;
return this;
};
this.getVolume = function() {
if ( !supported ) {
return this;
}
return this.volume;
};
this.increaseVolume = function( value ) {
return this.setVolume( this.volume + ( value || 1 ) );
};
this.decreaseVolume = function( value ) {
return this.setVolume( this.volume - ( value || 1 ) );
};
this.setTime = function( time ) {
if ( !supported ) {
return this;
}
this.whenReady( function() {
this.sound.currentTime = time;
});
return this;
};
this.getTime = function() {
if ( !supported ) {
return null;
}
var time = Math.round( this.sound.currentTime * 100 ) / 100;
return isNaN( time ) ? buzz.defaults.placeholder : time;
};
this.setPercent = function( percent ) {
if ( !supported ) {
return this;
}
return this.setTime( buzz.fromPercent( percent, this.sound.duration ) );
};
this.getPercent = function() {
if ( !supported ) {
return null;
}
var percent = Math.round( buzz.toPercent( this.sound.currentTime, this.sound.duration ) );
return isNaN( percent ) ? buzz.defaults.placeholder : percent;
};
this.setSpeed = function( duration ) {
if ( !supported ) {
return this;
}
this.sound.playbackRate = duration;
};
this.getSpeed = function() {
if ( !supported ) {
return null;
}
return this.sound.playbackRate;
};
this.getDuration = function() {
if ( !supported ) {
return null;
}
var duration = Math.round( this.sound.duration * 100 ) / 100;
return isNaN( duration ) ? buzz.defaults.placeholder : duration;
};
this.getPlayed = function() {
if ( !supported ) {
return null;
}
return timerangeToArray( this.sound.played );
};
this.getBuffered = function() {
if ( !supported ) {
return null;
}
return timerangeToArray( this.sound.buffered );
};
this.getSeekable = function() {
if ( !supported ) {
return null;
}
return timerangeToArray( this.sound.seekable );
};
this.getErrorCode = function() {
if ( supported && this.sound.error ) {
return this.sound.error.code;
}
return 0;
};
this.getErrorMessage = function() {
if ( !supported ) {
return null;
}
switch( this.getErrorCode() ) {
case 1:
return 'MEDIA_ERR_ABORTED';
case 2:
return 'MEDIA_ERR_NETWORK';
case 3:
return 'MEDIA_ERR_DECODE';
case 4:
return 'MEDIA_ERR_SRC_NOT_SUPPORTED';
default:
return null;
}
};
this.getStateCode = function() {
if ( !supported ) {
return null;
}
return this.sound.readyState;
};
this.getStateMessage = function() {
if ( !supported ) {
return null;
}
switch( this.getStateCode() ) {
case 0:
return 'HAVE_NOTHING';
case 1:
return 'HAVE_METADATA';
case 2:
return 'HAVE_CURRENT_DATA';
case 3:
return 'HAVE_FUTURE_DATA';
case 4:
return 'HAVE_ENOUGH_DATA';
default:
return null;
}
};
this.getNetworkStateCode = function() {
if ( !supported ) {
return null;
}
return this.sound.networkState;
};
this.getNetworkStateMessage = function() {
if ( !supported ) {
return null;
}
switch( this.getNetworkStateCode() ) {
case 0:
return 'NETWORK_EMPTY';
case 1:
return 'NETWORK_IDLE';
case 2:
return 'NETWORK_LOADING';
case 3:
return 'NETWORK_NO_SOURCE';
default:
return null;
}
};
this.set = function( key, value ) {
if ( !supported ) {
return this;
}
this.sound[ key ] = value;
return this;
};
this.get = function( key ) {
if ( !supported ) {
return null;
}
return key ? this.sound[ key ] : this.sound;
};
this.bind = function( types, func ) {
if ( !supported ) {
return this;
}
types = types.split( ' ' );
var that = this,
efunc = function( e ) { func.call( that, e ); };
for( var t = 0; t < types.length; t++ ) {
var type = types[ t ],
idx = type;
type = idx.split( '.' )[ 0 ];
events.push( { idx: idx, func: efunc } );
this.sound.addEventListener( type, efunc, true );
}
return this;
};
this.unbind = function( types ) {
if ( !supported ) {
return this;
}
types = types.split( ' ' );
for( var t = 0; t < types.length; t++ ) {
var idx = types[ t ],
type = idx.split( '.' )[ 0 ];
for( var i = 0; i < events.length; i++ ) {
var namespace = events[ i ].idx.split( '.' );
if ( events[ i ].idx == idx || ( namespace[ 1 ] && namespace[ 1 ] == idx.replace( '.', '' ) ) ) {
this.sound.removeEventListener( type, events[ i ].func, true );
// remove event
events.splice(i, 1);
}
}
}
return this;
};
this.bindOnce = function( type, func ) {
if ( !supported ) {
return this;
}
var that = this;
eventsOnce[ pid++ ] = false;
this.bind( pid + type, function() {
if ( !eventsOnce[ pid ] ) {
eventsOnce[ pid ] = true;
func.call( that );
}
that.unbind( pid + type );
});
};
this.trigger = function( types ) {
if ( !supported ) {
return this;
}
types = types.split( ' ' );
for( var t = 0; t < types.length; t++ ) {
var idx = types[ t ];
for( var i = 0; i < events.length; i++ ) {
var eventType = events[ i ].idx.split( '.' );
if ( events[ i ].idx == idx || ( eventType[ 0 ] && eventType[ 0 ] == idx.replace( '.', '' ) ) ) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent( eventType[ 0 ], false, true );
this.sound.dispatchEvent( evt );
}
}
}
return this;
};
this.fadeTo = function( to, duration, callback ) {
if ( !supported ) {
return this;
}
if ( duration instanceof Function ) {
callback = duration;
duration = buzz.defaults.duration;
} else {
duration = duration || buzz.defaults.duration;
}
var from = this.volume,
delay = duration / Math.abs( from - to ),
that = this;
this.play();
function doFade() {
setTimeout( function() {
if ( from < to && that.volume < to ) {
that.setVolume( that.volume += 1 );
doFade();
} else if ( from > to && that.volume > to ) {
that.setVolume( that.volume -= 1 );
doFade();
} else if ( callback instanceof Function ) {
callback.apply( that );
}
}, delay );
}
this.whenReady( function() {
doFade();
});
return this;
};
this.fadeIn = function( duration, callback ) {
if ( !supported ) {
return this;
}
return this.setVolume(0).fadeTo( 100, duration, callback );
};
this.fadeOut = function( duration, callback ) {
if ( !supported ) {
return this;
}
return this.fadeTo( 0, duration, callback );
};
this.fadeWith = function( sound, duration ) {
if ( !supported ) {
return this;
}
this.fadeOut( duration, function() {
this.stop();
});
sound.play().fadeIn( duration );
return this;
};
this.whenReady = function( func ) {
if ( !supported ) {
return null;
}
var that = this;
if ( this.sound.readyState === 0 ) {
this.bind( 'canplay.buzzwhenready', function() {
func.call( that );
});
} else {
func.call( that );
}
};
// privates
function timerangeToArray( timeRange ) {
var array = [],
length = timeRange.length - 1;
for( var i = 0; i <= length; i++ ) {
array.push({
start: timeRange.start( length ),
end: timeRange.end( length )
});
}
return array;
}
function getExt( filename ) {
return filename.split('.').pop();
}
function addSource( sound, src ) {
var source = document.createElement( 'source' );
source.src = src;
if ( buzz.types[ getExt( src ) ] ) {
source.type = buzz.types[ getExt( src ) ];
}
sound.appendChild( source );
}
// init
if ( supported && src ) {
for(var i in buzz.defaults ) {
if(buzz.defaults.hasOwnProperty(i)) {
options[ i ] = options[ i ] || buzz.defaults[ i ];
}
}
this.sound = document.createElement( 'audio' );
if ( src instanceof Array ) {
for( var j in src ) {
if(src.hasOwnProperty(j)) {
addSource( this.sound, src[ j ] );
}
}
} else if ( options.formats.length ) {
for( var k in options.formats ) {
if(options.formats.hasOwnProperty(k)) {
addSource( this.sound, src + '.' + options.formats[ k ] );
}
}
} else {
addSource( this.sound, src );
}
if ( options.loop ) {
this.loop();
}
if ( options.autoplay ) {
this.sound.autoplay = 'autoplay';
}
if ( options.preload === true ) {
this.sound.preload = 'auto';
} else if ( options.preload === false ) {
this.sound.preload = 'none';
} else {
this.sound.preload = options.preload;
}
this.setVolume( options.volume );
buzz.sounds.push( this );
}
},
group: function( sounds ) {
sounds = argsToArray( sounds, arguments );
// publics
this.getSounds = function() {
return sounds;
};
this.add = function( soundArray ) {
soundArray = argsToArray( soundArray, arguments );
for( var a = 0; a < soundArray.length; a++ ) {
sounds.push( soundArray[ a ] );
}
};
this.remove = function( soundArray ) {
soundArray = argsToArray( soundArray, arguments );
for( var a = 0; a < soundArray.length; a++ ) {
for( var i = 0; i < sounds.length; i++ ) {
if ( sounds[ i ] == soundArray[ a ] ) {
delete sounds[ i ];
break;
}
}
}
};
this.load = function() {
fn( 'load' );
return this;
};
this.play = function() {
fn( 'play' );
return this;
};
this.togglePlay = function( ) {
fn( 'togglePlay' );
return this;
};
this.pause = function( time ) {
fn( 'pause', time );
return this;
};
this.stop = function() {
fn( 'stop' );
return this;
};
this.mute = function() {
fn( 'mute' );
return this;
};
this.unmute = function() {
fn( 'unmute' );
return this;
};
this.toggleMute = function() {
fn( 'toggleMute' );
return this;
};
this.setVolume = function( volume ) {
fn( 'setVolume', volume );
return this;
};
this.increaseVolume = function( value ) {
fn( 'increaseVolume', value );
return this;
};
this.decreaseVolume = function( value ) {
fn( 'decreaseVolume', value );
return this;
};
this.loop = function() {
fn( 'loop' );
return this;
};
this.unloop = function() {
fn( 'unloop' );
return this;
};
this.setTime = function( time ) {
fn( 'setTime', time );
return this;
};
this.setduration = function( duration ) {
fn( 'setduration', duration );
return this;
};
this.set = function( key, value ) {
fn( 'set', key, value );
return this;
};
this.bind = function( type, func ) {
fn( 'bind', type, func );
return this;
};
this.unbind = function( type ) {
fn( 'unbind', type );
return this;
};
this.bindOnce = function( type, func ) {
fn( 'bindOnce', type, func );
return this;
};
this.trigger = function( type ) {
fn( 'trigger', type );
return this;
};
this.fade = function( from, to, duration, callback ) {
fn( 'fade', from, to, duration, callback );
return this;
};
this.fadeIn = function( duration, callback ) {
fn( 'fadeIn', duration, callback );
return this;
};
this.fadeOut = function( duration, callback ) {
fn( 'fadeOut', duration, callback );
return this;
};
// privates
function fn() {
var args = argsToArray( null, arguments ),
func = args.shift();
for( var i = 0; i < sounds.length; i++ ) {
sounds[ i ][ func ].apply( sounds[ i ], args );
}
}
function argsToArray( array, args ) {
return ( array instanceof Array ) ? array : Array.prototype.slice.call( args );
}
},
all: function() {
return new buzz.group( buzz.sounds );
},
isSupported: function() {
return !!buzz.el.canPlayType;
},
isOGGSupported: function() {
return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/ogg; codecs="vorbis"' );
},
isWAVSupported: function() {
return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/wav; codecs="1"' );
},
isMP3Supported: function() {
return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/mpeg;' );
},
isAACSupported: function() {
return !!buzz.el.canPlayType && ( buzz.el.canPlayType( 'audio/x-m4a;' ) || buzz.el.canPlayType( 'audio/aac;' ) );
},
toTimer: function( time, withHours ) {
var h, m, s;
h = Math.floor( time / 3600 );
h = isNaN( h ) ? '--' : ( h >= 10 ) ? h : '0' + h;
m = withHours ? Math.floor( time / 60 % 60 ) : Math.floor( time / 60 );
m = isNaN( m ) ? '--' : ( m >= 10 ) ? m : '0' + m;
s = Math.floor( time % 60 );
s = isNaN( s ) ? '--' : ( s >= 10 ) ? s : '0' + s;
return withHours ? h + ':' + m + ':' + s : m + ':' + s;
},
fromTimer: function( time ) {
var splits = time.toString().split( ':' );
if ( splits && splits.length == 3 ) {
time = ( parseInt( splits[ 0 ], 10 ) * 3600 ) + ( parseInt(splits[ 1 ], 10 ) * 60 ) + parseInt( splits[ 2 ], 10 );
}
if ( splits && splits.length == 2 ) {
time = ( parseInt( splits[ 0 ], 10 ) * 60 ) + parseInt( splits[ 1 ], 10 );
}
return time;
},
toPercent: function( value, total, decimal ) {
var r = Math.pow( 10, decimal || 0 );
return Math.round( ( ( value * 100 ) / total ) * r ) / r;
},
fromPercent: function( percent, total, decimal ) {
var r = Math.pow( 10, decimal || 0 );
return Math.round( ( ( total / 100 ) * percent ) * r ) / r;
}
};
exports = buzz;;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\lib\raphael.js
*/
define("scripts/lib/raphael.js", function(exports){
/*
* Raphael 1.5.2 - JavaScript Vector Library
*
* Copyright (c) 2010 Dmitry Baranovskiy (http://raphaeljs.com)
* Licensed under the MIT (http://raphaeljs.com/license.html) license.
*/
var Raphael;
var window = {};
(function(){function a(){if(a.is(arguments[0],G)){var b=arguments[0],d=bV[m](a,b.splice(0,3+a.is(b[0],E))),e=d.set();for(var g=0,h=b[w];g<h;g++){var i=b[g]||{};c[f](i.type)&&e[L](d[i.type]().attr(i))}return e}return bV[m](a,arguments)}a.version="1.5.2";var b=/[, ]+/,c={circle:1,rect:1,path:1,ellipse:1,text:1,image:1},d=/\{(\d+)\}/g,e="prototype",f="hasOwnProperty",g=document,h=window,i={was:Object[e][f].call(h,"Raphael"),is:h.Raphael},j=function(){this.customAttributes={}},k,l="appendChild",m="apply",n="concat",o="createTouch"in g,p="",q=" ",r=String,s="split",t="click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend orientationchange touchcancel gesturestart gesturechange gestureend"[s](q),u={mousedown:"touchstart",mousemove:"touchmove",mouseup:"touchend"},v="join",w="length",x=r[e].toLowerCase,y=Math,z=y.max,A=y.min,B=y.abs,C=y.pow,D=y.PI,E="number",F="string",G="array",H="toString",I="fill",J=Object[e][H],K={},L="push",M=/^url\(['"]?([^\)]+?)['"]?\)$/i,N=/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,O={"NaN":1,Infinity:1,"-Infinity":1},P=/^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,Q=y.round,R="setAttribute",S=parseFloat,T=parseInt,U=" progid:DXImageTransform.Microsoft",V=r[e].toUpperCase,W={blur:0,"clip-rect":"0 0 1e9 1e9",cursor:"default",cx:0,cy:0,fill:"#fff","fill-opacity":1,font:"10px \"Arial\"","font-family":"\"Arial\"","font-size":"10","font-style":"normal","font-weight":400,gradient:0,height:0,href:"http://raphaeljs.com/",opacity:1,path:"M0,0",r:0,rotation:0,rx:0,ry:0,scale:"1 1",src:"",stroke:"#000","stroke-dasharray":"","stroke-linecap":"butt","stroke-linejoin":"butt","stroke-miterlimit":0,"stroke-opacity":1,"stroke-width":1,target:"_blank","text-anchor":"middle",title:"Raphael",translation:"0 0",width:0,x:0,y:0},X={along:"along",blur:E,"clip-rect":"csv",cx:E,cy:E,fill:"colour","fill-opacity":E,"font-size":E,height:E,opacity:E,path:"path",r:E,rotation:"csv",rx:E,ry:E,scale:"csv",stroke:"colour","stroke-opacity":E,"stroke-width":E,translation:"csv",width:E,x:E,y:E},Y="replace",Z=/^(from|to|\d+%?)$/,$=/\s*,\s*/,_={hs:1,rg:1},ba=/,?([achlmqrstvxz]),?/gi,bb=/([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?\s*,?\s*)+)/ig,bc=/(-?\d*\.?\d*(?:e[-+]?\d+)?)\s*,?\s*/ig,bd=/^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,be=function(a,b){return a.key-b.key};a.type=h.SVGAngle||g.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML";if(a.type=="VML"){var bf=g.createElement("div"),bg;bf.innerHTML="<v:shape adj=\"1\"/>";bg=bf.firstChild;bg.style.behavior="url(#default#VML)";if(!(bg&&typeof bg.adj=="object"))return a.type=null;bf=null}a.svg=!(a.vml=a.type=="VML");j[e]=a[e];k=j[e];a._id=0;a._oid=0;a.fn={};a.is=function(a,b){b=x.call(b);if(b=="finite")return!O[f](+a);return b=="null"&&a===null||b==typeof a||b=="object"&&a===Object(a)||b=="array"&&Array.isArray&&Array.isArray(a)||J.call(a).slice(8,-1).toLowerCase()==b};a.angle=function(b,c,d,e,f,g){{if(f==null){var h=b-d,i=c-e;if(!h&&!i)return 0;return((h<0)*180+y.atan(-i/-h)*180/D+360)%360}return a.angle(b,c,f,g)-a.angle(d,e,f,g)}};a.rad=function(a){return a%360*D/180};a.deg=function(a){return a*180/D%360};a.snapTo=function(b,c,d){d=a.is(d,"finite")?d:10;if(a.is(b,G)){var e=b.length;while(e--)if(B(b[e]-c)<=d)return b[e]}else{b=+b;var f=c%b;if(f<d)return c-f;if(f>b-d)return c-f+b}return c};function bh(){var a=[],b=0;for(;b<32;b++)a[b]=(~(~(y.random()*16)))[H](16);a[12]=4;a[16]=(a[16]&3|8)[H](16);return"r-"+a[v]("")}a.setWindow=function(a){h=a;g=h.document};var bi=function(b){if(a.vml){var c=/^\s+|\s+$/g,d;try{var e=new ActiveXObject("htmlfile");e.write("<body>");e.close();d=e.body}catch(a){d=createPopup().document.body}var f=d.createTextRange();bi=bm(function(a){try{d.style.color=r(a)[Y](c,p);var b=f.queryCommandValue("ForeColor");b=(b&255)<<16|b&65280|(b&16711680)>>>16;return"#"+("000000"+b[H](16)).slice(-6)}catch(a){return"none"}})}else{var h=g.createElement("i");h.title="Raphaël Colour Picker";h.style.display="none";g.body[l](h);bi=bm(function(a){h.style.color=a;return g.defaultView.getComputedStyle(h,p).getPropertyValue("color")})}return bi(b)},bj=function(){return"hsb("+[this.h,this.s,this.b]+")"},bk=function(){return"hsl("+[this.h,this.s,this.l]+")"},bl=function(){return this.hex};a.hsb2rgb=function(b,c,d,e){if(a.is(b,"object")&&"h"in b&&"s"in b&&"b"in b){d=b.b;c=b.s;b=b.h;e=b.o}return a.hsl2rgb(b,c,d/2,e)};a.hsl2rgb=function(b,c,d,e){if(a.is(b,"object")&&"h"in b&&"s"in b&&"l"in b){d=b.l;c=b.s;b=b.h}if(b>1||c>1||d>1){b/=360;c/=100;d/=100}var f={},g=["r","g","b"],h,i,j,k,l,m;if(c){d<0.5?h=d*(1+c):h=d+c-d*c;i=2*d-h;for(var n=0;n<3;n++){j=b+1/3*-(n-1);j<0&&j++;j>1&&j--;j*6<1?f[g[n]]=i+(h-i)*6*j:j*2<1?f[g[n]]=h:j*3<2?f[g[n]]=i+(h-i)*(2/3-j)*6:f[g[n]]=i}}else f={r:d,g:d,b:d};f.r*=255;f.g*=255;f.b*=255;f.hex="#"+(16777216|f.b|f.g<<8|f.r<<16).toString(16).slice(1);a.is(e,"finite")&&(f.opacity=e);f.toString=bl;return f};a.rgb2hsb=function(b,c,d){if(c==null&&a.is(b,"object")&&"r"in b&&"g"in b&&"b"in b){d=b.b;c=b.g;b=b.r}if(c==null&&a.is(b,F)){var e=a.getRGB(b);b=e.r;c=e.g;d=e.b}if(b>1||c>1||d>1){b/=255;c/=255;d/=255}var f=z(b,c,d),g=A(b,c,d),h,i,j=f;{if(g==f)return{h:0,s:0,b:f,toString:bj};var k=f-g;i=k/f;b==f?h=(c-d)/k:c==f?h=2+(d-b)/k:h=4+(b-c)/k;h/=6;h<0&&h++;h>1&&h--}return{h:h,s:i,b:j,toString:bj}};a.rgb2hsl=function(b,c,d){if(c==null&&a.is(b,"object")&&"r"in b&&"g"in b&&"b"in b){d=b.b;c=b.g;b=b.r}if(c==null&&a.is(b,F)){var e=a.getRGB(b);b=e.r;c=e.g;d=e.b}if(b>1||c>1||d>1){b/=255;c/=255;d/=255}var f=z(b,c,d),g=A(b,c,d),h,i,j=(f+g)/2,k;if(g==f)k={h:0,s:0,l:j};else{var l=f-g;i=j<0.5?l/(f+g):l/(2-f-g);b==f?h=(c-d)/l:c==f?h=2+(d-b)/l:h=4+(b-c)/l;h/=6;h<0&&h++;h>1&&h--;k={h:h,s:i,l:j}}k.toString=bk;return k};a._path2string=function(){return this.join(",")[Y](ba,"$1")};function bm(a,b,c){function d(){var g=Array[e].slice.call(arguments,0),h=g[v]("►"),i=d.cache=d.cache||{},j=d.count=d.count||[];if(i[f](h))return c?c(i[h]):i[h];j[w]>=1000&&delete i[j.shift()];j[L](h);i[h]=a[m](b,g);return c?c(i[h]):i[h]}return d}a.getRGB=bm(function(b){if(!b||!(!((b=r(b)).indexOf("-")+1)))return{r:-1,g:-1,b:-1,hex:"none",error:1};if(b=="none")return{r:-1,g:-1,b:-1,hex:"none"};!(_[f](b.toLowerCase().substring(0,2))||b.charAt()=="#")&&(b=bi(b));var c,d,e,g,h,i,j,k=b.match(N);if(k){if(k[2]){g=T(k[2].substring(5),16);e=T(k[2].substring(3,5),16);d=T(k[2].substring(1,3),16)}if(k[3]){g=T((i=k[3].charAt(3))+i,16);e=T((i=k[3].charAt(2))+i,16);d=T((i=k[3].charAt(1))+i,16)}if(k[4]){j=k[4][s]($);d=S(j[0]);j[0].slice(-1)=="%"&&(d*=2.55);e=S(j[1]);j[1].slice(-1)=="%"&&(e*=2.55);g=S(j[2]);j[2].slice(-1)=="%"&&(g*=2.55);k[1].toLowerCase().slice(0,4)=="rgba"&&(h=S(j[3]));j[3]&&j[3].slice(-1)=="%"&&(h/=100)}if(k[5]){j=k[5][s]($);d=S(j[0]);j[0].slice(-1)=="%"&&(d*=2.55);e=S(j[1]);j[1].slice(-1)=="%"&&(e*=2.55);g=S(j[2]);j[2].slice(-1)=="%"&&(g*=2.55);(j[0].slice(-3)=="deg"||j[0].slice(-1)=="°")&&(d/=360);k[1].toLowerCase().slice(0,4)=="hsba"&&(h=S(j[3]));j[3]&&j[3].slice(-1)=="%"&&(h/=100);return a.hsb2rgb(d,e,g,h)}if(k[6]){j=k[6][s]($);d=S(j[0]);j[0].slice(-1)=="%"&&(d*=2.55);e=S(j[1]);j[1].slice(-1)=="%"&&(e*=2.55);g=S(j[2]);j[2].slice(-1)=="%"&&(g*=2.55);(j[0].slice(-3)=="deg"||j[0].slice(-1)=="°")&&(d/=360);k[1].toLowerCase().slice(0,4)=="hsla"&&(h=S(j[3]));j[3]&&j[3].slice(-1)=="%"&&(h/=100);return a.hsl2rgb(d,e,g,h)}k={r:d,g:e,b:g};k.hex="#"+(16777216|g|e<<8|d<<16).toString(16).slice(1);a.is(h,"finite")&&(k.opacity=h);return k}return{r:-1,g:-1,b:-1,hex:"none",error:1}},a);a.getColor=function(a){var b=this.getColor.start=this.getColor.start||{h:0,s:1,b:a||0.75},c=this.hsb2rgb(b.h,b.s,b.b);b.h+=0.075;if(b.h>1){b.h=0;b.s-=0.2;b.s<=0&&(this.getColor.start={h:0,s:1,b:b.b})}return c.hex};a.getColor.reset=function(){delete this.start};a.parsePathString=bm(function(b){if(!b)return null;var c={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},d=[];a.is(b,G)&&a.is(b[0],G)&&(d=bo(b));d[w]||r(b)[Y](bb,function(a,b,e){var f=[],g=x.call(b);e[Y](bc,function(a,b){b&&f[L](+b)});if(g=="m"&&f[w]>2){d[L]([b][n](f.splice(0,2)));g="l";b=b=="m"?"l":"L"}while(f[w]>=c[g]){d[L]([b][n](f.splice(0,c[g])));if(!c[g])break}});d[H]=a._path2string;return d});a.findDotsAtSegment=function(a,b,c,d,e,f,g,h,i){var j=1-i,k=C(j,3)*a+C(j,2)*3*i*c+j*3*i*i*e+C(i,3)*g,l=C(j,3)*b+C(j,2)*3*i*d+j*3*i*i*f+C(i,3)*h,m=a+2*i*(c-a)+i*i*(e-2*c+a),n=b+2*i*(d-b)+i*i*(f-2*d+b),o=c+2*i*(e-c)+i*i*(g-2*e+c),p=d+2*i*(f-d)+i*i*(h-2*f+d),q=(1-i)*a+i*c,r=(1-i)*b+i*d,s=(1-i)*e+i*g,t=(1-i)*f+i*h,u=90-y.atan((m-o)/(n-p))*180/D;(m>o||n<p)&&(u+=180);return{x:k,y:l,m:{x:m,y:n},n:{x:o,y:p},start:{x:q,y:r},end:{x:s,y:t},alpha:u}};var bn=bm(function(a){if(!a)return{x:0,y:0,width:0,height:0};a=bw(a);var b=0,c=0,d=[],e=[],f;for(var g=0,h=a[w];g<h;g++){f=a[g];if(f[0]=="M"){b=f[1];c=f[2];d[L](b);e[L](c)}else{var i=bv(b,c,f[1],f[2],f[3],f[4],f[5],f[6]);d=d[n](i.min.x,i.max.x);e=e[n](i.min.y,i.max.y);b=f[5];c=f[6]}}var j=A[m](0,d),k=A[m](0,e);return{x:j,y:k,width:z[m](0,d)-j,height:z[m](0,e)-k}}),bo=function(b){var c=[];if(!a.is(b,G)||!a.is(b&&b[0],G))b=a.parsePathString(b);for(var d=0,e=b[w];d<e;d++){c[d]=[];for(var f=0,g=b[d][w];f<g;f++)c[d][f]=b[d][f]}c[H]=a._path2string;return c},bp=bm(function(b){if(!a.is(b,G)||!a.is(b&&b[0],G))b=a.parsePathString(b);var c=[],d=0,e=0,f=0,g=0,h=0;if(b[0][0]=="M"){d=b[0][1];e=b[0][2];f=d;g=e;h++;c[L](["M",d,e])}for(var i=h,j=b[w];i<j;i++){var k=c[i]=[],l=b[i];if(l[0]!=x.call(l[0])){k[0]=x.call(l[0]);switch(k[0]){case"a":k[1]=l[1];k[2]=l[2];k[3]=l[3];k[4]=l[4];k[5]=l[5];k[6]=+(l[6]-d).toFixed(3);k[7]=+(l[7]-e).toFixed(3);break;case"v":k[1]=+(l[1]-e).toFixed(3);break;case"m":f=l[1];g=l[2];default:for(var m=1,n=l[w];m<n;m++)k[m]=+(l[m]-(m%2?d:e)).toFixed(3)}}else{k=c[i]=[];if(l[0]=="m"){f=l[1]+d;g=l[2]+e}for(var o=0,p=l[w];o<p;o++)c[i][o]=l[o]}var q=c[i][w];switch(c[i][0]){case"z":d=f;e=g;break;case"h":d+=+c[i][q-1];break;case"v":e+=+c[i][q-1];break;default:d+=+c[i][q-2];e+=+c[i][q-1]}}c[H]=a._path2string;return c},0,bo),bq=bm(function(b){if(!a.is(b,G)||!a.is(b&&b[0],G))b=a.parsePathString(b);var c=[],d=0,e=0,f=0,g=0,h=0;if(b[0][0]=="M"){d=+b[0][1];e=+b[0][2];f=d;g=e;h++;c[0]=["M",d,e]}for(var i=h,j=b[w];i<j;i++){var k=c[i]=[],l=b[i];if(l[0]!=V.call(l[0])){k[0]=V.call(l[0]);switch(k[0]){case"A":k[1]=l[1];k[2]=l[2];k[3]=l[3];k[4]=l[4];k[5]=l[5];k[6]=+(l[6]+d);k[7]=+(l[7]+e);break;case"V":k[1]=+l[1]+e;break;case"H":k[1]=+l[1]+d;break;case"M":f=+l[1]+d;g=+l[2]+e;default:for(var m=1,n=l[w];m<n;m++)k[m]=+l[m]+(m%2?d:e)}}else for(var o=0,p=l[w];o<p;o++)c[i][o]=l[o];switch(k[0]){case"Z":d=f;e=g;break;case"H":d=k[1];break;case"V":e=k[1];break;case"M":f=c[i][c[i][w]-2];g=c[i][c[i][w]-1];default:d=c[i][c[i][w]-2];e=c[i][c[i][w]-1]}}c[H]=a._path2string;return c},null,bo),br=function(a,b,c,d){return[a,b,c,d,c,d]},bs=function(a,b,c,d,e,f){var g=1/3,h=2/3;return[g*a+h*c,g*b+h*d,g*e+h*c,g*f+h*d,e,f]},bt=function(a,b,c,d,e,f,g,h,i,j){var k=D*120/180,l=D/180*(+e||0),m=[],o,p=bm(function(a,b,c){var d=a*y.cos(c)-b*y.sin(c),e=a*y.sin(c)+b*y.cos(c);return{x:d,y:e}});if(j){G=j[0];H=j[1];E=j[2];F=j[3]}else{o=p(a,b,-l);a=o.x;b=o.y;o=p(h,i,-l);h=o.x;i=o.y;var q=y.cos(D/180*e),r=y.sin(D/180*e),t=(a-h)/2,u=(b-i)/2,x=t*t/(c*c)+u*u/(d*d);if(x>1){x=y.sqrt(x);c=x*c;d=x*d}var z=c*c,A=d*d,C=(f==g?-1:1)*y.sqrt(B((z*A-z*u*u-A*t*t)/(z*u*u+A*t*t))),E=C*c*u/d+(a+h)/2,F=C*-d*t/c+(b+i)/2,G=y.asin(((b-F)/d).toFixed(9)),H=y.asin(((i-F)/d).toFixed(9));G=a<E?D-G:G;H=h<E?D-H:H;G<0&&(G=D*2+G);H<0&&(H=D*2+H);g&&G>H&&(G=G-D*2);!g&&H>G&&(H=H-D*2)}var I=H-G;if(B(I)>k){var J=H,K=h,L=i;H=G+k*(g&&H>G?1:-1);h=E+c*y.cos(H);i=F+d*y.sin(H);m=bt(h,i,c,d,e,0,g,K,L,[H,J,E,F])}I=H-G;var M=y.cos(G),N=y.sin(G),O=y.cos(H),P=y.sin(H),Q=y.tan(I/4),R=4/3*c*Q,S=4/3*d*Q,T=[a,b],U=[a+R*N,b-S*M],V=[h+R*P,i-S*O],W=[h,i];U[0]=2*T[0]-U[0];U[1]=2*T[1]-U[1];{if(j)return[U,V,W][n](m);m=[U,V,W][n](m)[v]()[s](",");var X=[];for(var Y=0,Z=m[w];Y<Z;Y++)X[Y]=Y%2?p(m[Y-1],m[Y],l).y:p(m[Y],m[Y+1],l).x;return X}},bu=function(a,b,c,d,e,f,g,h,i){var j=1-i;return{x:C(j,3)*a+C(j,2)*3*i*c+j*3*i*i*e+C(i,3)*g,y:C(j,3)*b+C(j,2)*3*i*d+j*3*i*i*f+C(i,3)*h}},bv=bm(function(a,b,c,d,e,f,g,h){var i=e-2*c+a-(g-2*e+c),j=2*(c-a)-2*(e-c),k=a-c,l=(-j+y.sqrt(j*j-4*i*k))/2/i,n=(-j-y.sqrt(j*j-4*i*k))/2/i,o=[b,h],p=[a,g],q;B(l)>"1e12"&&(l=0.5);B(n)>"1e12"&&(n=0.5);if(l>0&&l<1){q=bu(a,b,c,d,e,f,g,h,l);p[L](q.x);o[L](q.y)}if(n>0&&n<1){q=bu(a,b,c,d,e,f,g,h,n);p[L](q.x);o[L](q.y)}i=f-2*d+b-(h-2*f+d);j=2*(d-b)-2*(f-d);k=b-d;l=(-j+y.sqrt(j*j-4*i*k))/2/i;n=(-j-y.sqrt(j*j-4*i*k))/2/i;B(l)>"1e12"&&(l=0.5);B(n)>"1e12"&&(n=0.5);if(l>0&&l<1){q=bu(a,b,c,d,e,f,g,h,l);p[L](q.x);o[L](q.y)}if(n>0&&n<1){q=bu(a,b,c,d,e,f,g,h,n);p[L](q.x);o[L](q.y)}return{min:{x:A[m](0,p),y:A[m](0,o)},max:{x:z[m](0,p),y:z[m](0,o)}}}),bw=bm(function(a,b){var c=bq(a),d=b&&bq(b),e={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},f={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},g=function(a,b){var c,d;if(!a)return["C",b.x,b.y,b.x,b.y,b.x,b.y];!(a[0]in{T:1,Q:1})&&(b.qx=b.qy=null);switch(a[0]){case"M":b.X=a[1];b.Y=a[2];break;case"A":a=["C"][n](bt[m](0,[b.x,b.y][n](a.slice(1))));break;case"S":c=b.x+(b.x-(b.bx||b.x));d=b.y+(b.y-(b.by||b.y));a=["C",c,d][n](a.slice(1));break;case"T":b.qx=b.x+(b.x-(b.qx||b.x));b.qy=b.y+(b.y-(b.qy||b.y));a=["C"][n](bs(b.x,b.y,b.qx,b.qy,a[1],a[2]));break;case"Q":b.qx=a[1];b.qy=a[2];a=["C"][n](bs(b.x,b.y,a[1],a[2],a[3],a[4]));break;case"L":a=["C"][n](br(b.x,b.y,a[1],a[2]));break;case"H":a=["C"][n](br(b.x,b.y,a[1],b.y));break;case"V":a=["C"][n](br(b.x,b.y,b.x,a[1]));break;case"Z":a=["C"][n](br(b.x,b.y,b.X,b.Y));break}return a},h=function(a,b){if(a[b][w]>7){a[b].shift();var e=a[b];while(e[w])a.splice(b++,0,["C"][n](e.splice(0,6)));a.splice(b,1);k=z(c[w],d&&d[w]||0)}},i=function(a,b,e,f,g){if(a&&b&&a[g][0]=="M"&&b[g][0]!="M"){b.splice(g,0,["M",f.x,f.y]);e.bx=0;e.by=0;e.x=a[g][1];e.y=a[g][2];k=z(c[w],d&&d[w]||0)}};for(var j=0,k=z(c[w],d&&d[w]||0);j<k;j++){c[j]=g(c[j],e);h(c,j);d&&(d[j]=g(d[j],f));d&&h(d,j);i(c,d,e,f,j);i(d,c,f,e,j);var l=c[j],o=d&&d[j],p=l[w],q=d&&o[w];e.x=l[p-2];e.y=l[p-1];e.bx=S(l[p-4])||e.x;e.by=S(l[p-3])||e.y;f.bx=d&&(S(o[q-4])||f.x);f.by=d&&(S(o[q-3])||f.y);f.x=d&&o[q-2];f.y=d&&o[q-1]}return d?[c,d]:c},null,bo),bx=bm(function(b){var c=[];for(var d=0,e=b[w];d<e;d++){var f={},g=b[d].match(/^([^:]*):?([\d\.]*)/);f.color=a.getRGB(g[1]);if(f.color.error)return null;f.color=f.color.hex;g[2]&&(f.offset=g[2]+"%");c[L](f)}for(d=1,e=c[w]-1;d<e;d++){if(!c[d].offset){var h=S(c[d-1].offset||0),i=0;for(var j=d+1;j<e;j++){if(c[j].offset){i=c[j].offset;break}}if(!i){i=100;j=e}i=S(i);var k=(i-h)/(j-d+1);for(;d<j;d++){h+=k;c[d].offset=h+"%"}}}return c}),by=function(b,c,d,e){var f;if(a.is(b,F)||a.is(b,"object")){f=a.is(b,F)?g.getElementById(b):b;if(f.tagName)return c==null?{container:f,width:f.style.pixelWidth||f.offsetWidth,height:f.style.pixelHeight||f.offsetHeight}:{container:f,width:c,height:d}}else return{container:1,x:b,y:c,width:d,height:e}},bz=function(a,b){var c=this;for(var d in b){if(b[f](d)&&!(d in a))switch(typeof b[d]){case"function":(function(b){a[d]=a===c?b:function(){return b[m](c,arguments)}})(b[d]);break;case"object":a[d]=a[d]||{};bz.call(this,a[d],b[d]);break;default:a[d]=b[d];break}}},bA=function(a,b){a==b.top&&(b.top=a.prev);a==b.bottom&&(b.bottom=a.next);a.next&&(a.next.prev=a.prev);a.prev&&(a.prev.next=a.next)},bB=function(a,b){if(b.top===a)return;bA(a,b);a.next=null;a.prev=b.top;b.top.next=a;b.top=a},bC=function(a,b){if(b.bottom===a)return;bA(a,b);a.next=b.bottom;a.prev=null;b.bottom.prev=a;b.bottom=a},bD=function(a,b,c){bA(a,c);b==c.top&&(c.top=a);b.next&&(b.next.prev=a);a.next=b.next;a.prev=b;b.next=a},bE=function(a,b,c){bA(a,c);b==c.bottom&&(c.bottom=a);b.prev&&(b.prev.next=a);a.prev=b.prev;b.prev=a;a.next=b},bF=function(a){return function(){throw new Error("Raphaël: you are calling to method “"+a+"” of removed object")}};a.pathToRelative=bp;if(a.svg){k.svgns="http://www.w3.org/2000/svg";k.xlink="http://www.w3.org/1999/xlink";Q=function(a){return+a+(~(~a)===a)*0.5};var bG=function(a,b){if(b)for(var c in b)b[f](c)&&a[R](c,r(b[c]));else{a=g.createElementNS(k.svgns,a);a.style.webkitTapHighlightColor="rgba(0,0,0,0)";return a}};a[H]=function(){return"Your browser supports SVG.\nYou are running Raphaël "+this.version};var bH=function(a,b){var c=bG("path");b.canvas&&b.canvas[l](c);var d=new bN(c,b);d.type="path";bK(d,{fill:"none",stroke:"#000",path:a});return d},bI=function(a,b,c){var d="linear",e=0.5,f=0.5,h=a.style;b=r(b)[Y](bd,function(a,b,c){d="radial";if(b&&c){e=S(b);f=S(c);var g=(f>0.5)*2-1;C(e-0.5,2)+C(f-0.5,2)>0.25&&(f=y.sqrt(0.25-C(e-0.5,2))*g+0.5)&&f!=0.5&&(f=f.toFixed(5)-0.00001*g)}return p});b=b[s](/\s*\-\s*/);if(d=="linear"){var i=b.shift();i=-S(i);if(isNaN(i))return null;var j=[0,0,y.cos(i*D/180),y.sin(i*D/180)],k=1/(z(B(j[2]),B(j[3]))||1);j[2]*=k;j[3]*=k;if(j[2]<0){j[0]=-j[2];j[2]=0}if(j[3]<0){j[1]=-j[3];j[3]=0}}var m=bx(b);if(!m)return null;var n=a.getAttribute(I);n=n.match(/^url\(#(.*)\)$/);n&&c.defs.removeChild(g.getElementById(n[1]));var o=bG(d+"Gradient");o.id=bh();bG(o,d=="radial"?{fx:e,fy:f}:{x1:j[0],y1:j[1],x2:j[2],y2:j[3]});c.defs[l](o);for(var q=0,t=m[w];q<t;q++){var u=bG("stop");bG(u,{offset:m[q].offset?m[q].offset:q?"100%":"0%","stop-color":m[q].color||"#fff"});o[l](u)}bG(a,{fill:"url(#"+o.id+")",opacity:1,"fill-opacity":1});h.fill=p;h.opacity=1;h.fillOpacity=1;return 1},bJ=function(b){var c=b.getBBox();bG(b.pattern,{patternTransform:a.format("translate({0},{1})",c.x,c.y)})},bK=function(c,d){var e={"":[0],none:[0],"-":[3,1],".":[1,1],"-.":[3,1,1,1],"-..":[3,1,1,1,1,1],". ":[1,3],"- ":[4,3],"--":[8,3],"- .":[4,3,1,3],"--.":[8,3,1,3],"--..":[8,3,1,3,1,3]},h=c.node,i=c.attrs,j=c.rotate(),k=function(a,b){b=e[x.call(b)];if(b){var c=a.attrs["stroke-width"]||"1",f=({round:c,square:c,butt:0})[a.attrs["stroke-linecap"]||d["stroke-linecap"]]||0,g=[],i=b[w];while(i--)g[i]=b[i]*c+(i%2?1:-1)*f;bG(h,{"stroke-dasharray":g[v](",")})}};d[f]("rotation")&&(j=d.rotation);var m=r(j)[s](b);if(m.length-1){m[1]=+m[1];m[2]=+m[2]}else m=null;S(j)&&c.rotate(0,true);for(var n in d){if(d[f](n)){if(!W[f](n))continue;var o=d[n];i[n]=o;switch(n){case"blur":c.blur(o);break;case"rotation":c.rotate(o,true);break;case"href":case"title":case"target":var t=h.parentNode;if(x.call(t.tagName)!="a"){var u=bG("a");t.insertBefore(u,h);u[l](h);t=u}n=="target"&&o=="blank"?t.setAttributeNS(c.paper.xlink,"show","new"):t.setAttributeNS(c.paper.xlink,n,o);break;case"cursor":h.style.cursor=o;break;case"clip-rect":var y=r(o)[s](b);if(y[w]==4){c.clip&&c.clip.parentNode.parentNode.removeChild(c.clip.parentNode);var z=bG("clipPath"),A=bG("rect");z.id=bh();bG(A,{x:y[0],y:y[1],width:y[2],height:y[3]});z[l](A);c.paper.defs[l](z);bG(h,{"clip-path":"url(#"+z.id+")"});c.clip=A}if(!o){var B=g.getElementById(h.getAttribute("clip-path")[Y](/(^url\(#|\)$)/g,p));B&&B.parentNode.removeChild(B);bG(h,{"clip-path":p});delete c.clip}break;case"path":c.type=="path"&&bG(h,{d:o?i.path=bq(o):"M0,0"});break;case"width":h[R](n,o);if(i.fx){n="x";o=i.x}else break;case"x":i.fx&&(o=-i.x-(i.width||0));case"rx":if(n=="rx"&&c.type=="rect")break;case"cx":m&&(n=="x"||n=="cx")&&(m[1]+=o-i[n]);h[R](n,o);c.pattern&&bJ(c);break;case"height":h[R](n,o);if(i.fy){n="y";o=i.y}else break;case"y":i.fy&&(o=-i.y-(i.height||0));case"ry":if(n=="ry"&&c.type=="rect")break;case"cy":m&&(n=="y"||n=="cy")&&(m[2]+=o-i[n]);h[R](n,o);c.pattern&&bJ(c);break;case"r":c.type=="rect"?bG(h,{rx:o,ry:o}):h[R](n,o);break;case"src":c.type=="image"&&h.setAttributeNS(c.paper.xlink,"href",o);break;case"stroke-width":h.style.strokeWidth=o;h[R](n,o);i["stroke-dasharray"]&&k(c,i["stroke-dasharray"]);break;case"stroke-dasharray":k(c,o);break;case"translation":var C=r(o)[s](b);C[0]=+C[0]||0;C[1]=+C[1]||0;if(m){m[1]+=C[0];m[2]+=C[1]}cz.call(c,C[0],C[1]);break;case"scale":C=r(o)[s](b);c.scale(+C[0]||1,+C[1]||+C[0]||1,isNaN(S(C[2]))?null:+C[2],isNaN(S(C[3]))?null:+C[3]);break;case I:var D=r(o).match(M);if(D){z=bG("pattern");var E=bG("image");z.id=bh();bG(z,{x:0,y:0,patternUnits:"userSpaceOnUse",height:1,width:1});bG(E,{x:0,y:0});E.setAttributeNS(c.paper.xlink,"href",D[1]);z[l](E);var F=g.createElement("img");F.style.cssText="position:absolute;left:-9999em;top-9999em";F.onload=function(){bG(z,{width:this.offsetWidth,height:this.offsetHeight});bG(E,{width:this.offsetWidth,height:this.offsetHeight});g.body.removeChild(this);c.paper.safari()};g.body[l](F);F.src=D[1];c.paper.defs[l](z);h.style.fill="url(#"+z.id+")";bG(h,{fill:"url(#"+z.id+")"});c.pattern=z;c.pattern&&bJ(c);break}var G=a.getRGB(o);if(G.error)if((({circle:1,ellipse:1})[f](c.type)||r(o).charAt()!="r")&&bI(h,o,c.paper)){i.gradient=o;i.fill="none";break}else{delete d.gradient;delete i.gradient;!a.is(i.opacity,"undefined")&&a.is(d.opacity,"undefined")&&bG(h,{opacity:i.opacity});!a.is(i["fill-opacity"],"undefined")&&a.is(d["fill-opacity"],"undefined")&&bG(h,{"fill-opacity":i["fill-opacity"]})}G[f]("opacity")&&bG(h,{"fill-opacity":G.opacity>1?G.opacity/100:G.opacity});case"stroke":G=a.getRGB(o);h[R](n,G.hex);n=="stroke"&&G[f]("opacity")&&bG(h,{"stroke-opacity":G.opacity>1?G.opacity/100:G.opacity});break;case"gradient":(({circle:1,ellipse:1})[f](c.type)||r(o).charAt()!="r")&&bI(h,o,c.paper);break;case"opacity":i.gradient&&!i[f]("stroke-opacity")&&bG(h,{"stroke-opacity":o>1?o/100:o});case"fill-opacity":if(i.gradient){var H=g.getElementById(h.getAttribute(I)[Y](/^url\(#|\)$/g,p));if(H){var J=H.getElementsByTagName("stop");J[J[w]-1][R]("stop-opacity",o)}break}default:n=="font-size"&&(o=T(o,10)+"px");var K=n[Y](/(\-.)/g,function(a){return V.call(a.substring(1))});h.style[K]=o;h[R](n,o);break}}}bM(c,d);m?c.rotate(m.join(q)):S(j)&&c.rotate(j,true)},bL=1.2,bM=function(b,c){if(b.type!="text"||!(c[f]("text")||c[f]("font")||c[f]("font-size")||c[f]("x")||c[f]("y")))return;var d=b.attrs,e=b.node,h=e.firstChild?T(g.defaultView.getComputedStyle(e.firstChild,p).getPropertyValue("font-size"),10):10;if(c[f]("text")){d.text=c.text;while(e.firstChild)e.removeChild(e.firstChild);var i=r(c.text)[s]("\n");for(var j=0,k=i[w];j<k;j++)if(i[j]){var m=bG("tspan");j&&bG(m,{dy:h*bL,x:d.x});m[l](g.createTextNode(i[j]));e[l](m)}}else{i=e.getElementsByTagName("tspan");for(j=0,k=i[w];j<k;j++)j&&bG(i[j],{dy:h*bL,x:d.x})}bG(e,{y:d.y});var n=b.getBBox(),o=d.y-(n.y+n.height/2);o&&a.is(o,"finite")&&bG(e,{y:d.y+o})},bN=function(b,c){var d=0,e=0;this[0]=b;this.id=a._oid++;this.node=b;b.raphael=this;this.paper=c;this.attrs=this.attrs||{};this.transformations=[];this._={tx:0,ty:0,rt:{deg:0,cx:0,cy:0},sx:1,sy:1};!c.bottom&&(c.bottom=this);this.prev=c.top;c.top&&(c.top.next=this);c.top=this;this.next=null},bO=bN[e];bN[e].rotate=function(c,d,e){if(this.removed)return this;if(c==null){if(this._.rt.cx)return[this._.rt.deg,this._.rt.cx,this._.rt.cy][v](q);return this._.rt.deg}var f=this.getBBox();c=r(c)[s](b);if(c[w]-1){d=S(c[1]);e=S(c[2])}c=S(c[0]);d!=null&&d!==false?this._.rt.deg=c:this._.rt.deg+=c;e==null&&(d=null);this._.rt.cx=d;this._.rt.cy=e;d=d==null?f.x+f.width/2:d;e=e==null?f.y+f.height/2:e;if(this._.rt.deg){this.transformations[0]=a.format("rotate({0} {1} {2})",this._.rt.deg,d,e);this.clip&&bG(this.clip,{transform:a.format("rotate({0} {1} {2})",-this._.rt.deg,d,e)})}else{this.transformations[0]=p;this.clip&&bG(this.clip,{transform:p})}bG(this.node,{transform:this.transformations[v](q)});return this};bN[e].hide=function(){!this.removed&&(this.node.style.display="none");return this};bN[e].show=function(){!this.removed&&(this.node.style.display="");return this};bN[e].remove=function(){if(this.removed)return;bA(this,this.paper);this.node.parentNode.removeChild(this.node);for(var a in this)delete this[a];this.removed=true};bN[e].getBBox=function(){if(this.removed)return this;if(this.type=="path")return bn(this.attrs.path);if(this.node.style.display=="none"){this.show();var a=true}var b={};try{b=this.node.getBBox()}catch(a){}finally{b=b||{}}if(this.type=="text"){b={x:b.x,y:Infinity,width:0,height:0};for(var c=0,d=this.node.getNumberOfChars();c<d;c++){var e=this.node.getExtentOfChar(c);e.y<b.y&&(b.y=e.y);e.y+e.height-b.y>b.height&&(b.height=e.y+e.height-b.y);e.x+e.width-b.x>b.width&&(b.width=e.x+e.width-b.x)}}a&&this.hide();return b};bN[e].attr=function(b,c){if(this.removed)return this;if(b==null){var d={};for(var e in this.attrs)this.attrs[f](e)&&(d[e]=this.attrs[e]);this._.rt.deg&&(d.rotation=this.rotate());(this._.sx!=1||this._.sy!=1)&&(d.scale=this.scale());d.gradient&&d.fill=="none"&&(d.fill=d.gradient)&&delete d.gradient;return d}if(c==null&&a.is(b,F)){if(b=="translation")return cz.call(this);if(b=="rotation")return this.rotate();if(b=="scale")return this.scale();if(b==I&&this.attrs.fill=="none"&&this.attrs.gradient)return this.attrs.gradient;return this.attrs[b]}if(c==null&&a.is(b,G)){var g={};for(var h=0,i=b.length;h<i;h++)g[b[h]]=this.attr(b[h]);return g}if(c!=null){var j={};j[b]=c}else b!=null&&a.is(b,"object")&&(j=b);for(var k in this.paper.customAttributes)if(this.paper.customAttributes[f](k)&&j[f](k)&&a.is(this.paper.customAttributes[k],"function")){var l=this.paper.customAttributes[k].apply(this,[][n](j[k]));this.attrs[k]=j[k];for(var m in l)l[f](m)&&(j[m]=l[m])}bK(this,j);return this};bN[e].toFront=function(){if(this.removed)return this;this.node.parentNode[l](this.node);var a=this.paper;a.top!=this&&bB(this,a);return this};bN[e].toBack=function(){if(this.removed)return this;if(this.node.parentNode.firstChild!=this.node){this.node.parentNode.insertBefore(this.node,this.node.parentNode.firstChild);bC(this,this.paper);var a=this.paper}return this};bN[e].insertAfter=function(a){if(this.removed)return this;var b=a.node||a[a.length-1].node;b.nextSibling?b.parentNode.insertBefore(this.node,b.nextSibling):b.parentNode[l](this.node);bD(this,a,this.paper);return this};bN[e].insertBefore=function(a){if(this.removed)return this;var b=a.node||a[0].node;b.parentNode.insertBefore(this.node,b);bE(this,a,this.paper);return this};bN[e].blur=function(a){var b=this;if(+a!==0){var c=bG("filter"),d=bG("feGaussianBlur");b.attrs.blur=a;c.id=bh();bG(d,{stdDeviation:+a||1.5});c.appendChild(d);b.paper.defs.appendChild(c);b._blur=c;bG(b.node,{filter:"url(#"+c.id+")"})}else{if(b._blur){b._blur.parentNode.removeChild(b._blur);delete b._blur;delete b.attrs.blur}b.node.removeAttribute("filter")}};var bP=function(a,b,c,d){var e=bG("circle");a.canvas&&a.canvas[l](e);var f=new bN(e,a);f.attrs={cx:b,cy:c,r:d,fill:"none",stroke:"#000"};f.type="circle";bG(e,f.attrs);return f},bQ=function(a,b,c,d,e,f){var g=bG("rect");a.canvas&&a.canvas[l](g);var h=new bN(g,a);h.attrs={x:b,y:c,width:d,height:e,r:f||0,rx:f||0,ry:f||0,fill:"none",stroke:"#000"};h.type="rect";bG(g,h.attrs);return h},bR=function(a,b,c,d,e){var f=bG("ellipse");a.canvas&&a.canvas[l](f);var g=new bN(f,a);g.attrs={cx:b,cy:c,rx:d,ry:e,fill:"none",stroke:"#000"};g.type="ellipse";bG(f,g.attrs);return g},bS=function(a,b,c,d,e,f){var g=bG("image");bG(g,{x:c,y:d,width:e,height:f,preserveAspectRatio:"none"});g.setAttributeNS(a.xlink,"href",b);a.canvas&&a.canvas[l](g);var h=new bN(g,a);h.attrs={x:c,y:d,width:e,height:f,src:b};h.type="image";return h},bT=function(a,b,c,d){var e=bG("text");bG(e,{x:b,y:c,"text-anchor":"middle"});a.canvas&&a.canvas[l](e);var f=new bN(e,a);f.attrs={x:b,y:c,"text-anchor":"middle",text:d,font:W.font,stroke:"none",fill:"#000"};f.type="text";bK(f,f.attrs);return f},bU=function(a,b){this.width=a||this.width;this.height=b||this.height;this.canvas[R]("width",this.width);this.canvas[R]("height",this.height);return this},bV=function(){var b=by[m](0,arguments),c=b&&b.container,d=b.x,e=b.y,f=b.width,h=b.height;if(!c)throw new Error("SVG container not found.");var i=bG("svg");d=d||0;e=e||0;f=f||512;h=h||342;bG(i,{xmlns:"http://www.w3.org/2000/svg",version:1.1,width:f,height:h});if(c==1){i.style.cssText="position:absolute;left:"+d+"px;top:"+e+"px";g.body[l](i)}else c.firstChild?c.insertBefore(i,c.firstChild):c[l](i);c=new j;c.width=f;c.height=h;c.canvas=i;bz.call(c,c,a.fn);c.clear();return c};k.clear=function(){var a=this.canvas;while(a.firstChild)a.removeChild(a.firstChild);this.bottom=this.top=null;(this.desc=bG("desc"))[l](g.createTextNode("Created with Raphaël"));a[l](this.desc);a[l](this.defs=bG("defs"))};k.remove=function(){this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas);for(var a in this)this[a]=bF(a)}}if(a.vml){var bW={M:"m",L:"l",C:"c",Z:"x",m:"t",l:"r",c:"v",z:"x"},bX=/([clmz]),?([^clmz]*)/gi,bY=/ progid:\S+Blur\([^\)]+\)/g,bZ=/-?[^,\s-]+/g,b$=1000+q+1000,b_=10,ca={path:1,rect:1},cb=function(a){var b=/[ahqstv]/ig,c=bq;r(a).match(b)&&(c=bw);b=/[clmz]/g;if(c==bq&&!r(a).match(b)){var d=r(a)[Y](bX,function(a,b,c){var d=[],e=x.call(b)=="m",f=bW[b];c[Y](bZ,function(a){if(e&&d[w]==2){f+=d+bW[b=="m"?"l":"L"];d=[]}d[L](Q(a*b_))});return f+d});return d}var e=c(a),f,g;d=[];for(var h=0,i=e[w];h<i;h++){f=e[h];g=x.call(e[h][0]);g=="z"&&(g="x");for(var j=1,k=f[w];j<k;j++)g+=Q(f[j]*b_)+(j!=k-1?",":p);d[L](g)}return d[v](q)};a[H]=function(){return"Your browser doesn’t support SVG. Falling down to VML.\nYou are running Raphaël "+this.version};bH=function(a,b){var c=cd("group");c.style.cssText="position:absolute;left:0;top:0;width:"+b.width+"px;height:"+b.height+"px";c.coordsize=b.coordsize;c.coordorigin=b.coordorigin;var d=cd("shape"),e=d.style;e.width=b.width+"px";e.height=b.height+"px";d.coordsize=b$;d.coordorigin=b.coordorigin;c[l](d);var f=new bN(d,c,b),g={fill:"none",stroke:"#000"};a&&(g.path=a);f.type="path";f.path=[];f.Path=p;bK(f,g);b.canvas[l](c);return f};bK=function(c,d){c.attrs=c.attrs||{};var e=c.node,h=c.attrs,i=e.style,j,k=(d.x!=h.x||d.y!=h.y||d.width!=h.width||d.height!=h.height||d.r!=h.r)&&c.type=="rect",m=c;for(var n in d)d[f](n)&&(h[n]=d[n]);if(k){h.path=cc(h.x,h.y,h.width,h.height,h.r);c.X=h.x;c.Y=h.y;c.W=h.width;c.H=h.height}d.href&&(e.href=d.href);d.title&&(e.title=d.title);d.target&&(e.target=d.target);d.cursor&&(i.cursor=d.cursor);"blur"in d&&c.blur(d.blur);if(d.path&&c.type=="path"||k)e.path=cb(h.path);d.rotation!=null&&c.rotate(d.rotation,true);if(d.translation){j=r(d.translation)[s](b);cz.call(c,j[0],j[1]);if(c._.rt.cx!=null){c._.rt.cx+=+j[0];c._.rt.cy+=+j[1];c.setBox(c.attrs,j[0],j[1])}}if(d.scale){j=r(d.scale)[s](b);c.scale(+j[0]||1,+j[1]||+j[0]||1,+j[2]||null,+j[3]||null)}if("clip-rect"in d){var o=r(d["clip-rect"])[s](b);if(o[w]==4){o[2]=+o[2]+ +o[0];o[3]=+o[3]+ +o[1];var q=e.clipRect||g.createElement("div"),t=q.style,u=e.parentNode;t.clip=a.format("rect({1}px {2}px {3}px {0}px)",o);if(!e.clipRect){t.position="absolute";t.top=0;t.left=0;t.width=c.paper.width+"px";t.height=c.paper.height+"px";u.parentNode.insertBefore(q,u);q[l](u);e.clipRect=q}}d["clip-rect"]||e.clipRect&&(e.clipRect.style.clip=p)}c.type=="image"&&d.src&&(e.src=d.src);if(c.type=="image"&&d.opacity){e.filterOpacity=U+".Alpha(opacity="+d.opacity*100+")";i.filter=(e.filterMatrix||p)+(e.filterOpacity||p)}d.font&&(i.font=d.font);d["font-family"]&&(i.fontFamily="\""+d["font-family"][s](",")[0][Y](/^['"]+|['"]+$/g,p)+"\"");d["font-size"]&&(i.fontSize=d["font-size"]);d["font-weight"]&&(i.fontWeight=d["font-weight"]);d["font-style"]&&(i.fontStyle=d["font-style"]);if(d.opacity!=null||d["stroke-width"]!=null||d.fill!=null||d.stroke!=null||d["stroke-width"]!=null||d["stroke-opacity"]!=null||d["fill-opacity"]!=null||d["stroke-dasharray"]!=null||d["stroke-miterlimit"]!=null||d["stroke-linejoin"]!=null||d["stroke-linecap"]!=null){e=c.shape||e;var v=e.getElementsByTagName(I)&&e.getElementsByTagName(I)[0],x=false;!v&&(x=v=cd(I));if("fill-opacity"in d||"opacity"in d){var y=((+h["fill-opacity"]+1||2)-1)*((+h.opacity+1||2)-1)*((+a.getRGB(d.fill).o+1||2)-1);y=A(z(y,0),1);v.opacity=y}d.fill&&(v.on=true);if(v.on==null||d.fill=="none")v.on=false;if(v.on&&d.fill){var B=d.fill.match(M);if(B){v.src=B[1];v.type="tile"}else{v.color=a.getRGB(d.fill).hex;v.src=p;v.type="solid";if(a.getRGB(d.fill).error&&(m.type in{circle:1,ellipse:1}||r(d.fill).charAt()!="r")&&bI(m,d.fill)){h.fill="none";h.gradient=d.fill}}}x&&e[l](v);var C=e.getElementsByTagName("stroke")&&e.getElementsByTagName("stroke")[0],D=false;!C&&(D=C=cd("stroke"));if(d.stroke&&d.stroke!="none"||d["stroke-width"]||d["stroke-opacity"]!=null||d["stroke-dasharray"]||d["stroke-miterlimit"]||d["stroke-linejoin"]||d["stroke-linecap"])C.on=true;(d.stroke=="none"||C.on==null||d.stroke==0||d["stroke-width"]==0)&&(C.on=false);var E=a.getRGB(d.stroke);C.on&&d.stroke&&(C.color=E.hex);y=((+h["stroke-opacity"]+1||2)-1)*((+h.opacity+1||2)-1)*((+E.o+1||2)-1);var F=(S(d["stroke-width"])||1)*0.75;y=A(z(y,0),1);d["stroke-width"]==null&&(F=h["stroke-width"]);d["stroke-width"]&&(C.weight=F);F&&F<1&&(y*=F)&&(C.weight=1);C.opacity=y;d["stroke-linejoin"]&&(C.joinstyle=d["stroke-linejoin"]||"miter");C.miterlimit=d["stroke-miterlimit"]||8;d["stroke-linecap"]&&(C.endcap=d["stroke-linecap"]=="butt"?"flat":d["stroke-linecap"]=="square"?"square":"round");if(d["stroke-dasharray"]){var G={"-":"shortdash",".":"shortdot","-.":"shortdashdot","-..":"shortdashdotdot",". ":"dot","- ":"dash","--":"longdash","- .":"dashdot","--.":"longdashdot","--..":"longdashdotdot"};C.dashstyle=G[f](d["stroke-dasharray"])?G[d["stroke-dasharray"]]:p}D&&e[l](C)}if(m.type=="text"){i=m.paper.span.style;h.font&&(i.font=h.font);h["font-family"]&&(i.fontFamily=h["font-family"]);h["font-size"]&&(i.fontSize=h["font-size"]);h["font-weight"]&&(i.fontWeight=h["font-weight"]);h["font-style"]&&(i.fontStyle=h["font-style"]);m.node.string&&(m.paper.span.innerHTML=r(m.node.string)[Y](/</g,"<")[Y](/&/g,"&")[Y](/\n/g,"<br>"));m.W=h.w=m.paper.span.offsetWidth;m.H=h.h=m.paper.span.offsetHeight;m.X=h.x;m.Y=h.y+Q(m.H/2);switch(h["text-anchor"]){case"start":m.node.style["v-text-align"]="left";m.bbx=Q(m.W/2);break;case"end":m.node.style["v-text-align"]="right";m.bbx=-Q(m.W/2);break;default:m.node.style["v-text-align"]="center";break}}};bI=function(a,b){a.attrs=a.attrs||{};var c=a.attrs,d,e="linear",f=".5 .5";a.attrs.gradient=b;b=r(b)[Y](bd,function(a,b,c){e="radial";if(b&&c){b=S(b);c=S(c);C(b-0.5,2)+C(c-0.5,2)>0.25&&(c=y.sqrt(0.25-C(b-0.5,2))*((c>0.5)*2-1)+0.5);f=b+q+c}return p});b=b[s](/\s*\-\s*/);if(e=="linear"){var g=b.shift();g=-S(g);if(isNaN(g))return null}var h=bx(b);if(!h)return null;a=a.shape||a.node;d=a.getElementsByTagName(I)[0]||cd(I);!d.parentNode&&a.appendChild(d);if(h[w]){d.on=true;d.method="none";d.color=h[0].color;d.color2=h[h[w]-1].color;var i=[];for(var j=0,k=h[w];j<k;j++)h[j].offset&&i[L](h[j].offset+q+h[j].color);d.colors&&(d.colors.value=i[w]?i[v]():"0% "+d.color);if(e=="radial"){d.type="gradientradial";d.focus="100%";d.focussize=f;d.focusposition=f}else{d.type="gradient";d.angle=(270-g)%360}}return 1};bN=function(b,c,d){var e=0,f=0,g=0,h=1;this[0]=b;this.id=a._oid++;this.node=b;b.raphael=this;this.X=0;this.Y=0;this.attrs={};this.Group=c;this.paper=d;this._={tx:0,ty:0,rt:{deg:0},sx:1,sy:1};!d.bottom&&(d.bottom=this);this.prev=d.top;d.top&&(d.top.next=this);d.top=this;this.next=null};bO=bN[e];bO.rotate=function(a,c,d){if(this.removed)return this;if(a==null){if(this._.rt.cx)return[this._.rt.deg,this._.rt.cx,this._.rt.cy][v](q);return this._.rt.deg}a=r(a)[s](b);if(a[w]-1){c=S(a[1]);d=S(a[2])}a=S(a[0]);c!=null?this._.rt.deg=a:this._.rt.deg+=a;d==null&&(c=null);this._.rt.cx=c;this._.rt.cy=d;this.setBox(this.attrs,c,d);this.Group.style.rotation=this._.rt.deg;return this};bO.setBox=function(a,b,c){if(this.removed)return this;var d=this.Group.style,e=this.shape&&this.shape.style||this.node.style;a=a||{};for(var g in a)a[f](g)&&(this.attrs[g]=a[g]);b=b||this._.rt.cx;c=c||this._.rt.cy;var h=this.attrs,i,j,k,l;switch(this.type){case"circle":i=h.cx-h.r;j=h.cy-h.r;k=l=h.r*2;break;case"ellipse":i=h.cx-h.rx;j=h.cy-h.ry;k=h.rx*2;l=h.ry*2;break;case"image":i=+h.x;j=+h.y;k=h.width||0;l=h.height||0;break;case"text":this.textpath.v=["m",Q(h.x),", ",Q(h.y-2),"l",Q(h.x)+1,", ",Q(h.y-2)][v](p);i=h.x-Q(this.W/2);j=h.y-this.H/2;k=this.W;l=this.H;break;case"rect":case"path":if(this.attrs.path){var m=bn(this.attrs.path);i=m.x;j=m.y;k=m.width;l=m.height}else{i=0;j=0;k=this.paper.width;l=this.paper.height}break;default:i=0;j=0;k=this.paper.width;l=this.paper.height;break}b=b==null?i+k/2:b;c=c==null?j+l/2:c;var n=b-this.paper.width/2,o=c-this.paper.height/2,q;d.left!=(q=n+"px")&&(d.left=q);d.top!=(q=o+"px")&&(d.top=q);this.X=ca[f](this.type)?-n:i;this.Y=ca[f](this.type)?-o:j;this.W=k;this.H=l;if(ca[f](this.type)){e.left!=(q=-n*b_+"px")&&(e.left=q);e.top!=(q=-o*b_+"px")&&(e.top=q)}else if(this.type=="text"){e.left!=(q=-n+"px")&&(e.left=q);e.top!=(q=-o+"px")&&(e.top=q)}else{d.width!=(q=this.paper.width+"px")&&(d.width=q);d.height!=(q=this.paper.height+"px")&&(d.height=q);e.left!=(q=i-n+"px")&&(e.left=q);e.top!=(q=j-o+"px")&&(e.top=q);e.width!=(q=k+"px")&&(e.width=q);e.height!=(q=l+"px")&&(e.height=q)}};bO.hide=function(){!this.removed&&(this.Group.style.display="none");return this};bO.show=function(){!this.removed&&(this.Group.style.display="block");return this};bO.getBBox=function(){if(this.removed)return this;if(ca[f](this.type))return bn(this.attrs.path);return{x:this.X+(this.bbx||0),y:this.Y,width:this.W,height:this.H}};bO.remove=function(){if(this.removed)return;bA(this,this.paper);this.node.parentNode.removeChild(this.node);this.Group.parentNode.removeChild(this.Group);this.shape&&this.shape.parentNode.removeChild(this.shape);for(var a in this)delete this[a];this.removed=true};bO.attr=function(b,c){if(this.removed)return this;if(b==null){var d={};for(var e in this.attrs)this.attrs[f](e)&&(d[e]=this.attrs[e]);this._.rt.deg&&(d.rotation=this.rotate());(this._.sx!=1||this._.sy!=1)&&(d.scale=this.scale());d.gradient&&d.fill=="none"&&(d.fill=d.gradient)&&delete d.gradient;return d}if(c==null&&a.is(b,"string")){if(b=="translation")return cz.call(this);if(b=="rotation")return this.rotate();if(b=="scale")return this.scale();if(b==I&&this.attrs.fill=="none"&&this.attrs.gradient)return this.attrs.gradient;return this.attrs[b]}if(this.attrs&&c==null&&a.is(b,G)){var g,h={};for(e=0,g=b[w];e<g;e++)h[b[e]]=this.attr(b[e]);return h}var i;if(c!=null){i={};i[b]=c}c==null&&a.is(b,"object")&&(i=b);if(i){for(var j in this.paper.customAttributes)if(this.paper.customAttributes[f](j)&&i[f](j)&&a.is(this.paper.customAttributes[j],"function")){var k=this.paper.customAttributes[j].apply(this,[][n](i[j]));this.attrs[j]=i[j];for(var l in k)k[f](l)&&(i[l]=k[l])}i.text&&this.type=="text"&&(this.node.string=i.text);bK(this,i);i.gradient&&(({circle:1,ellipse:1})[f](this.type)||r(i.gradient).charAt()!="r")&&bI(this,i.gradient);(!ca[f](this.type)||this._.rt.deg)&&this.setBox(this.attrs)}return this};bO.toFront=function(){!this.removed&&this.Group.parentNode[l](this.Group);this.paper.top!=this&&bB(this,this.paper);return this};bO.toBack=function(){if(this.removed)return this;if(this.Group.parentNode.firstChild!=this.Group){this.Group.parentNode.insertBefore(this.Group,this.Group.parentNode.firstChild);bC(this,this.paper)}return this};bO.insertAfter=function(a){if(this.removed)return this;a.constructor==cC&&(a=a[a.length-1]);a.Group.nextSibling?a.Group.parentNode.insertBefore(this.Group,a.Group.nextSibling):a.Group.parentNode[l](this.Group);bD(this,a,this.paper);return this};bO.insertBefore=function(a){if(this.removed)return this;a.constructor==cC&&(a=a[0]);a.Group.parentNode.insertBefore(this.Group,a.Group);bE(this,a,this.paper);return this};bO.blur=function(b){var c=this.node.runtimeStyle,d=c.filter;d=d.replace(bY,p);if(+b!==0){this.attrs.blur=b;c.filter=d+q+U+".Blur(pixelradius="+(+b||1.5)+")";c.margin=a.format("-{0}px 0 0 -{0}px",Q(+b||1.5))}else{c.filter=d;c.margin=0;delete this.attrs.blur}};bP=function(a,b,c,d){var e=cd("group"),f=cd("oval"),g=f.style;e.style.cssText="position:absolute;left:0;top:0;width:"+a.width+"px;height:"+a.height+"px";e.coordsize=b$;e.coordorigin=a.coordorigin;e[l](f);var h=new bN(f,e,a);h.type="circle";bK(h,{stroke:"#000",fill:"none"});h.attrs.cx=b;h.attrs.cy=c;h.attrs.r=d;h.setBox({x:b-d,y:c-d,width:d*2,height:d*2});a.canvas[l](e);return h};function cc(b,c,d,e,f){return f?a.format("M{0},{1}l{2},0a{3},{3},0,0,1,{3},{3}l0,{5}a{3},{3},0,0,1,{4},{3}l{6},0a{3},{3},0,0,1,{4},{4}l0,{7}a{3},{3},0,0,1,{3},{4}z",b+f,c,d-f*2,f,-f,e-f*2,f*2-d,f*2-e):a.format("M{0},{1}l{2},0,0,{3},{4},0z",b,c,d,e,-d)}bQ=function(a,b,c,d,e,f){var g=cc(b,c,d,e,f),h=a.path(g),i=h.attrs;h.X=i.x=b;h.Y=i.y=c;h.W=i.width=d;h.H=i.height=e;i.r=f;i.path=g;h.type="rect";return h};bR=function(a,b,c,d,e){var f=cd("group"),g=cd("oval"),h=g.style;f.style.cssText="position:absolute;left:0;top:0;width:"+a.width+"px;height:"+a.height+"px";f.coordsize=b$;f.coordorigin=a.coordorigin;f[l](g);var i=new bN(g,f,a);i.type="ellipse";bK(i,{stroke:"#000"});i.attrs.cx=b;i.attrs.cy=c;i.attrs.rx=d;i.attrs.ry=e;i.setBox({x:b-d,y:c-e,width:d*2,height:e*2});a.canvas[l](f);return i};bS=function(a,b,c,d,e,f){var g=cd("group"),h=cd("image");g.style.cssText="position:absolute;left:0;top:0;width:"+a.width+"px;height:"+a.height+"px";g.coordsize=b$;g.coordorigin=a.coordorigin;h.src=b;g[l](h);var i=new bN(h,g,a);i.type="image";i.attrs.src=b;i.attrs.x=c;i.attrs.y=d;i.attrs.w=e;i.attrs.h=f;i.setBox({x:c,y:d,width:e,height:f});a.canvas[l](g);return i};bT=function(b,c,d,e){var f=cd("group"),g=cd("shape"),h=g.style,i=cd("path"),j=i.style,k=cd("textpath");f.style.cssText="position:absolute;left:0;top:0;width:"+b.width+"px;height:"+b.height+"px";f.coordsize=b$;f.coordorigin=b.coordorigin;i.v=a.format("m{0},{1}l{2},{1}",Q(c*10),Q(d*10),Q(c*10)+1);i.textpathok=true;h.width=b.width;h.height=b.height;k.string=r(e);k.on=true;g[l](k);g[l](i);f[l](g);var m=new bN(k,f,b);m.shape=g;m.textpath=i;m.type="text";m.attrs.text=e;m.attrs.x=c;m.attrs.y=d;m.attrs.w=1;m.attrs.h=1;bK(m,{font:W.font,stroke:"none",fill:"#000"});m.setBox();b.canvas[l](f);return m};bU=function(a,b){var c=this.canvas.style;a==+a&&(a+="px");b==+b&&(b+="px");c.width=a;c.height=b;c.clip="rect(0 "+a+" "+b+" 0)";return this};var cd;g.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{!g.namespaces.rvml&&g.namespaces.add("rvml","urn:schemas-microsoft-com:vml");cd=function(a){return g.createElement("<rvml:"+a+" class=\"rvml\">")}}catch(a){cd=function(a){return g.createElement("<"+a+" xmlns=\"urn:schemas-microsoft.com:vml\" class=\"rvml\">")}}bV=function(){var b=by[m](0,arguments),c=b.container,d=b.height,e,f=b.width,h=b.x,i=b.y;if(!c)throw new Error("VML container not found.");var k=new j,n=k.canvas=g.createElement("div"),o=n.style;h=h||0;i=i||0;f=f||512;d=d||342;f==+f&&(f+="px");d==+d&&(d+="px");k.width=1000;k.height=1000;k.coordsize=b_*1000+q+b_*1000;k.coordorigin="0 0";k.span=g.createElement("span");k.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";n[l](k.span);o.cssText=a.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",f,d);if(c==1){g.body[l](n);o.left=h+"px";o.top=i+"px";o.position="absolute"}else c.firstChild?c.insertBefore(n,c.firstChild):c[l](n);bz.call(k,k,a.fn);return k};k.clear=function(){this.canvas.innerHTML=p;this.span=g.createElement("span");this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";this.canvas[l](this.span);this.bottom=this.top=null};k.remove=function(){this.canvas.parentNode.removeChild(this.canvas);for(var a in this)this[a]=bF(a);return true}}var ce=navigator.userAgent.match(/Version\\x2f(.*?)\s/);navigator.vendor=="Apple Computer, Inc."&&(ce&&ce[1]<4||navigator.platform.slice(0,2)=="iP")?k.safari=function(){var a=this.rect(-99,-99,this.width+99,this.height+99).attr({stroke:"none"});h.setTimeout(function(){a.remove()})}:k.safari=function(){};var cf=function(){this.returnValue=false},cg=function(){return this.originalEvent.preventDefault()},ch=function(){this.cancelBubble=true},ci=function(){return this.originalEvent.stopPropagation()},cj=(function(){{if(g.addEventListener)return function(a,b,c,d){var e=o&&u[b]?u[b]:b,g=function(e){if(o&&u[f](b))for(var g=0,h=e.targetTouches&&e.targetTouches.length;g<h;g++){if(e.targetTouches[g].target==a){var i=e;e=e.targetTouches[g];e.originalEvent=i;e.preventDefault=cg;e.stopPropagation=ci;break}}return c.call(d,e)};a.addEventListener(e,g,false);return function(){a.removeEventListener(e,g,false);return true}};if(g.attachEvent)return function(a,b,c,d){var e=function(a){a=a||h.event;a.preventDefault=a.preventDefault||cf;a.stopPropagation=a.stopPropagation||ch;return c.call(d,a)};a.attachEvent("on"+b,e);var f=function(){a.detachEvent("on"+b,e);return true};return f}}})(),ck=[],cl=function(a){var b=a.clientX,c=a.clientY,d=g.documentElement.scrollTop||g.body.scrollTop,e=g.documentElement.scrollLeft||g.body.scrollLeft,f,h=ck.length;while(h--){f=ck[h];if(o){var i=a.touches.length,j;while(i--){j=a.touches[i];if(j.identifier==f.el._drag.id){b=j.clientX;c=j.clientY;(a.originalEvent?a.originalEvent:a).preventDefault();break}}}else a.preventDefault();b+=e;c+=d;f.move&&f.move.call(f.move_scope||f.el,b-f.el._drag.x,c-f.el._drag.y,b,c,a)}},cm=function(b){a.unmousemove(cl).unmouseup(cm);var c=ck.length,d;while(c--){d=ck[c];d.el._drag={};d.end&&d.end.call(d.end_scope||d.start_scope||d.move_scope||d.el,b)}ck=[]};for(var cn=t[w];cn--;)(function(b){a[b]=bN[e][b]=function(c,d){if(a.is(c,"function")){this.events=this.events||[];this.events.push({name:b,f:c,unbind:cj(this.shape||this.node||g,b,c,d||this)})}return this};a["un"+b]=bN[e]["un"+b]=function(a){var c=this.events,d=c[w];while(d--)if(c[d].name==b&&c[d].f==a){c[d].unbind();c.splice(d,1);!c.length&&delete this.events;return this}return this}})(t[cn]);bO.hover=function(a,b,c,d){return this.mouseover(a,c).mouseout(b,d||c)};bO.unhover=function(a,b){return this.unmouseover(a).unmouseout(b)};bO.drag=function(b,c,d,e,f,h){this._drag={};this.mousedown(function(i){(i.originalEvent||i).preventDefault();var j=g.documentElement.scrollTop||g.body.scrollTop,k=g.documentElement.scrollLeft||g.body.scrollLeft;this._drag.x=i.clientX+k;this._drag.y=i.clientY+j;this._drag.id=i.identifier;c&&c.call(f||e||this,i.clientX+k,i.clientY+j,i);!ck.length&&a.mousemove(cl).mouseup(cm);ck.push({el:this,move:b,end:d,move_scope:e,start_scope:f,end_scope:h})});return this};bO.undrag=function(b,c,d){var e=ck.length;while(e--)ck[e].el==this&&(ck[e].move==b&&ck[e].end==d)&&ck.splice(e++,1);!ck.length&&a.unmousemove(cl).unmouseup(cm)};k.circle=function(a,b,c){return bP(this,a||0,b||0,c||0)};k.rect=function(a,b,c,d,e){return bQ(this,a||0,b||0,c||0,d||0,e||0)};k.ellipse=function(a,b,c,d){return bR(this,a||0,b||0,c||0,d||0)};k.path=function(b){b&&!a.is(b,F)&&!a.is(b[0],G)&&(b+=p);return bH(a.format[m](a,arguments),this)};k.image=function(a,b,c,d,e){return bS(this,a||"about:blank",b||0,c||0,d||0,e||0)};k.text=function(a,b,c){return bT(this,a||0,b||0,r(c))};k.set=function(a){arguments[w]>1&&(a=Array[e].splice.call(arguments,0,arguments[w]));return new cC(a)};k.setSize=bU;k.top=k.bottom=null;k.raphael=a;function co(){return this.x+q+this.y}bO.resetScale=function(){if(this.removed)return this;this._.sx=1;this._.sy=1;this.attrs.scale="1 1"};bO.scale=function(a,b,c,d){if(this.removed)return this;if(a==null&&b==null)return{x:this._.sx,y:this._.sy,toString:co};b=b||a;!(+b)&&(b=a);var e,f,g,h,i=this.attrs;if(a!=0){var j=this.getBBox(),k=j.x+j.width/2,l=j.y+j.height/2,m=B(a/this._.sx),o=B(b/this._.sy);c=+c||c==0?c:k;d=+d||d==0?d:l;var r=this._.sx>0,s=this._.sy>0,t=~(~(a/B(a))),u=~(~(b/B(b))),x=m*t,y=o*u,z=this.node.style,A=c+B(k-c)*x*(k>c==r?1:-1),C=d+B(l-d)*y*(l>d==s?1:-1),D=a*t>b*u?o:m;switch(this.type){case"rect":case"image":var E=i.width*m,F=i.height*o;this.attr({height:F,r:i.r*D,width:E,x:A-E/2,y:C-F/2});break;case"circle":case"ellipse":this.attr({rx:i.rx*m,ry:i.ry*o,r:i.r*D,cx:A,cy:C});break;case"text":this.attr({x:A,y:C});break;case"path":var G=bp(i.path),H=true,I=r?x:m,J=s?y:o;for(var K=0,L=G[w];K<L;K++){var M=G[K],N=V.call(M[0]);{if(N=="M"&&H)continue;H=false}if(N=="A"){M[G[K][w]-2]*=I;M[G[K][w]-1]*=J;M[1]*=m;M[2]*=o;M[5]=+(t+u?!(!(+M[5])):!(+M[5]))}else if(N=="H")for(var O=1,P=M[w];O<P;O++)M[O]*=I;else if(N=="V")for(O=1,P=M[w];O<P;O++)M[O]*=J;else for(O=1,P=M[w];O<P;O++)M[O]*=O%2?I:J}var Q=bn(G);e=A-Q.x-Q.width/2;f=C-Q.y-Q.height/2;G[0][1]+=e;G[0][2]+=f;this.attr({path:G});break}if(this.type in{text:1,image:1}&&(t!=1||u!=1))if(this.transformations){this.transformations[2]="scale("[n](t,",",u,")");this.node[R]("transform",this.transformations[v](q));e=t==-1?-i.x-(E||0):i.x;f=u==-1?-i.y-(F||0):i.y;this.attr({x:e,y:f});i.fx=t-1;i.fy=u-1}else{this.node.filterMatrix=U+".Matrix(M11="[n](t,", M12=0, M21=0, M22=",u,", Dx=0, Dy=0, sizingmethod='auto expand', filtertype='bilinear')");z.filter=(this.node.filterMatrix||p)+(this.node.filterOpacity||p)}else if(this.transformations){this.transformations[2]=p;this.node[R]("transform",this.transformations[v](q));i.fx=0;i.fy=0}else{this.node.filterMatrix=p;z.filter=(this.node.filterMatrix||p)+(this.node.filterOpacity||p)}i.scale=[a,b,c,d][v](q);this._.sx=a;this._.sy=b}return this};bO.clone=function(){if(this.removed)return null;var a=this.attr();delete a.scale;delete a.translation;return this.paper[this.type]().attr(a)};var cp={},cq=function(b,c,d,e,f,g,h,i,j){var k=0,l=100,m=[b,c,d,e,f,g,h,i].join(),n=cp[m],o,p;!n&&(cp[m]=n={data:[]});n.timer&&clearTimeout(n.timer);n.timer=setTimeout(function(){delete cp[m]},2000);if(j!=null){var q=cq(b,c,d,e,f,g,h,i);l=~(~q)*10}for(var r=0;r<l+1;r++){if(n.data[j]>r)p=n.data[r*l];else{p=a.findDotsAtSegment(b,c,d,e,f,g,h,i,r/l);n.data[r]=p}r&&(k+=C(C(o.x-p.x,2)+C(o.y-p.y,2),0.5));if(j!=null&&k>=j)return p;o=p}if(j==null)return k},cr=function(b,c){return function(d,e,f){d=bw(d);var g,h,i,j,k="",l={},m,n=0;for(var o=0,p=d.length;o<p;o++){i=d[o];if(i[0]=="M"){g=+i[1];h=+i[2]}else{j=cq(g,h,i[1],i[2],i[3],i[4],i[5],i[6]);if(n+j>e){if(c&&!l.start){m=cq(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n);k+=["C",m.start.x,m.start.y,m.m.x,m.m.y,m.x,m.y];if(f)return k;l.start=k;k=["M",m.x,m.y+"C",m.n.x,m.n.y,m.end.x,m.end.y,i[5],i[6]][v]();n+=j;g=+i[5];h=+i[6];continue}if(!b&&!c){m=cq(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n);return{x:m.x,y:m.y,alpha:m.alpha}}}n+=j;g=+i[5];h=+i[6]}k+=i}l.end=k;m=b?n:c?l:a.findDotsAtSegment(g,h,i[1],i[2],i[3],i[4],i[5],i[6],1);m.alpha&&(m={x:m.x,y:m.y,alpha:m.alpha});return m}},cs=cr(1),ct=cr(),cu=cr(0,1);bO.getTotalLength=function(){if(this.type!="path")return;if(this.node.getTotalLength)return this.node.getTotalLength();return cs(this.attrs.path)};bO.getPointAtLength=function(a){if(this.type!="path")return;return ct(this.attrs.path,a)};bO.getSubpath=function(a,b){if(this.type!="path")return;if(B(this.getTotalLength()-b)<"1e-6")return cu(this.attrs.path,a).end;var c=cu(this.attrs.path,b,1);return a?cu(c,a).end:c};a.easing_formulas={linear:function(a){return a},"<":function(a){return C(a,3)},">":function(a){return C(a-1,3)+1},"<>":function(a){a=a*2;if(a<1)return C(a,3)/2;a-=2;return(C(a,3)+2)/2},backIn:function(a){var b=1.70158;return a*a*((b+1)*a-b)},backOut:function(a){a=a-1;var b=1.70158;return a*a*((b+1)*a+b)+1},elastic:function(a){if(a==0||a==1)return a;var b=0.3,c=b/4;return C(2,-10*a)*y.sin((a-c)*(2*D)/b)+1},bounce:function(a){var b=7.5625,c=2.75,d;if(a<1/c)d=b*a*a;else if(a<2/c){a-=1.5/c;d=b*a*a+0.75}else if(a<2.5/c){a-=2.25/c;d=b*a*a+0.9375}else{a-=2.625/c;d=b*a*a+0.984375}return d}};var cv=[],cw=function(){var b=+(new Date);for(var c=0;c<cv[w];c++){var d=cv[c];if(d.stop||d.el.removed)continue;var e=b-d.start,g=d.ms,h=d.easing,i=d.from,j=d.diff,k=d.to,l=d.t,m=d.el,n={},o;if(e<g){var r=h(e/g);for(var s in i)if(i[f](s)){switch(X[s]){case"along":o=r*g*j[s];k.back&&(o=k.len-o);var t=ct(k[s],o);m.translate(j.sx-j.x||0,j.sy-j.y||0);j.x=t.x;j.y=t.y;m.translate(t.x-j.sx,t.y-j.sy);k.rot&&m.rotate(j.r+t.alpha,t.x,t.y);break;case E:o=+i[s]+r*g*j[s];break;case"colour":o="rgb("+[cy(Q(i[s].r+r*g*j[s].r)),cy(Q(i[s].g+r*g*j[s].g)),cy(Q(i[s].b+r*g*j[s].b))][v](",")+")";break;case"path":o=[];for(var u=0,x=i[s][w];u<x;u++){o[u]=[i[s][u][0]];for(var y=1,z=i[s][u][w];y<z;y++)o[u][y]=+i[s][u][y]+r*g*j[s][u][y];o[u]=o[u][v](q)}o=o[v](q);break;case"csv":switch(s){case"translation":var A=r*g*j[s][0]-l.x,B=r*g*j[s][1]-l.y;l.x+=A;l.y+=B;o=A+q+B;break;case"rotation":o=+i[s][0]+r*g*j[s][0];i[s][1]&&(o+=","+i[s][1]+","+i[s][2]);break;case"scale":o=[+i[s][0]+r*g*j[s][0],+i[s][1]+r*g*j[s][1],2 in k[s]?k[s][2]:p,3 in k[s]?k[s][3]:p][v](q);break;case"clip-rect":o=[];u=4;while(u--)o[u]=+i[s][u]+r*g*j[s][u];break}break;default:var C=[].concat(i[s]);o=[];u=m.paper.customAttributes[s].length;while(u--)o[u]=+C[u]+r*g*j[s][u];break}n[s]=o}m.attr(n);m._run&&m._run.call(m)}else{if(k.along){t=ct(k.along,k.len*!k.back);m.translate(j.sx-(j.x||0)+t.x-j.sx,j.sy-(j.y||0)+t.y-j.sy);k.rot&&m.rotate(j.r+t.alpha,t.x,t.y)}(l.x||l.y)&&m.translate(-l.x,-l.y);k.scale&&(k.scale+=p);m.attr(k);cv.splice(c--,1)}}a.svg&&m&&m.paper&&m.paper.safari();cv[w]&&setTimeout(cw)},cx=function(b,c,d,e,f){var g=d-e;c.timeouts.push(setTimeout(function(){a.is(f,"function")&&f.call(c);c.animate(b,g,b.easing)},e))},cy=function(a){return z(A(a,255),0)},cz=function(a,b){if(a==null)return{x:this._.tx,y:this._.ty,toString:co};this._.tx+=+a;this._.ty+=+b;switch(this.type){case"circle":case"ellipse":this.attr({cx:+a+this.attrs.cx,cy:+b+this.attrs.cy});break;case"rect":case"image":case"text":this.attr({x:+a+this.attrs.x,y:+b+this.attrs.y});break;case"path":var c=bp(this.attrs.path);c[0][1]+=+a;c[0][2]+=+b;this.attr({path:c});break}return this};bO.animateWith=function(a,b,c,d,e){for(var f=0,g=cv.length;f<g;f++)cv[f].el.id==a.id&&(b.start=cv[f].start);return this.animate(b,c,d,e)};bO.animateAlong=cA();bO.animateAlongBack=cA(1);function cA(b){return function(c,d,e,f){var g={back:b};a.is(e,"function")?f=e:g.rot=e;c&&c.constructor==bN&&(c=c.attrs.path);c&&(g.along=c);return this.animate(g,d,f)}}function cB(a,b,c,d,e,f){var g=3*b,h=3*(d-b)-g,i=1-g-h,j=3*c,k=3*(e-c)-j,l=1-j-k;function m(a){return((i*a+h)*a+g)*a}function n(a,b){var c=o(a,b);return((l*c+k)*c+j)*c}function o(a,b){var c,d,e,f,j,k;for(e=a,k=0;k<8;k++){f=m(e)-a;if(B(f)<b)return e;j=(3*i*e+2*h)*e+g;if(B(j)<0.000001)break;e=e-f/j}c=0;d=1;e=a;if(e<c)return c;if(e>d)return d;while(c<d){f=m(e);if(B(f-a)<b)return e;a>f?c=e:d=e;e=(d-c)/2+c}return e}return n(a,1/(200*f))}bO.onAnimation=function(a){this._run=a||0;return this};bO.animate=function(c,d,e,g){var h=this;h.timeouts=h.timeouts||[];if(a.is(e,"function")||!e)g=e||null;if(h.removed){g&&g.call(h);return h}var i={},j={},k=false,l={};for(var m in c)if(c[f](m)){if(X[f](m)||h.paper.customAttributes[f](m)){k=true;i[m]=h.attr(m);i[m]==null&&(i[m]=W[m]);j[m]=c[m];switch(X[m]){case"along":var n=cs(c[m]),o=ct(c[m],n*!(!c.back)),p=h.getBBox();l[m]=n/d;l.tx=p.x;l.ty=p.y;l.sx=o.x;l.sy=o.y;j.rot=c.rot;j.back=c.back;j.len=n;c.rot&&(l.r=S(h.rotate())||0);break;case E:l[m]=(j[m]-i[m])/d;break;case"colour":i[m]=a.getRGB(i[m]);var q=a.getRGB(j[m]);l[m]={r:(q.r-i[m].r)/d,g:(q.g-i[m].g)/d,b:(q.b-i[m].b)/d};break;case"path":var t=bw(i[m],j[m]);i[m]=t[0];var u=t[1];l[m]=[];for(var v=0,x=i[m][w];v<x;v++){l[m][v]=[0];for(var y=1,z=i[m][v][w];y<z;y++)l[m][v][y]=(u[v][y]-i[m][v][y])/d}break;case"csv":var A=r(c[m])[s](b),B=r(i[m])[s](b);switch(m){case"translation":i[m]=[0,0];l[m]=[A[0]/d,A[1]/d];break;case"rotation":i[m]=B[1]==A[1]&&B[2]==A[2]?B:[0,A[1],A[2]];l[m]=[(A[0]-i[m][0])/d,0,0];break;case"scale":c[m]=A;i[m]=r(i[m])[s](b);l[m]=[(A[0]-i[m][0])/d,(A[1]-i[m][1])/d,0,0];break;case"clip-rect":i[m]=r(i[m])[s](b);l[m]=[];v=4;while(v--)l[m][v]=(A[v]-i[m][v])/d;break}j[m]=A;break;default:A=[].concat(c[m]);B=[].concat(i[m]);l[m]=[];v=h.paper.customAttributes[m][w];while(v--)l[m][v]=((A[v]||0)-(B[v]||0))/d;break}}}if(k){var G=a.easing_formulas[e];if(!G){G=r(e).match(P);if(G&&G[w]==5){var H=G;G=function(a){return cB(a,+H[1],+H[2],+H[3],+H[4],d)}}else G=function(a){return a}}cv.push({start:c.start||+(new Date),ms:d,easing:G,from:i,diff:l,to:j,el:h,t:{x:0,y:0}});a.is(g,"function")&&(h._ac=setTimeout(function(){g.call(h)},d));cv[w]==1&&setTimeout(cw)}else{var C=[],D;for(var F in c)if(c[f](F)&&Z.test(F)){m={value:c[F]};F=="from"&&(F=0);F=="to"&&(F=100);m.key=T(F,10);C.push(m)}C.sort(be);C[0].key&&C.unshift({key:0,value:h.attrs});for(v=0,x=C[w];v<x;v++)cx(C[v].value,h,d/100*C[v].key,d/100*(C[v-1]&&C[v-1].key||0),C[v-1]&&C[v-1].value.callback);D=C[C[w]-1].value.callback;D&&h.timeouts.push(setTimeout(function(){D.call(h)},d))}return this};bO.stop=function(){for(var a=0;a<cv.length;a++)cv[a].el.id==this.id&&cv.splice(a--,1);for(a=0,ii=this.timeouts&&this.timeouts.length;a<ii;a++)clearTimeout(this.timeouts[a]);this.timeouts=[];clearTimeout(this._ac);delete this._ac;return this};bO.translate=function(a,b){return this.attr({translation:a+" "+b})};bO[H]=function(){return"Raphaël’s object"};a.ae=cv;var cC=function(a){this.items=[];this[w]=0;this.type="set";if(a)for(var b=0,c=a[w];b<c;b++){if(a[b]&&(a[b].constructor==bN||a[b].constructor==cC)){this[this.items[w]]=this.items[this.items[w]]=a[b];this[w]++}}};cC[e][L]=function(){var a,b;for(var c=0,d=arguments[w];c<d;c++){a=arguments[c];if(a&&(a.constructor==bN||a.constructor==cC)){b=this.items[w];this[b]=this.items[b]=a;this[w]++}}return this};cC[e].pop=function(){delete this[this[w]--];return this.items.pop()};for(var cD in bO)bO[f](cD)&&(cC[e][cD]=(function(a){return function(){for(var b=0,c=this.items[w];b<c;b++)this.items[b][a][m](this.items[b],arguments);return this}})(cD));cC[e].attr=function(b,c){if(b&&a.is(b,G)&&a.is(b[0],"object"))for(var d=0,e=b[w];d<e;d++)this.items[d].attr(b[d]);else for(var f=0,g=this.items[w];f<g;f++)this.items[f].attr(b,c);return this};cC[e].animate=function(b,c,d,e){(a.is(d,"function")||!d)&&(e=d||null);var f=this.items[w],g=f,h,i=this,j;e&&(j=function(){!(--f)&&e.call(i)});d=a.is(d,F)?d:j;h=this.items[--g].animate(b,c,d,j);while(g--)this.items[g]&&!this.items[g].removed&&this.items[g].animateWith(h,b,c,d,j);return this};cC[e].insertAfter=function(a){var b=this.items[w];while(b--)this.items[b].insertAfter(a);return this};cC[e].getBBox=function(){var a=[],b=[],c=[],d=[];for(var e=this.items[w];e--;){var f=this.items[e].getBBox();a[L](f.x);b[L](f.y);c[L](f.x+f.width);d[L](f.y+f.height)}a=A[m](0,a);b=A[m](0,b);return{x:a,y:b,width:z[m](0,c)-a,height:z[m](0,d)-b}};cC[e].clone=function(a){a=new cC;for(var b=0,c=this.items[w];b<c;b++)a[L](this.items[b].clone());return a};a.registerFont=function(a){if(!a.face)return a;this.fonts=this.fonts||{};var b={w:a.w,face:{},glyphs:{}},c=a.face["font-family"];for(var d in a.face)a.face[f](d)&&(b.face[d]=a.face[d]);this.fonts[c]?this.fonts[c][L](b):this.fonts[c]=[b];if(!a.svg){b.face["units-per-em"]=T(a.face["units-per-em"],10);for(var e in a.glyphs)if(a.glyphs[f](e)){var g=a.glyphs[e];b.glyphs[e]={w:g.w,k:{},d:g.d&&"M"+g.d[Y](/[mlcxtrv]/g,function(a){return({l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"})[a]||"M"})+"z"};if(g.k)for(var h in g.k)g[f](h)&&(b.glyphs[e].k[h]=g.k[h])}}return a};k.getFont=function(b,c,d,e){e=e||"normal";d=d||"normal";c=+c||({normal:400,bold:700,lighter:300,bolder:800})[c]||400;if(!a.fonts)return;var g=a.fonts[b];if(!g){var h=new RegExp("(^|\\s)"+b[Y](/[^\w\d\s+!~.:_-]/g,p)+"(\\s|$)","i");for(var i in a.fonts)if(a.fonts[f](i)){if(h.test(i)){g=a.fonts[i];break}}}var j;if(g)for(var k=0,l=g[w];k<l;k++){j=g[k];if(j.face["font-weight"]==c&&(j.face["font-style"]==d||!j.face["font-style"])&&j.face["font-stretch"]==e)break}return j};k.print=function(c,d,e,f,g,h,i){h=h||"middle";i=z(A(i||0,1),-1);var j=this.set(),k=r(e)[s](p),l=0,m=p,n;a.is(f,e)&&(f=this.getFont(f));if(f){n=(g||16)/f.face["units-per-em"];var o=f.face.bbox.split(b),q=+o[0],t=+o[1]+(h=="baseline"?o[3]-o[1]+ +f.face.descent:(o[3]-o[1])/2);for(var u=0,v=k[w];u<v;u++){var x=u&&f.glyphs[k[u-1]]||{},y=f.glyphs[k[u]];l+=u?(x.w||f.w)+(x.k&&x.k[k[u]]||0)+f.w*i:0;y&&y.d&&j[L](this.path(y.d).attr({fill:"#000",stroke:"none",translation:[l,0]}))}j.scale(n,n,q,t).translate(c-q,d-t)}return j};a.format=function(b,c){var e=a.is(c,G)?[0][n](c):arguments;b&&a.is(b,F)&&e[w]-1&&(b=b[Y](d,function(a,b){return e[++b]==null?p:e[b]}));return b||p};a.ninja=function(){i.was?h.Raphael=i.is:delete Raphael;return a};a.el=bO;a.st=cC[e];i.was?h.Raphael=a:Raphael=a})();
exports = Raphael;;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\lib\sound.js
*/
define("scripts/lib/sound.js", function(exports){
/**
* 简易声效控制
*/
/**
* 使用方法:
*
* var sound = require("scripts/lib/sound/main");
*
* var snd = sound.create("sounds/myfile");
* snd.play();
*/
var buzz = require("scripts/lib/buzz");
function ClassBuzz( src ){
this.sound = new buzz.sound( src, { formats: [ "ogg", "mp3" ], preload: true, autoload: true, loop: false });
}
ClassBuzz.prototype.play = function(){
this.sound.setPercent( 0 );
this.sound.setVolume( 100 );
this.sound.play();
};
ClassBuzz.prototype.stop = function(){
this.sound.fadeOut( 1e3, function(){
this.pause();
} );
};
exports.create = function( src ){
return new ClassBuzz( src );
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\lib\tween.js
*/
define("scripts/lib/tween.js", function(exports){
exports.exponential = function(){};
exports.exponential.co = function(index, offset, target, framesNum){ return (index == framesNum) ? offset + target : target * (-Math.pow(2, -10 * index / framesNum) + 1) + offset; };
// exports.exponential.ci = function(index, offset, target, framesNum){ return (index == 0) ? offset : target * Math.pow(2, 10 * (index / framesNum - 1)) + offset; }
exports.bounce = function(){};
exports.bounce.co = function(index, offset, target, framesNum){ if((index /= framesNum) < (1 / 2.75)) return target * (7.5625 * index * index) + offset; else if(index < (2 / 2.75)) return target * (7.5625 * (index -= (1.5 / 2.75)) * index + .75) + offset; else if(index < (2.5 / 2.75)) return target * (7.5625 * (index -= (2.25 / 2.75)) * index + .9375) + offset; else return target * (7.5625 * (index -= (2.625 / 2.75)) * index + .984375) + offset; };
exports.quadratic = function(){};
exports.quadratic.ci = function(index, offset, target, framesNum){ return target * (index /= framesNum) * index + offset; };
exports.quadratic.co = function(index, offset, target, framesNum){ return - target * (index /= framesNum) * (index - 2) + offset; }
exports.quadratic.cio = function(index, offset, target, framesNum){ if((index /= framesNum / 2) < 1) return target / 2 * index * index + offset; else return - target / 2 * ((-- index) * (index - 2) - 1) + offset; };
exports.circular = function(index, offset, target, framesNum){ if((index /= framesNum / 2) < 1) return - target / 2 * (Math.sqrt(1 - index * index) - 1) + offset; else return target / 2 * (Math.sqrt(1 - (index -= 2) * index) + 1) + offset; }
exports.linear = function(index, offset, target, framesNum){ return target * index / framesNum + offset; };
exports.back = function(){};
exports.back.ci = function(index, offset, target, framesNum, s){ s = 1.70158; return target * (index /= framesNum) * index * ((s + 1) * index - s) + offset; };
exports.back.co = function(index, offset, target, framesNum, s){ s = 1.70158; return target * ((index = index / framesNum - 1) * index * ((s + 1) * index + s) + 1) + offset; };;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\lib\ucren.js
*/
define("scripts/lib/ucren.js", function(exports){
/**
* ucren-lite
* filename: boot.js
* author: dron
* version: 5.0.2.20120628
* date: 2009-03-15
* contact: ucren.com
*/
var Ucren;
var blankArray = [];
var slice = blankArray.slice;
var join = blankArray.join;
//
// [基本数据类型扩展]
//
// String.prototype.trim
if(!String.prototype.trim)
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/, "");
};
// String.prototype.format
String.prototype.format = function(conf){
var rtn = this, blank = {};
Ucren.each(conf, function(item, key){
item = item.toString().replace(/\$/g, "$$$$");
rtn = rtn.replace(RegExp("@{" + key + "}", "g"), item);
});
return rtn.toString();
};
// String.prototype.htmlEncode
String.prototype.htmlEncode = function(){
var div = document.createElement("div");
return function(){
var text;
div.appendChild(document.createTextNode(this));
text = div.innerHTML;
div.innerHTML = "";
return text;
};
}();
// String.prototype.byteLength
String.prototype.byteLength = function(){
return this.replace(/[^\x00-\xff]/g, " ").length;
};
// String.prototype.subByte
String.prototype.subByte = function(len, tail){
var s = this;
if(s.byteLength() <= len)
return s;
tail = tail || "";
len -= tail.byteLength();
return s = s.slice(0, len).replace(/([^\x00-\xff])/g, "$1 ")
.slice(0, len)
.replace(/[^\x00-\xff]$/, "")
.replace(/([^\x00-\xff]) /g, "$1") + tail;
}
// Function.prototype.defer
Function.prototype.defer = function(scope, timeout){
var me = this;
var fn = function(){
me.apply(scope, arguments);
};
return setTimeout(fn, timeout);
};
// Function.prototype.bind
if(!Function.prototype.bind)
Function.prototype.bind = function(scope){
var me = this;
return function(){
return me.apply(scope, arguments);
}
};
// Function.prototype.saturate
Function.prototype.saturate = function(scope/*, args */){
var fn = this, afters = slice.call( arguments, 1 );
return function(){
return fn.apply( scope, slice.call( arguments, 0 ).concat( afters ) );
}
};
// Array.prototype.indexOf
// if(!Array.prototype.indexOf)
Array.prototype.indexOf = function( item, i ){
var length = this.length;
if( !i )
i = 0;
if( i < 0 )
i = length + i;
for(; i < length; i ++)
if( this[i] === item )
return i;
return -1;
};
// Array.prototype.every
// if(!Array.prototype.every)
Array.prototype.every = function( fn, context ) {
for (var i = 0, len = this.length; i < len; i ++)
if ( !fn.call(context, this[i], i, this) )
return false;
return true;
};
// Array.prototype.filter
// if(!Array.prototype.filter)
Array.prototype.filter = function( fn, context ) {
var result = [], val;
for (var i = 0, len = this.length; i < len; i ++)
if (val = this[i], fn.call( context, val, i, this ))
result.push(val);
return result;
};
// Array.prototype.forEach
// if(!Array.prototype.forEach)
Array.prototype.forEach = function( fn, context ) {
for (var i = 0, len = this.length; i < len; i ++)
fn.call(context, this[i], i, this);
};
// Array.prototype.map
// if(!Array.prototype.map)
Array.prototype.map = function( fn, context ) {
var result = [];
for (var i = 0, len = this.length; i < len; i ++)
result[i] = fn.call(context, this[i], i, this);
return result;
};
// Array.prototype.some
// if(!Array.prototype.some)
Array.prototype.some = function( fn, context ) {
for (var i = 0, len = this.length; i < len; i ++)
if ( fn.call( context, this[i], i, this ) )
return true;
return false;
};
Array.prototype.invoke = function( method /*, args */ ){
var args = slice.call( arguments, 1 );
this.forEach(function( item ){
if(item instanceof Array)
item[0][method].apply( item[0], item.slice(1) );
else
item[method].apply( item, args );
});
return this;
};
Array.prototype.random = function(){
var arr = this.slice( 0 ), ret = [], i = arr.length;
while( i -- )
ret.push( arr.splice( Ucren.randomNumber( i + 1 ), 1 )[0] );
return ret;
};
Ucren = {
//
// [全局属性]
//
// Ucren.isIe
isIe: /msie/i.test(navigator.userAgent),
// Ucren.isIe6
isIe6: /msie 6/i.test(navigator.userAgent),
// Ucren.isFirefox
isFirefox: /firefox/i.test(navigator.userAgent),
// Ucren.isSafari
isSafari: /version\/[\d\.]+\s+safari/i.test(navigator.userAgent),
// Ucren.isOpera
isOpera: /opera/i.test(navigator.userAgent),
// Ucren.isChrome
isChrome: /chrome/i.test(navigator.userAgent), //todo isChrome = true, isSafari = true
// Ucren.isStrict
isStrict: document.compatMode == "CSS1Compat",
// Ucren.tempDom
tempDom: document.createElement("div"),
//
// [全局方法]
//
// Ucren.apply
apply: function(form, to, except){
if(!to)to = {};
if(except){
Ucren.each(form, function(item, key){
if(key in except)
return ;
to[key] = item;
});
}else{
Ucren.each(form, function(item, key){
to[key] = item;
});
}
return to;
},
// Ucren.appendStyle
appendStyle: function(text){
var style;
if(arguments.length > 1)
text = join.call(arguments, "");
if(document.createStyleSheet){
style = document.createStyleSheet();
style.cssText = text;
}else{
style = document.createElement("style");
style.type = "text/css";
//style.innerHTML = text; fix Chrome bug
style.appendChild(document.createTextNode(text));
document.getElementsByTagName("head")[0].appendChild(style);
}
},
// for copy :)
//
// var addEvent = function(target, name, fn){
// var call = function(){
// fn.apply(target, arguments);
// };
// if(window.attachEvent)
// target.attachEvent("on" + name, call);
// else if(window.addEventListener)
// target.addEventListener(name, call, false);
// else
// target["on" + name] = call;
// return call;
// }
// Ucren.addEvent
addEvent: function(target, name, fn){
var call = function(){
fn.apply(target, arguments);
};
if(target.dom){
target = target.dom;
}
if(window.attachEvent){
target.attachEvent("on" + name, call);
}else if(window.addEventListener){
target.addEventListener(name, call, false);
}else{
target["on" + name] = call;
}
return call;
},
// Ucren.delEvent
delEvent: function(target, name, fn){
if(window.detachEvent){
target.detachEvent("on" + name, fn);
}else if(window.removeEventListener){
target.removeEventListener(name, fn, false);
}else if(target["on" + name] == fn){
target["on" + name] = null;
}
},
// Ucren.Class
Class: function(initialize, methods, befores, afters){
var fn, prototype, blank;
initialize = initialize || function(){};
methods = methods || {};
blank = {};
fn = function(){
this.instanceId = Ucren.id();
initialize.apply(this, arguments);
};
prototype = fn.prototype;
Ucren.registerClassEvent.call(prototype);
Ucren.each(methods, function(item, key){
prototype[key] = function(method, name){
if(typeof(method) == "function"){
return function(){
var args, rtn;
args = slice.call(arguments, 0);
if(befores &&
befores.apply(this, [name].concat(args)) === false){
return ;
}
this.fireEvent("before" + name, args);
rtn = method.apply(this, args);
if(afters)
afters.apply(this, [name].concat(args));
this.fireEvent(name, args);
return rtn;
};
}else{
return method;
}
}(item, key);
});
prototype.getOriginMethod = function(name){
return methods[name];
};
return fn;
},
//private
registerClassEvent: function(){
this.on = function(name, fn){
var instanceId = this.instanceId;
Ucren.dispatch(instanceId + name, fn.bind(this));
};
this.onbefore = function(name, fn){
var instanceId = this.instanceId;
Ucren.dispatch(instanceId + "before" + name, fn.bind(this));
};
this.un = function(name, fn){
//todo
};
this.fireEvent = function(name, args){
var instanceId = this.instanceId;
Ucren.dispatch(instanceId + name, args);
};
},
// Ucren.createFuze
createFuze: function(){
var queue, fn, infire;
queue = [];
fn = function(process){
if(infire){
process();
}else{
queue.push(process);
}
};
fn.fire = function(){
while(queue.length){
queue.shift()();
}
infire = true;
};
fn.extinguish = function(){
infire = false;
};
fn.wettish = function(){
if(queue.length){
queue.shift()();
}
};
return fn;
},
// Ucren.createIf
// createIf: function(expressionFunction){
// return function(callback){
// var expression = expressionFunction();
// var returnValue = {
// Else: function(callback){
// callback = callback || nul;
// expression || callback();
// }
// };
// callback = callback || nul;
// expression && callback();
// return returnValue;
// };
// },
// Ucren.dispatch
dispatch: function(){
var map = {}, send, incept;
send = function( processId, args, scope ){
var processItems;
if( processItems = map[processId] )
Ucren.each(processItems, function(item){
item.apply( scope, args );
});
};
incept = function( processId, fn ){
if( !map[processId] )
map[processId] = [];
map[processId].push( fn );
};
return function(arg1, arg2, arg3){
if( typeof(arg2) === "undefined" )
arg2 = [];
if( arg2 instanceof Array )
send.apply(this, arguments);
else if( typeof(arg2) === "function" )
incept.apply(this, arguments);
}
}(),
// Ucren.each (not recommended)
each: function(unknown, fn){
/// unknown 是 array 的,会慢慢退化,建议用 Array.prototype.forEach 替代
/// unknown 为其它类似的,短期内将暂时支持
if(unknown instanceof Array || (typeof unknown == "object" &&
typeof unknown[0] != "undefined" && unknown.length)){
if(typeof unknown == "object" && Ucren.isSafari)
unknown = slice.call(unknown);
// for(var i = 0, l = unknown.length; i < l; i ++){
// if(fn(unknown[i], i) === false){
// break;
// }
// }
unknown.forEach(fn);
}else if(typeof(unknown) == "object"){
var blank = {};
for(var i in unknown){
if(blank[i]){
continue;
}
if(fn(unknown[i], i) === false){
break;
}
}
}else if(typeof(unknown) == "number"){
for(var i = 0; i < unknown; i ++){
if(fn(i, i) === false){
break;
}
}
}else if(typeof(unknown) == "string"){
for(var i = 0, l = unknown.length; i < l; i ++){
if(fn(unknown.charAt(i), i) === false){
break;
}
}
}
},
// Ucren.Element
Element: function(el, returnDom){
var rtn, handleId;
if(el && el.isUcrenElement){
return returnDom ? el.dom : el;
}
el = typeof(el) == "string" ? document.getElementById(el) : el;
if(!el)
return null;
if(returnDom)
return el;
handleId = el.getAttribute("handleId");
if(typeof handleId == "string"){
return Ucren.handle(handleId - 0);
}else{
rtn = new Ucren.BasicElement(el);
handleId = Ucren.handle(rtn);
el.setAttribute("handleId", handleId + "");
return rtn;
}
},
// Ucren.Event
Event: function(e){
e = e || window.event;
if(!e){
var c = arguments.callee.caller;
while(c){
e = c.arguments[0];
if(e && typeof(e.altKey) == "boolean"){ // duck typing
break;
}
c = c.caller;
e = null;
}
}
return e;
},
// Ucren.fixNumber
fixNumber: function(unknown, defaultValue){
return typeof(unknown) == "number" ? unknown : defaultValue;
},
// Ucren.fixString
fixString: function(unknown, defaultValue){
return typeof(unknown) == "string" ? unknown : defaultValue;
},
// Ucren.fixConfig
fixConfig: function(conf){
var defaultConf;
defaultConf = {};
if(typeof conf == "undefined"){
return defaultConf;
}else if(typeof conf == "function"){
return new conf;
}else{
return conf;
}
},
// Ucren.handle
handle: function(unknown){
var fn, type, number;
fn = arguments.callee;
if(!fn.cache){
fn.cache = {};
}
if(typeof(fn.number) == "undefined"){
fn.number = 0;
}
type = typeof(unknown);
if(type == "number"){
return fn.cache[unknown.toString()];
}else if(type == "object" || type == "function"){
number = fn.number ++;
fn.cache[number.toString()] = unknown;
return number;
}
},
// Ucren.id
id: function(){
var id = arguments.callee;
id.number = ++ id.number || 0;
return "_" + id.number;
},
// Ucren.loadImage
loadImage: function(urls, onLoadComplete){
var length = urls.length;
var loaded = 0;
var check = function(){
if(loaded == length)
onLoadComplete && onLoadComplete();
};
Ucren.each(urls, function(url){
var img = document.createElement("img");
img.onload = img.onerror = function(){
this.onload = this.onerror = null;
loaded ++;
check();
};
Ucren.tempDom.appendChild(img);
img.src = url;
});
},
// Ucren.loadScript
loadScript: function(src, callback){
Ucren.request(src, function(text){
eval(text);
callback && callback(text);
});
},
// Ucren.makeElement
makeElement: function(tagName, attributes){
var el = document.createElement(tagName);
var setStyle = function(unknown){
if(typeof unknown == "string")
el.style.cssText = unknown;
else
Ucren.apply(unknown, el.style);
};
for (var prop in attributes) {
if (prop === "class")
el.className = attributes[prop];
else if (prop === "for")
el.htmlFor = attributes[prop];
else if(prop === "style")
setStyle(attributes[prop]);
else
el.setAttribute(prop, attributes[prop]);
}
return el;
},
// Ucren.nul
nul: function(){
return false;
},
// Ucren.queryString
// queryString: function(name, sourceString){
// var source, pattern, result;
// source = sourceString || location.href;
// pattern = new RegExp("(\\?|&)" + name + "=([^&#]*)(#|&|$)", "i");
// result = source.match(pattern);
// return result ? result[2] : "";
// },
// Ucren.randomNumber
randomNumber: function(num){
return Math.floor(Math.random() * num);
},
// Ucren.randomWord
randomWord: function(){
var cw = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return function(length, sourceString){
var words, re = [];
words = sourceString || cw;
Ucren.each(length, function(index){
re[index] = words.charAt(this.randomNumber(words.length));
}.bind(this));
return re.join("");
}
}(),
// Ucren.request
request: function(url, callback){
request = Ucren.request;
var xhr = request.xhr;
if(!request.xhr){
if(window.XMLHttpRequest){
xhr = request.xhr = new XMLHttpRequest();
}else{
xhr = request.xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xhr.open("GET", url, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
callback(xhr.responseText);
}
};
xhr.send(null);
}
// // Ucren.decodeColor
// decodeColor: function(){
// var r = /^\#?(\w{2})(\w{2})(\w{2})$/;
// var x = function(x){
// return parseInt(x, 16);
// };
// return function(color){
// r.test(color);
// return {
// red: x(RegExp.$1),
// green: x(RegExp.$2),
// blue: x(RegExp.$3)
// };
// }
// }(),
// // Ucren.encodeColor
// encodeColor: function(){
// var x = function(x){
// return x.toString(16).split(".")[0];
// };
// x = x.improve(function(origin, x){
// x = origin(x);
// return x.length == 1 ? "0" + x : x;
// });
// return function(data){
// return ["#", x(data.red), x(data.green), x(data.blue)].join("");
// }
// }()
};
//
// [底层操作类]
//
// Ucren.BasicDrag
Ucren.BasicDrag = Ucren.Class(
/* constructor */ function(conf){
conf = Ucren.fixConfig(conf);
this.type = Ucren.fixString(conf.type, "normal");
var isTouch = this.isTouch = "ontouchstart" in window;
this.TOUCH_START = isTouch ? "touchstart" : "mousedown",
this.TOUCH_MOVE = isTouch ? "touchmove" : "mousemove",
this.TOUCH_END = isTouch ? "touchend" : "mouseup";
},
/* methods */ {
bind: function(el, handle){
el = Ucren.Element(el);
handle = Ucren.Element(handle) || el;
var evt = {};
evt[this.TOUCH_START] = function(e){
e = Ucren.Event(e);
this.startDrag();
e.cancelBubble = true;
e.stopPropagation && e.stopPropagation();
return e.returnValue = false;
}.bind(this);
handle.addEvents(evt);
this.target = el;
},
//private
getCoors: function(e){
var coors = [];
if (e.targetTouches && e.targetTouches.length) { // iPhone
var thisTouch = e.targetTouches[0];
coors[0] = thisTouch.clientX;
coors[1] = thisTouch.clientY;
}else{ // all others
coors[0] = e.clientX;
coors[1] = e.clientY;
}
return coors;
},
//private
startDrag: function(){
var target, draging, e;
target = this.target;
draging = target.draging = {};
this.isDraging = true;
draging.x = parseInt(target.style("left"), 10) || 0;
draging.y = parseInt(target.style("top"), 10) || 0;
e = Ucren.Event();
var coors = this.getCoors(e);
draging.mouseX = coors[0];
draging.mouseY = coors[1];
this.registerDocumentEvent();
},
//private
endDrag: function(){
this.isDraging = false;
this.unRegisterDocumentEvent();
},
//private
registerDocumentEvent: function(){
var target, draging;
target = this.target;
draging = target.draging;
draging.documentSelectStart =
Ucren.addEvent(document, "selectstart", function(e){
e = e || event;
e.stopPropagation && e.stopPropagation();
e.cancelBubble = true;
return e.returnValue = false;
});
draging.documentMouseMove =
Ucren.addEvent(document, this.TOUCH_MOVE, function(e){
var ie, nie;
e = e || event;
ie = Ucren.isIe && e.button != 1;
nie = !Ucren.isIe && e.button != 0;
if((ie || nie) && !this.isTouch)
this.endDrag();
var coors = this.getCoors(e);
draging.newMouseX = coors[0];
draging.newMouseY = coors[1];
e.stopPropagation && e.stopPropagation();
return e.returnValue = false;
}.bind(this));
draging.documentMouseUp =
Ucren.addEvent(document, this.TOUCH_END, function(){
this.endDrag();
}.bind(this));
clearInterval(draging.timer);
draging.timer = setInterval(function(){
var x, y, dx, dy;
if(draging.newMouseX){
dx = draging.newMouseX - draging.mouseX;
dy = draging.newMouseY - draging.mouseY;
x = draging.x + dx;
y = draging.y + dy;
if(this.type == "calc"){
this.returnValue(dx, dy, draging.newMouseX, draging.newMouseY);
}else{
target.left(x).top(y);
}
}
}.bind(this), 10);
},
//private
unRegisterDocumentEvent: function(){
var draging = this.target.draging;
Ucren.delEvent(document, this.TOUCH_MOVE, draging.documentMouseMove);
Ucren.delEvent(document, this.TOUCH_END, draging.documentMouseUp);
Ucren.delEvent(document, "selectstart", draging.documentSelectStart);
clearInterval(draging.timer);
},
//private
returnValue: function(dx, dy, x, y){
//todo something
}
}
);
// Ucren.Template
Ucren.Template = Ucren.Class(
/* constructor */ function(){
this.string = join.call(arguments, "");
},
/* methods */ {
apply: function(conf){
return this.string.format(conf);
}
}
);
// Ucren.BasicElement
Ucren.BasicElement = Ucren.Class(
/* constructor */ function(el){
this.dom = el;
this.countMapping = {};
},
/* methods */ {
isUcrenElement: true,
attr: function(name, value){
if(typeof value == "string"){
this.dom.setAttribute(name, value);
}else{
return this.dom.getAttribute(name);
}
return this;
},
style: function(/* unknown1, unknown2 */){
var getStyle = Ucren.isIe ?
function(name){
return this.dom.currentStyle[name];
} :
function(name){
var style;
style = document.defaultView.getComputedStyle(this.dom, null);
return style.getPropertyValue(name);
};
return function(unknown1, unknown2){
if(typeof unknown1 == "object"){
Ucren.each(unknown1, function(value, key){
this[key] = value;
}.bind(this.dom.style));
}else if(typeof unknown1 == "string" && typeof unknown2 == "undefined"){
return getStyle.call(this, unknown1);
}else if(typeof unknown1 == "string" && typeof unknown2 != "undefined"){
this.dom.style[unknown1] = unknown2;
}
return this;
};
}(),
hasClass: function(name){
var className = " " + this.dom.className + " ";
return className.indexOf(" " + name + " ") > -1;
},
setClass: function(name){
if(typeof(name) == "string")
this.dom.className = name.trim();
return this;
},
addClass: function(name){
var el, className;
el = this.dom;
className = " " + el.className + " ";
if(className.indexOf(" " + name + " ") == -1){
className += name;
className = className.trim();
className = className.replace(/ +/g, " ");
el.className = className;
}
return this;
},
delClass: function(name){
var el, className;
el = this.dom;
className = " " + el.className + " ";
if(className.indexOf(" " + name + " ") > -1){
className = className.replace(" " + name + " ", " ");
className = className.trim();
className = className.replace(/ +/g, " ");
el.className = className;
}
return this;
},
html: function(html){
var el = this.dom;
if(typeof html == "string"){
el.innerHTML = html;
}else if(html instanceof Array){
el.innerHTML = html.join("");
}else{
return el.innerHTML;
}
return this;
},
left: function(number){
var el = this.dom;
if(typeof(number) == "number"){
el.style.left = number + "px";
this.fireEvent("infect", [{ left: number }]);
}else{
return this.getPos().x;
}
return this;
},
top: function(number){
var el = this.dom;
if(typeof(number) == "number"){
el.style.top = number + "px";
this.fireEvent("infect", [{ top: number }]);
}else{
return this.getPos().y;
}
return this;
},
width: function(unknown){
var el = this.dom;
if(typeof unknown == "number"){
el.style.width = unknown + "px";
this.fireEvent("infect", [{ width: unknown }]);
}else if(typeof unknown == "string"){
el.style.width = unknown;
this.fireEvent("infect", [{ width: unknown }]);
}else{
return this.getSize().width;
}
return this;
},
height: function(unknown){
var el = this.dom;
if(typeof unknown == "number"){
el.style.height = unknown + "px";
this.fireEvent("infect", [{ height: unknown }]);
}else if(typeof unknown == "string"){
el.style.height = unknown;
this.fireEvent("infect", [{ height: unknown }]);
}else{
return this.getSize().height;
}
return this;
},
count: function(name){
return this.countMapping[name] = ++ this.countMapping[name] || 1;
},
display: function(bool){
var dom = this.dom;
if(typeof(bool) == "boolean"){
dom.style.display = bool ? "block" : "none";
this.fireEvent("infect", [{ display: bool }]);
}else{
return this.style("display") != "none";
}
return this;
},
first: function(){
var c = this.dom.firstChild;
while(c && !c.tagName && c.nextSibling){
c = c.nextSibling;
}
return c;
},
add: function(dom){
var el;
el = Ucren.Element(dom);
this.dom.appendChild(el.dom);
return this;
},
remove: function(dom){
var el;
if(dom){
el = Ucren.Element(dom);
el.html("");
this.dom.removeChild(el.dom);
}else{
el = Ucren.Element(this.dom.parentNode);
el.remove(this);
}
return this;
},
insert: function(dom){
var tdom;
tdom = this.dom;
if(tdom.firstChild){
tdom.insertBefore(dom, tdom.firstChild);
}else{
this.add(dom);
}
return this;
},
addEvents: function(conf){
var blank, el, rtn;
blank = {};
rtn = {};
el = this.dom;
Ucren.each(conf, function(item, key){
rtn[key] = Ucren.addEvent(el, key, item);
});
return rtn;
},
removeEvents: function(conf){
var blank, el;
blank = {};
el = this.dom;
Ucren.each(conf, function(item, key){
Ucren.delEvent(el, key, item);
});
return this;
},
getPos: function(){
var el, parentNode, pos, box, offset;
el = this.dom;
pos = {};
if(el.getBoundingClientRect){
box = el.getBoundingClientRect();
offset = Ucren.isIe ? 2 : 0;
var doc = document;
var scrollTop = Math.max(doc.documentElement.scrollTop,
doc.body.scrollTop);
var scrollLeft = Math.max(doc.documentElement.scrollLeft,
doc.body.scrollLeft);
return {
x: box.left + scrollLeft - offset,
y: box.top + scrollTop - offset
};
}else{
pos = {
x: el.offsetLeft,
y: el.offsetTop
};
parentNode = el.offsetParent;
if(parentNode != el){
while(parentNode){
pos.x += parentNode.offsetLeft;
pos.y += parentNode.offsetTop;
parentNode = parentNode.offsetParent;
}
}
if(Ucren.isSafari && this.style("position") == "absolute"){ // safari doubles in some cases
pos.x -= document.body.offsetLeft;
pos.y -= document.body.offsetTop;
}
}
if(el.parentNode){
parentNode = el.parentNode;
}else{
parentNode = null;
}
while(parentNode && parentNode.tagName.toUpperCase() != "BODY" &&
parentNode.tagName.toUpperCase() != "HTML"){ // account for any scrolled ancestors
pos.x -= parentNode.scrollLeft;
pos.y -= parentNode.scrollTop;
if(parentNode.parentNode){
parentNode = parentNode.parentNode;
}else{
parentNode = null;
}
}
return pos;
},
getSize: function(){
var dom = this.dom;
var display = this.style("display");
if (display && display !== "none") {
return { width: dom.offsetWidth, height: dom.offsetHeight };
}
var style = dom.style;
var originalStyles = {
visibility: style.visibility,
position: style.position,
display: style.display
};
var newStyles = {
visibility: "hidden",
display: "block"
};
if (originalStyles.position !== "fixed")
newStyles.position = "absolute";
this.style(newStyles);
var dimensions = {
width: dom.offsetWidth,
height: dom.offsetHeight
};
this.style(originalStyles);
return dimensions;
},
observe: function(el, fn){
el = Ucren.Element(el);
el.on("infect", fn.bind(this));
return this;
},
usePNGbackground: function(image){
var dom;
dom = this.dom;
if(/\.png$/i.test(image) && Ucren.isIe6){
dom.style.filter =
"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" +
image + "',sizingMethod='scale');";
/// _background: none;
/// _filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/pic.png',sizingMethod='scale');
}else{
dom.style.backgroundImage = "url(" + image + ")";
}
return this;
},
setAlpha: function(){
var reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/;
return function(value){
var element = this.dom, es = element.style;
if(!Ucren.isIe){
es.opacity = value / 100;
/* }else if(es.filter === "string"){ */
}else{
if (element.currentStyle && !element.currentStyle.hasLayout)
es.zoom = 1;
if (reOpacity.test(es.filter)) {
value = value >= 99.99 ? "" : ("alpha(opacity=" + value + ")");
es.filter = es.filter.replace(reOpacity, value);
} else {
es.filter += " alpha(opacity=" + value + ")";
}
}
return this;
};
}(),
fadeIn: function(callback){
if(typeof this.fadingNumber == "undefined")
this.fadingNumber = 0;
this.setAlpha(this.fadingNumber);
var fading = function(){
this.setAlpha(this.fadingNumber);
if(this.fadingNumber == 100){
clearInterval(this.fadingInterval);
callback && callback();
}else
this.fadingNumber += 10;
}.bind(this);
this.display(true);
clearInterval(this.fadingInterval);
this.fadingInterval = setInterval(fading, Ucren.isIe ? 20 : 30);
return this;
},
fadeOut: function(callback){
if(typeof this.fadingNumber == "undefined")
this.fadingNumber = 100;
this.setAlpha(this.fadingNumber);
var fading = function(){
this.setAlpha(this.fadingNumber);
if(this.fadingNumber == 0){
clearInterval(this.fadingInterval);
this.display(false);
callback && callback();
}else
this.fadingNumber -= 10;
}.bind(this);
clearInterval(this.fadingInterval);
this.fadingInterval = setInterval(fading, Ucren.isIe ? 20 : 30);
return this;
},
useMouseAction: function(className, actions){
/**
* 调用示例: el.useMouseAction("xbutton", "over,out,down,up");
* 使用效果: el 会在 "xbutton xbutton-over","xbutton xbutton-out","xbutton xbutton-down","xbutton xbutton-up"
* 等四个 className 中根据相应的鼠标事件来进行切换。
* 特别提示: useMouseAction 可使用不同参数多次调用。
*/
if(!this.MouseAction)
this.MouseAction = new Ucren.MouseAction({ element: this });
this.MouseAction.use(className, actions);
return this;
}
}
);
if(Ucren.isIe)
document.execCommand("BackgroundImageCache", false, true);
for(var i in Ucren){
exports[i] = Ucren[i];
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\background.js
*/
define("scripts/object/background.js", function(exports){
var Ucren = require("scripts/lib/ucren");
var layer = require("scripts/layer");
var timeline = require("scripts/timeline");
var image, time;
var random = Ucren.randomNumber;
exports.set = function(){
image = layer.createImage( "default", "images/background.jpg", 0, 0, 640, 480 );
};
exports.wobble = function(){
time = timeline.setInterval( wobble, 50 );
};
exports.stop = function(){
time.stop();
image.attr({ x: 0, y: 0 });
};
function wobble(){
var x, y;
x = random( 12 ) - 6;
y = random( 12 ) - 6;
image.attr({ x: x, y: y });
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\console.js
*/
define("scripts/object/console.js", function(exports){
var layer = require("scripts/layer");
var x = 16, y = 0;
var texts = [];
exports.set = function(){
};
exports.clear = function(){
for(var i = 0, l = texts.length; i < l; i ++)
texts[i].remove();
texts.length = y = 0;
};
exports.log = function(text){
y += 20;
texts.push( layer.createText( "default", text, x, y ) );
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\developing.js
*/
define("scripts/object/developing.js", function(exports){
var layer = require("scripts/layer");
var tween = require("scripts/lib/tween");
var timeline = require("scripts/timeline");
var message = require("scripts/message");
var exponential = tween.exponential.co;
/**
* "coming soon" 模块
*/
exports.anims = [];
exports.set = function(){
this.image = layer.createImage( "default", "images/developing.png", 103, 218, 429, 53 ).hide().scale( 1e-5, 1e-5 );
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1e-5, 1, "show" ],
object: this, onTimeUpdate: this.onZooming, onTimeStart: this.onZoomStart, onTimeEnd: this.onZoomEnd,
recycle: this.anims
});
this.hide( 2000 );
};
exports.hide = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1, 1e-5, "hide" ],
object: this, onTimeUpdate: this.onZooming, onTimeStart: this.onZoomStart, onTimeEnd: this.onZoomEnd,
recycle: this.anims
});
};
// 显示/隐藏 相关
exports.onZoomStart = function(){
this.image.show();
};
exports.onZooming = function( time, sz, ez, z ){
this.image.scale( z = exponential( time, sz, ez - sz, 500 ), z );
};
exports.onZoomEnd = function( sz, ez, mode ){
if( mode === "hide" )
this.image.hide();
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\dojo.js
*/
define("scripts/object/dojo.js", function(exports){
var rotate = require("scripts/factory/rotate");
var tween = require("scripts/lib/tween");
exports = rotate.create("images/dojo.png", 41, 240, 175, 175, 1e-5, tween.exponential.co, 500);;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\flame.js
*/
define("scripts/object/flame.js", function(exports){
/**
* 火焰模块
* @author zswang, dron
*/
var layer = require("scripts/layer").getLayer( "fruit" );
var timeline = require("scripts/timeline");
var Ucren = require("scripts/lib/ucren");
/*
raphael.path('M 27,122 Q 9,42 27,21 45,42 27,122')
.attr({
stroke: 'none',
fill: '180-#D8D380-#EDED7A-#D8D380'
});
*/
// 缩写
var math = Math, cos = math.cos, sin = math.sin,
trunc = parseInt,
random = math.random,
PI = math.PI;
var guid = 0;
/**
* 添加一个火苗
* @param{Array} center 中心位置 单位像素
* @param{Number} angle 运动方向 单位幅度
* @param{Number} length 运动长度 单位像素
* @param{Number} life 存活时间 单位毫秒
*/
function appendFlame( center, angle, length, life, flames ){
return flames[guid] = {
id: guid ++,
birthday: new Date,
center: center,
angle: angle,
length: length,
life: life,
path: layer.path().attr({ stroke: 'none', fill: trunc( angle * 180 / PI ) + '-#fafad9-#f0ef9c' })
};
}
var radius = 15;
function updateFlame( flames, n ){
var item = flames[n];
if ( !item )
return;
var age, center, p1, p2, p3, p4;
age = 1 - (new Date - item.birthday) / item.life;
if ( age <= 0 ){
item.path.remove();
delete flames[item.id];
return;
}
var ia, ic, il;
ia = item.angle;
ic = item.center;
il = item.length;
center = [ trunc(ic[0] + cos(ia) * il * (1 - age)), trunc(ic[1] + sin(ia) * il * (1 - age)) ];
p1 = [ trunc(center[0] - cos(ia) * radius * age), trunc(center[1] - sin(ia) * radius * age) ];
p2 = [ trunc(center[0] + cos(ia) * radius * age), trunc(center[1] + sin(ia) * radius * age) ];
p3 = [ trunc(center[0] - cos(ia + .5 * PI) * radius * .4 * age), trunc(center[1] - sin(ia + .5 * PI) * radius * .4 * age) ];
p4 = [ trunc(center[0] - cos(ia - .5 * PI) * radius * .4 * age), trunc(center[1] - sin(ia - .5 * PI) * radius * .4 * age) ];
item.path.attr({ path: 'M' + p1 + ' Q' + [ p3, p2, p4, p1 ].join(' ') });
};
function removeFlame( flames, n ){
var item = flames[n];
if( !item )
return;
item.path.remove();
delete flames[ n ];
};
exports.create = function( ox, oy, start ){
var timer1, timer2;
var object = {
pos: function( x, y ){
nx = x;
ny = y;
image.attr( "x", nx - 21 ).attr( "y", ny - 21 );
},
remove: function(){
[ timer1, timer2 ].invoke( "stop" );
image.remove();
for (var p in flames)
removeFlame( flames, p );
}
};
var nx = ox, ny = oy;
var image = layer.image("images/smoke.png", nx - 21, ny - 21, 43, 43).hide();
var flames = {};
timer1 = timeline.setTimeout(function(){
image.show();
timer2 = timeline.setInterval(function(){
if(random() < 0.9)
appendFlame( [ nx, ny ], PI * 2 * random(), 60, 200 + 500 * random(), flames );
for (var p in flames)
updateFlame( flames, p );
}, Ucren.isIe ? 20 : 40);
}, start || 0);
return object;
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\flash.js
*/
define("scripts/object/flash.js", function(exports){
/**
*
*/
var layer = require("scripts/layer");
var timeline = require("scripts/timeline")
var tween = require("scripts/lib/tween");
var Ucren = require("scripts/lib/ucren");
var sound = require("scripts/lib/sound");
var image, snd, xDiff = 0, yDiff = 0;
var anim = tween.quadratic.cio;
var anims = [];
var dur = 100;
var switchOn = true;
// if( Ucren.isIe || Ucren.isSafari )
// switchOn = false;
exports.set = switchOn ? function(){
image = layer.createImage( "flash", "images/flash.png", 0, 0, 358, 20 ).hide();
snd = sound.create( "sound/splatter" );
} : Ucren.nul;
exports.showAt = switchOn ? function( x, y, an ){
image.rotate( an, true ).scale( 1e-5, 1e-5 ).attr({
x: x + xDiff,
y: y + yDiff
}).show();
anims.clear && anims.clear();
snd.play();
timeline.createTask({
start: 0, duration: dur, data: [ 1e-5, 1 ],
object: this, onTimeUpdate: this.onTimeUpdate,
recycle: anims
});
timeline.createTask({
start: dur, duration: dur, data: [ 1, 1e-5 ],
object: this, onTimeUpdate: this.onTimeUpdate,
recycle: anims
});
} : Ucren.nul;
exports.onTimeUpdate = switchOn ? function( time, a, b, z ){
image.scale( z = anim( time, a, b - a, dur ), z );
} : Ucren.nul;;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\fps.js
*/
define("scripts/object/fps.js", function(exports){
var layer = require("scripts/layer");
var timeline =require("scripts/timeline");
var text, fps = "fps: ";
exports.set = function(){
text = layer.createText( "default", fps + "0", 4, 470 ).attr( "fill", "#ccc" );
};
exports.update = function(){
text.attr( "text", fps + ( timeline.getFPS() >> 0 ) );
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\game-over.js
*/
define("scripts/object/game-over.js", function(exports){
var layer = require("scripts/layer");
var tween = require("scripts/lib/tween");
var timeline = require("scripts/timeline");
var message = require("scripts/message");
var state = require("scripts/state");
var exponential = tween.exponential.co;
/**
* "game-over"模块
*/
exports.anims = [];
exports.set = function(){
this.image = layer.createImage( "default", "images/game-over.png", 75, 198, 490, 85 ).hide().scale( 1e-5, 1e-5 );
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1e-5, 1, "show" ],
object: this, onTimeUpdate: this.onZooming, onTimeStart: this.onZoomStart, onTimeEnd: this.onZoomEnd,
recycle: this.anims
});
};
exports.hide = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1, 1e-5, "hide" ],
object: this, onTimeUpdate: this.onZooming, onTimeStart: this.onZoomStart, onTimeEnd: this.onZoomEnd,
recycle: this.anims
});
};
// 显示/隐藏 相关
exports.onZoomStart = function( sz, ez, mode ){
if( mode == "show" )
this.image.show();
};
exports.onZooming = function( time, sz, ez, z ){
this.image.scale( z = exponential( time, sz, ez - sz, 500 ), z );
};
exports.onZoomEnd = function( sz, ez, mode ){
if( mode == "show" )
state( "click-enable" ).on();
else if( mode === "hide" )
this.image.hide();
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\home-desc.js
*/
define("scripts/object/home-desc.js", function(exports){
var displacement = require("scripts/factory/displacement");
var tween = require("scripts/lib/tween");
exports = displacement.create("images/home-desc.png", 161, 91, -161, 140, 7, 127, tween.exponential.co, 500);;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\home-mask.js
*/
define("scripts/object/home-mask.js", function(exports){
var displacement = require("scripts/factory/displacement");
var tween = require("scripts/lib/tween");
exports = displacement.create("images/home-mask.png", 640, 183, 0, -183, 0, 0, tween.exponential.co, 1e3);;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\knife.js
*/
define("scripts/object/knife.js", function(exports){
var timeline = require("scripts/timeline");
var layer = require("scripts/layer").getLayer( "knife" );
var Ucren = require("scripts/lib/ucren");
/**
* 刀光模块
*/
var lastX = null, lastY = null;
var abs = Math.abs;
var life = 200;
var stroke = 10;
var color = "#cbd3db";
var anims = [];
var switchState = true;
var knifes = [];
function ClassKnifePart( conf ){
this.sx = conf.sx;
this.sy = conf.sy;
this.ex = conf.ex;
this.ey = conf.ey;
knifes.push( this );
}
ClassKnifePart.prototype.set = function(){
var sx, sy, ex, ey, dx, dy, ax, ay;
sx = this.sx;
sy = this.sy;
ex = this.ex;
ey = this.ey;
dx = sx - ex;
dy = sy - ey;
ax = abs(dx);
ay = abs(dy);
if(ax > ay)
sx += dx < 0 ? -1 : 1,
sy += dy < 0 ? -( 1 * ay / ax ) : 1 * ay / ax;
else
sx += dx < 0 ? -( 1 * ax / ay ) : 1 * ax / ay,
sy += dy < 0 ? -1 : 1;
this.line = layer.path( "M" + sx + "," + sy + "L" + ex + "," + ey ).attr({
"stroke": color,
"stroke-width": stroke + "px"
});
timeline.createTask({ start: 0, duration: life, object: this, onTimeUpdate: this.update, onTimeEnd: this.end, recycle: anims });
return this;
};
ClassKnifePart.prototype.update = function( time ){
this.line.attr( "stroke-width", stroke * (1 - time / life) + "px" );
};
ClassKnifePart.prototype.end = function(){
this.line.remove();
var index;
if( index = knifes.indexOf( this ) )
knifes.splice( index, 1 );
};
exports.newKnife = function(){
lastX = lastY = null;
};
exports.through = function( x, y ){
if( !switchState )
return ;
var ret = null;
if( lastX !== null && ( lastX != x || lastY != y ) )
new ClassKnifePart({ sx: lastX, sy: lastY, ex: x, ey: y }).set(),
ret = [ lastX, lastY, x, y ];
lastX = x;
lastY = y;
return ret;
};
exports.pause = function(){
anims.clear();
this.switchOff();
};
exports.switchOff = function(){
switchState = false;
};
exports.switchOn = function(){
switchState = true;
this.endAll();
};
exports.endAll = function(){
for(var i = knifes.length - 1; i >= 0; i --)
knifes[i].end();
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\light.js
*/
define("scripts/object/light.js", function(exports){
/**
* 炸弹爆炸时的光线
*/
var layer = require("scripts/layer");
var maskLayer = layer.getLayer( "mask" );
layer = layer.getLayer( "light" );
var Ucren = require("scripts/lib/ucren");
var timeline = require("scripts/timeline");
var message = require("scripts/message");
var random = Ucren.randomNumber;
var pi = Math.PI;
var sin = Math.sin;
var cos = Math.cos;
var lights = [];
var indexs = [];
var lightsNum = 10;
for(var i = 0; i < lightsNum; i ++)
indexs[i] = i;
exports.start = function( boom ){
var x = boom.originX, y = boom.originY, time = 0, idx = indexs.random();
var b = function(){
build( x, y, idx[ this ] );
};
for(var i = 0; i < lightsNum; i ++)
timeline.setTimeout( b.bind( i ), time += 200 );
timeline.setTimeout(function(){
this.overWhiteLight();
}.bind( this ), time + 200);
};
exports.overWhiteLight = function(){
message.postMessage( "overWhiteLight.show" );
this.removeLights();
var dur = 4e3;
var mask = maskLayer.rect( 0, 0, 640, 480 ).attr({ fill: "#fff", stroke: "none" });
var control = {
onTimeUpdate: function( time ){
mask.attr( "opacity", 1 - time / dur );
},
onTimeEnd: function(){
mask.remove();
message.postMessage( "game.over" );
}
};
timeline.createTask({
start: 0, duration: dur,
object: control, onTimeUpdate: control.onTimeUpdate, onTimeEnd: control.onTimeEnd
});
};
exports.removeLights = function(){
for(var i = 0, l = lights.length; i < l; i ++)
lights[i].remove();
lights.length = 0;
};
function build( x, y, r ){
var a1, a2, x1, y1, x2, y2;
a1 = r * 36 + random( 10 );
a2 = a1 + 5;
a1 = pi * a1 / 180;
a2 = pi * a2 / 180;
x1 = x + 640 * cos( a1 );
y1 = y + 640 * sin( a1 );
x2 = x + 640 * cos( a2 );
y2 = y + 640 * sin( a2 );
var light = layer.path( [ "M", x, y, "L", x1, y1, "L", x2, y2, "Z" ] ).attr({
stroke: "none",
fill: "#fff"
});
lights.push( light );
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\logo.js
*/
define("scripts/object/logo.js", function(exports){
var displacement = require("scripts/factory/displacement");
var tween = require("scripts/lib/tween");
exports = displacement.create("images/logo.png", 288, 135, 17, -182, 17, 1, tween.exponential.co, 1e3);;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\lose.js
*/
define("scripts/object/lose.js", function(exports){
var layer = require("scripts/layer");
var tween = require("scripts/lib/tween");
var timeline = require("scripts/timeline");
var Ucren = require("scripts/lib/ucren");
var message = require("scripts/message");
var anim = tween.exponential.co;
var back = tween.back.co;
/**
*
*/
var o1, o2, o3, animLength = 500;
var conf1 = { src: "images/x.png", sx: 650, ex: 561, y: 5, w: 22, h: 19 };
var conf2 = { src: "images/xx.png", sx: 671, ex: 582, y: 5, w: 27, h: 26 };
var conf3 = { src: "images/xxx.png", sx: 697, ex: 608, y: 6, w: 31, h: 32 };
var number = 0;
exports.anims = [];
exports.set = function(){
o1 = layer.createImage( "default", conf1.src, conf1.sx, conf1.y, conf1.w, conf1.h ).hide();
o2 = layer.createImage( "default", conf2.src, conf2.sx, conf2.y, conf2.w, conf2.h ).hide();
o3 = layer.createImage( "default", conf3.src, conf3.sx, conf3.y, conf3.w, conf3.h ).hide();
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: animLength, data: [ "show", conf1.sx, conf1.ex, conf2.sx, conf2.ex, conf3.sx, conf3.ex ],
object: this, onTimeUpdate: this.onTimeUpdate, onTimeStart: this.onTimeStart, onTimeEnd: this.onTimeEnd,
recycle: this.anims
});
};
exports.hide = function( start ){
timeline.createTask({
start: start, duration: animLength, data: [ "hide", conf1.ex, conf1.sx, conf2.ex, conf2.sx, conf3.ex, conf3.sx ],
object: this, onTimeUpdate: this.onTimeUpdate, onTimeStart: this.onTimeStart, onTimeEnd: this.onTimeEnd,
recycle: this.anims
});
};
exports.showLoseAt = function( x ){
var infx, inf = [
[ o1, conf1 ],
[ o2, conf2 ],
[ o3, conf3 ]
];
createPosShow( x );
infx = inf[ ( ++ number ) - 1 ];
infx[0].attr( "src", infx[1].src.replace( "x.png", "xf.png" ) ).scale( 1e-5, 1e-5 );
this.scaleImage( infx[0] );
if( number == 3 )
number = 0,
message.postMessage( "game.over" );
};
exports.scaleImage = function( image ){
var dur = 500;
image.myOnScaling = image.myOnScaling || function( time, z ){
this.scale( z = back( time, 1e-5, 1 - 1e-5, dur ), z );
};
image.myOnScaleEnd = image.myOnScaleEnd || function(){
this.scale( 1, 1 );
};
timeline.createTask({
start: 0, duration: dur,
object: image, onTimeUpdate: image.myOnScaling, onTimeEnd: image.myOnScaleEnd,
recycle: this.anims
});
};
// 显示/隐藏 相关
exports.onTimeUpdate = function( time, mode, x1s, x1e, x2s, x2e, x3s, x3e ){
o1.attr( "x", anim( time, x1s, x1e - x1s, animLength ) );
o2.attr( "x", anim( time, x2s, x2e - x2s, animLength ) );
o3.attr( "x", anim( time, x3s, x3e - x3s, animLength ) );
};
exports.onTimeStart = function( mode ){
if( mode == "show" )
[ o1, o2, o3 ].invoke( "show" );
};
exports.onTimeEnd = function( mode ){
if( mode == "hide" )
[ o1, o2, o3 ].invoke( "hide" ),
[ [ o1, conf1 ], [ o2, conf2 ], [ o3, conf3 ] ].forEach(function( infx ){
infx[0].attr( "src", infx[1].src.replace( "xf.png", "x.png" ) );
});
};
function createPosShow( x ){
var image = layer.createImage( "default", "images/lose.png", x - 27, 406, 54, 50 ).scale( 1e-5, 1e-5 );
var duration = 500;
var control = {
show: function( start ){
timeline.createTask({
start: start, duration: duration, data: [ tween.back.co, 1e-5, 1 ],
object: this, onTimeUpdate: this.onScaling, onTimeEnd: this.onShowEnd
// recycle: anims
});
},
hide: function( start ){
timeline.createTask({
start: start, duration: duration, data: [ tween.back.ci, 1, 1e-5 ],
object: this, onTimeUpdate: this.onScaling, onTimeEnd: this.onHideEnd
// recycle: anims
});
},
onScaling: function( time, anim, a, b, z ){
image.scale( z = anim( time, a, b - a, duration ), z );
},
onShowEnd: function(){
this.hide( 1500 );
},
onHideEnd: function(){
image.remove();
}
};
control.show( 200 );
};
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\new-game.js
*/
define("scripts/object/new-game.js", function(exports){
var rotate = require("scripts/factory/rotate");
var tween = require("scripts/lib/tween");
exports = rotate.create("images/new-game.png", 244, 231, 195, 195, 1e-5, tween.exponential.co, 500);;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\new.js
*/
define("scripts/object/new.js", function(exports){
var layer = require("scripts/layer");
var tween = require("scripts/lib/tween");
var timeline = require("scripts/timeline");
var Ucren = require("scripts/lib/ucren");
var image;
var cycleTime = 300;
var sx = 129, sy = 328, ex = 170, ey = 221, sw = 0, sh = 0, ew = 70, eh = 42, dy = 8;
var showAnim = tween.exponential.co;
var jumpAnim = tween.quadratic.ci;
exports.anims = [];
exports.set = function(){
image = layer.createImage( "default", "images/new.png", sx, sy, sw, sh );
};
exports.unset = function(){
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: 500,
data: [ sx, ex, sy, ey, sw, ew, sh, eh ],
object: this, onTimeUpdate: this.onShowing, onTimeStart: this.onShowStart, onTimeEnd: this.onShowEnd,
recycle: this.anims
});
};
exports.hide = function( start ){
this.anims.clear();
timeline.createTask({
start: start, duration: 500,
data: [ ex, sx, ey, sy, ew, sw, eh, sh ],
object: this, onTimeUpdate: this.onShowing,
recycle: this.anims
});
};
exports.jump = function(){
this.anims.clear();
timeline.createTask({ start: 0, duration: -1, object: this, onTimeUpdate: this.onJumping, recycle: this.anims });
};
// 显示相关
exports.onShowStart = function(){
};
exports.onShowing = function( time, sx, ex, sy, ey, sw, ew, sh, eh ){
image.attr({
x: showAnim( time, sx, ex - sx, 500 ),
y: showAnim( time, sy, ey - sy, 500 ),
width: showAnim( time, sw, ew - sw, 500 ),
height: showAnim( time, sh, eh - sh, 500 )
});
};
exports.onShowEnd = function(){
this.jump();
};
// 跳跃相关
exports.onJumping = function(time){
var t = parseInt(time / cycleTime);
time = time % cycleTime;
if( t % 2 ) time = cycleTime - time;
image.attr("y", jumpAnim( time, ey, dy, cycleTime ));
};;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\ninja.js
*/
define("scripts/object/ninja.js", function(exports){
var displacement = require("scripts/factory/displacement");
var tween = require("scripts/lib/tween");
exports = displacement.create("images/ninja.png", 244, 81, 315, -140, 315, 43, {
show: tween.bounce.co,
hide: tween.exponential.co
}, 1e3);;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\quit.js
*/
define("scripts/object/quit.js", function(exports){
var rotate = require("scripts/factory/rotate");
var tween = require("scripts/lib/tween");
exports = rotate.create("images/quit.png", 493, 311, 141, 141, 1e-5, tween.exponential.co, 500);;
return exports;
});
/**
* @source D:\hosting\demos\fruit-ninja\output\scripts\object\score.js
*/
define("scripts/object/score.js", function(exports){
var layer = require("scripts/layer");
var tween = require("scripts/lib/tween");
var timeline = require("scripts/timeline");
var Ucren = require("scripts/lib/ucren");
var setTimeout = timeline.setTimeout.bind( timeline );
var anim = tween.exponential.co;
var message = require("scripts/message");
/**
* 分数模块
*/
var image, text1, text2, animLength = 500;;
var imageSx = -94, imageEx = 6;
var text1Sx = -59, text1Ex = 41;
var text2Sx = -93, text2Ex = 7;
exports.anims = [];
exports.set = function(){
image = layer.createImage( "default", "images/score.png", imageSx, 8, 29, 31 ).hide();
text1 = layer.createText( "default", "0", text1Sx, 24, "90-#fc7f0c-#ffec53", "30px" ).hide();
text2 = layer.createText( "default", "BEST 999", text2Sx, 48, "#af7c05", "14px" ).hide();
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: animLength, data: [ "show", imageSx, imageEx, text1Sx, text1Ex, text2Sx, text2Ex ],
object: this, onTimeUpdate: this.onTimeUpdate, onTimeStart: this.onTimeStart, onTimeEnd: this.onTimeEnd,
recycle: this.anims
});
};
exports.hide = function( start ){
timeline.createTask({
start: start, duration: animLength, data: [ "hide", imageEx, imageSx, text1Ex, text1Sx, text2Ex, text2Sx ],
object: this, onTimeUpdate: this.onTimeUpdate, onTimeStart: this.onTimeStart, onTimeEnd: this.onTimeEnd,
recycle: this.anims
});
};
exports.number = function( number ){
text1.attr( "text", number || 0 );
image.scale( 1.2, 1.2 );
setTimeout(function(){
image.scale( 1, 1 );
}, 60);
// message.postMessage( number, "score.change" );
};
// 显示/隐藏 相关
exports.onTimeUpdate = function( time, mode, isx, iex, t1sx, t1ex, t2sx, t2ex ){
image.attr( "x", anim( time, isx, iex - isx, animLength ) );
text1.attr( "x", anim( time, t1sx, t1ex - t1sx, animLength ) );
text2.attr( "x", anim( time, t2sx, t2ex - t2sx, animLength ) );
};
exports.onTimeStart = function( mode ){
if( mode === "show" )
[ image, text1, text2 ].invoke( "show" );
};
exports.onTimeEnd = function( mode ){
if( mode === "hide" )
[ image, text1, text2 ].invoke( "hide" ),
text1.attr( "text", 0 );
};;
return exports;
});
startModule("scripts/main"); | zzy-code-test | html5/fruitninja/scripts/all.js | JavaScript | gpl2 | 186,995 |
var Ucren = require( "lib/ucren" );
var knife = require( "object/knife" );
var message = require( "message" );
var state = require( "state" );
var canvasLeft, canvasTop;
canvasLeft = canvasTop = 0;
exports.init = function(){
this.fixCanvasPos();
this.installDragger();
this.installClicker();
};
exports.installDragger = function(){
var dragger = new Ucren.BasicDrag({ type: "calc" });
dragger.on( "returnValue", function( dx, dy, x, y, kf ){
if( kf = knife.through( x - canvasLeft, y - canvasTop ) )
message.postMessage( kf, "slice" );
});
dragger.on( "startDrag", function(){
knife.newKnife();
});
dragger.bind( document.documentElement );
};
exports.installClicker = function(){
Ucren.addEvent( document, "click", function(){
if( state( "click-enable" ).ison() )
message.postMessage( "click" );
});
};
exports.fixCanvasPos = function(){
var de = document.documentElement;
var fix = function( e ){
canvasLeft = ( de.clientWidth - 640 ) / 2;
canvasTop = ( de.clientHeight - 480 ) / 2 - 40;
};
fix();
Ucren.addEvent( window, "resize", fix );
}; | zzy-code-test | html5/fruitninja/scripts/control.js | JavaScript | gpl2 | 1,147 |
var fruit = require( "factory/fruit" );
var Ucren = require( "lib/ucren" );
var fruits = fruit.getFruitInView();
/**
* 碰撞检测
*/
exports.check = function( knife ){
var ret = [], index = 0;
fruits.forEach(function( fruit ){
var ck = lineInEllipse(
knife.slice( 0, 2 ),
knife.slice( 2, 4 ),
[ fruit.originX, fruit.originY ],
fruit.radius
);
if( ck )
ret[ index ++ ] = fruit;
});
return ret;
};
function sqr(x){
return x * x;
}
function sign(n){
return n < 0 ? -1 : ( n > 0 ? 1 : 0 );
}
function equation12( a, b, c ){
if(a == 0)return;
var delta = b * b - 4 * a * c;
if(delta == 0)
return [ -1 * b / (2 * a), -1 * b / (2 * a) ];
else if(delta > 0)
return [ (-1 * b + Math.sqrt(delta)) / (2 * a), (-1 * b - Math.sqrt(delta)) / (2 * a) ];
}
// 返回线段和椭圆的两个交点,如果不相交,返回 null
function lineXEllipse( p1, p2, c, r, e ){
// 线段:p1, p2 圆心:c 半径:r 离心率:e
if (r <= 0) return;
e = e === undefined ? 1 : e;
var t1 = r, t2 = r * e, k;
a = sqr( t2) * sqr(p1[0] - p2[0]) + sqr(t1) * sqr(p1[1] - p2[1]);
if (a <= 0) return;
b = 2 * sqr(t2) * (p2[0] - p1[0]) * (p1[0] - c[0]) + 2 * sqr(t1) * (p2[1] - p1[1]) * (p1[1] - c[1]);
c = sqr(t2) * sqr(p1[0] - c[0]) + sqr(t1) * sqr(p1[1] - c[1]) - sqr(t1) * sqr(t2);
if (!( k = equation12(a, b, c, t1, t2) )) return;
var result = [
[ p1[0] + k[0] * (p2[0] - p1[0]), p1[1] + k[0] * (p2[1] - p1[1]) ],
[ p1[0] + k[1] * (p2[0] - p1[0]), p1[1] + k[1] * (p2[1] - p1[1]) ]
];
if ( !( ( sign( result[0][0] - p1[0] ) * sign( result[0][0] - p2[0] ) <= 0 ) &&
( sign( result[0][1] - p1[1] ) * sign( result[0][1] - p2[1] ) <= 0 ) ) )
result[0] = null;
if ( !( ( sign( result[1][0] - p1[0] ) * sign( result[1][0] - p2[0] ) <= 0 ) &&
( sign( result[1][1] - p1[1] ) * sign( result[1][1] - p2[1] ) <= 0 ) ) )
result[1] = null;
return result;
}
// 判断计算线段和椭圆是否相交
function lineInEllipse( p1, p2, c, r, e ){
var t = lineXEllipse( p1, p2, c, r, e );
return t && ( t[0] || t[1] );
} | zzy-code-test | html5/fruitninja/scripts/collide.js | JavaScript | gpl2 | 2,104 |
/**
* game logic
*/
var timeline = require( "timeline" );
var Ucren = require( "lib/ucren" );
var sound = require( "lib/sound" );
var fruit = require( "factory/fruit" );
var score = require( "object/score" );
var message = require( "message" );
var state = require( "state" );
var lose = require( "object/lose" );
var gameOver = require( "object/game-over" );
var knife = require( "object/knife" );
// var sence = require( "sence" );
var background = require( "object/background" );
var light = require( "object/light" );
var scoreNumber = 0;
var random = Ucren.randomNumber;
var volleyNum = 2, volleyMultipleNumber = 5;
var fruits = [];
var gameInterval;
var snd;
var boomSnd;
// fruit barbette
var barbette = function(){
if( fruits.length >= volleyNum )
return ;
var startX = random( 640 ), endX = random( 640 ), startY = 600;
var f = fruit.create( startX, startY ).shotOut( 0, endX );
fruits.push( f );
snd.play();
barbette();
};
// start game
exports.start = function(){
snd = sound.create( "sound/throw" );
boomSnd = sound.create( "sound/boom" );
timeline.setTimeout(function(){
state( "game-state" ).set( "playing" );
gameInterval = timeline.setInterval( barbette, 1e3 );
}, 500);
};
exports.gameOver = function(){
state( "game-state" ).set( "over" );
gameInterval.stop();
gameOver.show();
// timeline.setTimeout(function(){
// // sence.switchSence( "home-menu" );
// // TODO: require 出现互相引用时,造成死循环,这个问题需要跟进,这里暂时用 postMessage 代替
// message.postMessage( "home-menu", "sence.switchSence" );
// }, 2000);
scoreNumber = 0;
volleyNum = 2;
fruits.length = 0;
};
exports.applyScore = function( score ){
if( score > volleyNum * volleyMultipleNumber )
volleyNum ++,
volleyMultipleNumber += 50;
};
exports.sliceAt = function( fruit, angle ){
var index;
if( state( "game-state" ).isnot( "playing" ) )
return;
if( fruit.type != "boom" ){
fruit.broken( angle );
if( index = fruits.indexOf( fruit ) )
fruits.splice( index, 1 );
score.number( ++ scoreNumber );
this.applyScore( scoreNumber );
}else{
boomSnd.play();
this.pauseAllFruit();
background.wobble();
light.start( fruit );
}
};
exports.pauseAllFruit = function(){
gameInterval.stop();
knife.pause();
fruits.invoke( "pause" );
};
// message.addEventListener("fruit.fallOff", function( fruit ){
// var index;
// if( ( index = fruits.indexOf( fruit ) ) > -1 )
// fruits.splice( index, 1 );
// });
message.addEventListener("fruit.remove", function( fruit ){
var index;
if( ( index = fruits.indexOf( fruit ) ) > -1 )
fruits.splice( index, 1 );
});
var eventFruitFallOutOfViewer = function( fruit ){
if( fruit.type != "boom" )
lose.showLoseAt( fruit.originX );
};
state( "game-state" ).hook( function( value ){
if( value == "playing" )
message.addEventListener( "fruit.fallOutOfViewer", eventFruitFallOutOfViewer );
else
message.removeEventListener( "fruit.fallOutOfViewer", eventFruitFallOutOfViewer );
} );
message.addEventListener("game.over", function(){
exports.gameOver();
knife.switchOn();
});
message.addEventListener("overWhiteLight.show", function(){
knife.endAll();
for(var i = fruits.length - 1; i >= 0; i --)
fruits[i].remove();
background.stop();
});
message.addEventListener("click", function(){
state( "click-enable" ).off();
gameOver.hide();
message.postMessage( "home-menu", "sence.switchSence" );
}); | zzy-code-test | html5/fruitninja/scripts/game.js | JavaScript | gpl2 | 3,708 |
var Ucren = require( "lib/ucren" );
var sound = require( "lib/sound" );
var fruit = require( "factory/fruit" );
var flash = require( "object/flash" );
var state = require( "state" );
var message = require( "message" );
// the fixed elements
var background = require( "object/background" );
var fps = require( "object/fps" );
// the home page elements
var homeMask = require( "object/home-mask" );
var logo = require( "object/logo" );
var ninja = require( "object/ninja" )
var homeDesc = require( "object/home-desc" );
var dojo = require( "object/dojo" );
var newGame = require( "object/new-game" );
var quit = require( "object/quit" );
var newSign = require( "object/new" );
var peach, sandia, boom;
// the elements in game body
var score = require( "object/score" );
var lose = require( "object/lose" );
// the game logic
var game = require( "game" );
// the elements in 'developing' module
var developing = require( "object/developing" );
var gameOver = require( "object/game-over" );
// commons
var message = require( "message" );
var timeline = require( "timeline" );
var setTimeout = timeline.setTimeout.bind( timeline );
var setInterval = timeline.setInterval.bind( timeline );
var menuSnd;
var gameStartSnd;
// initialize sence
exports.init = function(){
menuSnd = sound.create( "sound/menu" );
gameStartSnd = sound.create( "sound/start" );
[ background, homeMask, logo, ninja, homeDesc, dojo, newSign, newGame, quit, score, lose, developing, gameOver, flash /*, fps */ ].invoke( "set" );
// setInterval( fps.update.bind( fps ), 500 );
};
// switch sence
exports.switchSence = function( name ){
var curSence = state( "sence-name" );
var senceState = state( "sence-state" );
if( curSence.is( name ) )
return ;
var onHide = function(){
curSence.set( name );
senceState.set( "entering" );
switch( name ){
case "home-menu": this.showMenu( onShow ); break;
case "dojo-body": this.showDojo( onShow ); break;
case "game-body": this.showNewGame( onShow ); break;
case "quit-body": this.showQuit( onShow ); break;
}
}.bind( this );
var onShow = function(){
senceState.set( "ready" );
if( name == "dojo-body" || name == "quit-body" ){
exports.switchSence( "home-menu" );
}
};
senceState.set( "exiting" );
if( curSence.isunset() ) onHide();
else if( curSence.is( "home-menu" ) ) this.hideMenu( onHide );
else if( curSence.is( "dojo-body" ) ) this.hideDojo( onHide );
else if( curSence.is( "game-body" ) ) this.hideNewGame( onHide );
else if( curSence.is( "quit-body" ) ) this.hideQuit( onHide );
};
// to enter home page menu
exports.showMenu = function( callback ){
var callee = arguments.callee;
var times = callee.times = ++ callee.times || 1;
peach = fruit.create( "peach", 137, 333, true );
sandia = fruit.create( "sandia", 330, 322, true );
boom = fruit.create( "boom", 552, 367, true, 2500 );
[ peach, sandia, boom ].forEach(function( f ){ f.isHomeMenu = 1; });
peach.isDojoIcon = sandia.isNewGameIcon = boom.isQuitIcon = 1;
var group = [
[ homeMask, 0 ],
[ logo, 0 ],
[ ninja, 500 ],
[ homeDesc, 1500 ],
[ dojo, 2000 ],
[ newGame, 2000 ],
[ quit, 2000 ],
[ newSign, 2000 ],
[ peach, 2000 ],
[ sandia, 2000 ],
[ boom, 2000 ]
];
group.invoke( "show" );
[ peach, sandia ].invoke( "rotate", 2500 );
menuSnd.play();
setTimeout( callback, 2500 );
};
// to exit home page menu
exports.hideMenu = function( callback ){
[ newSign, dojo, newGame, quit ].invoke( "hide" );
[ homeMask, logo, ninja, homeDesc ].invoke( "hide" );
[ peach, sandia, boom ].invoke( "fallOff", 150 );
menuSnd.stop();
setTimeout( callback, fruit.getDropTimeSetting() );
};
// to enter game body
exports.showNewGame = function( callback ){
score.show();
lose.show();
game.start();
gameStartSnd.play();
setTimeout( callback, 1000 );
};
// to exit game body
exports.hideNewGame = function( callback ){
score.hide();
lose.hide();
gameStartSnd.stop();
setTimeout( callback, 1000 );
};
// to enter dojo mode
exports.showDojo = function( callback ){
developing.show( 250 );
setTimeout( callback, 1500 );
};
// to exit dojo mode
exports.hideDojo = function( callback ){
// TODO:
setTimeout( callback, 1000 );
};
// to enter quit page
exports.showQuit = function( callback ){
developing.show( 250 );
setTimeout( callback, 1500 );
};
// to exit quit page
exports.hideQuit = function( callback ){
// TODO:
setTimeout( callback, 1000 );
};
message.addEventListener("sence.switchSence", function( name ){
exports.switchSence( name );
}); | zzy-code-test | html5/fruitninja/scripts/sence.js | JavaScript | gpl2 | 4,850 |
/**
* a simple message manager
* @author dron
* @date 2012-06-27
*/
var Ucren = require( "lib/ucren" );
/**
* send a message
* @param {Any} message,message... message contents
* @param {String} to message address
*/
exports.postMessage = function( message/*, message, message... */, to ){
var messages = [].slice.call( arguments, 0 ),
splitIndex = messages.length - 1;
to = messages[ splitIndex ];
messages.slice( 0, splitIndex );
Ucren.dispatch( to, messages );
};
/**
* bind an message handler
* @param {String} from message address
* @param {Function} fn message handler
*/
exports.addEventListener = function( from, fn ){
Ucren.dispatch( from, fn );
};
/**
* remove an message handler
* @param {String} from message address
* @param {Function} fn message handler
*/
exports.removeEventListener = function( from, fn ){
Ucren.dispatch.remove( from, fn );
}; | zzy-code-test | html5/fruitninja/scripts/message.js | JavaScript | gpl2 | 905 |
{include ../../../system/scripts/libs/buzz.js} | zzy-code-test | html5/fruitninja/scripts/lib/buzz.js | JavaScript | gpl2 | 46 |
exports.exponential = function(){};
exports.exponential.co = function(index, offset, target, framesNum){ return (index == framesNum) ? offset + target : target * (-Math.pow(2, -10 * index / framesNum) + 1) + offset; };
// exports.exponential.ci = function(index, offset, target, framesNum){ return (index == 0) ? offset : target * Math.pow(2, 10 * (index / framesNum - 1)) + offset; }
exports.bounce = function(){};
exports.bounce.co = function(index, offset, target, framesNum){ if((index /= framesNum) < (1 / 2.75)) return target * (7.5625 * index * index) + offset; else if(index < (2 / 2.75)) return target * (7.5625 * (index -= (1.5 / 2.75)) * index + .75) + offset; else if(index < (2.5 / 2.75)) return target * (7.5625 * (index -= (2.25 / 2.75)) * index + .9375) + offset; else return target * (7.5625 * (index -= (2.625 / 2.75)) * index + .984375) + offset; };
exports.quadratic = function(){};
exports.quadratic.ci = function(index, offset, target, framesNum){ return target * (index /= framesNum) * index + offset; };
exports.quadratic.co = function(index, offset, target, framesNum){ return - target * (index /= framesNum) * (index - 2) + offset; }
exports.quadratic.cio = function(index, offset, target, framesNum){ if((index /= framesNum / 2) < 1) return target / 2 * index * index + offset; else return - target / 2 * ((-- index) * (index - 2) - 1) + offset; };
exports.circular = function(index, offset, target, framesNum){ if((index /= framesNum / 2) < 1) return - target / 2 * (Math.sqrt(1 - index * index) - 1) + offset; else return target / 2 * (Math.sqrt(1 - (index -= 2) * index) + 1) + offset; }
exports.linear = function(index, offset, target, framesNum){ return target * index / framesNum + offset; };
exports.back = function(){};
exports.back.ci = function(index, offset, target, framesNum, s){ s = 1.70158; return target * (index /= framesNum) * index * ((s + 1) * index - s) + offset; };
exports.back.co = function(index, offset, target, framesNum, s){ s = 1.70158; return target * ((index = index / framesNum - 1) * index * ((s + 1) * index + s) + 1) + offset; }; | zzy-code-test | html5/fruitninja/scripts/lib/tween.js | JavaScript | gpl2 | 2,096 |
/**
* 简易声效控制
*/
/**
* 使用方法:
*
* var sound = require( "sound/main" );
*
* var snd = sound.create("sounds/myfile");
* snd.play();
*/
var buzz = require( "buzz" );
var supported = buzz.isSupported();
var config = {
formats: [ "ogg", "mp3" ],
preload: true,
autoload: true,
loop: false
};
function ClassBuzz( src ){
this.sound = new buzz.sound( src, config );
}
ClassBuzz.prototype.play = function( s ){
s = this.sound;
s.setPercent( 0 );
s.setVolume( 100 );
s.play();
};
ClassBuzz.prototype.stop = function(){
this.sound.fadeOut( 1e3, function(){
this.pause();
} );
};
exports.create = function( src ){
if( !supported )
return unSupported;
else
return new ClassBuzz( src );
}
function unSupported(){
// TODO:
}
unSupported.play =
unSupported.stop = function(){
// TODO:
}; | zzy-code-test | html5/fruitninja/scripts/lib/sound.js | JavaScript | gpl2 | 852 |
{include ../../../system/scripts/libs/ucren.js} | zzy-code-test | html5/fruitninja/scripts/lib/ucren.js | JavaScript | gpl2 | 47 |
{include ../../../system/scripts/libs/raphael-1.5.2.js} | zzy-code-test | html5/fruitninja/scripts/lib/raphael.js | JavaScript | gpl2 | 55 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="A simple HTML5 Template">
<meta name="author" content="dron">
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="/favicon.ico">
<link rel="stylesheet" href="images/index.css">
<title>水果忍者网页版</title>
<!--[if lt IE 9]><script>document.createElement("canvas");</script><![endif]-->
</head>
<body>
<div id="extra"></div>
<em> -- Fruit Ninja -- </em>
<em> The game is developed by the Baidu JS team, </em>
<em> we provide the source in git: https://github.com/ChineseDron/fruit-ninja </em>
<em> follow me on weibo http://weibo.com/baidujs </em>
<em> or learn more, to see http://tangram.baidu.com </em>
<a id="fork" href="https://github.com/ChineseDron/fruit-ninja" target="_blank"></a>
<canvas id="view" width="640" height="480"></canvas>
<div id="desc">
<div>水果忍者网页版,由百度 JS 小组倾情提供,我们邀请您关注<a href="http://weibo.com/baidujs" target="_blank">JS 小组的微博</a>,共同探讨前端话题。</div>
<div id="browser"></div>
</div>
<script src="scripts/all.js"></script>
</body>
</html>
| zzy-code-test | html5/fruitninja/index.html | HTML | gpl2 | 1,421 |
{include ../../system/css/reset.css}
{include ../../system/css/common.css}
html, body{
width: 100%;
height: 100%;
background: #484848;
}
body{
position: relative;
}
em{
display: none;
}
#extra, #view{
position: absolute;
left: 50%;
top: 50%;
width: 640px;
height: 480px;
margin: -280px auto auto -320px;
text-align: left;
background: #fff;
}
#view{
display: block;
background: transparent url(blank.gif) repeat 0 0;
cursor: default;
z-index: 20;
}
#extra{
background: #000;
}
#extra .layer{
position: absolute;
left: 0;
top: 0;
width: 640px;
height: 480px;
z-index: 10;
}
#fork{
display: block;
position: absolute;
right: 0;
top: 0;
width: 356px;
height: 92px;
cursor: pointer;
background-image: url(fork.gif);
z-index: 0;
}
#desc{
width: 100%;
position: absolute;
left: 0;
top: 50%;
height: 80px;
color: #ccc;
line-height: 40px;
margin-top: 200px;
text-align: center;
font-size: 14px;
}
#desc a{
color: #318fe1;
}
#browser{
font-size: 14px;
line-height: 16px;
}
#browser .b{
color: #fff;
font-weight: 700;
} | zzy-code-test | html5/fruitninja/images/index.css | CSS | gpl2 | 1,068 |
*{
margin:0;
padding:0;
}
body {
font:14px/1.3 Arial,sans-serif;
}
header {
background-color:#212121;
box-shadow: 0 -1px 2px #111111;
color:#fff;
display:block;
height:70px;
position:relative;
width:100%;
z-index:100;
}
header h2{
font-size:22px;
font-weight:normal;
left:50%;
margin-left:-400px;
padding:22px 0;
position:absolute;
width:540px;
}
header a.stuts,a.stuts:visited{
border:none;
text-decoration:none;
color:#fcfcfc;
font-size:14px;
left:50%;
line-height:31px;
margin:23px 0 0 110px;
position:absolute;
top:0;
}
header .stuts span {
font-size:22px;
font-weight:bold;
margin-left:5px;
}
.container {
background: url('../images/bg.jpg') repeat scroll 0 0 transparent;
height: 548px;
margin: 30px auto;
width: 450px;
position:relative;
}
/* CSS3 keyframes */
@-webkit-keyframes ckw {
0% {
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
}
100% {
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
}
}
@-moz-keyframes ckw {
0% {
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
}
100% {
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
}
}
@-webkit-keyframes cckw {
0% {
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
}
100% {
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
}
}
@-moz-keyframes cckw {
0% {
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
}
100% {
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
}
}
/* gears */
.gear {
float: none;
position: absolute;
text-align: center;
-moz-animation-timing-function: linear;
-moz-animation-iteration-count: infinite;
-moz-animation-direction: normal;
-moz-animation-delay: 0;
-moz-animation-play-state: running;
-moz-animation-fill-mode: forwards;
-webkit-animation-timing-function: linear;
-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: normal;
-webkit-animation-delay: 0;
-webkit-animation-play-state: running;
-webkit-animation-fill-mode: forwards;
}
#gear1 {
background: url('../images/g1.png') no-repeat 0 0;
height: 85px;
left: 31px;
top: 45px;
width: 85px;
-moz-animation-name: ckw;
-moz-animation-duration: 10s;
-webkit-animation-name: ckw;
-webkit-animation-duration: 10s;
}
#gear2 {
background: url('../images/g2.png') no-repeat 0 0;
height: 125px;
left: 105px;
top: 10px;
width: 125px;
-moz-animation-name: cckw;
-moz-animation-duration: 16.84s;
-webkit-animation-name: cckw;
-webkit-animation-duration: 16.84s;
}
#gear3 {
background: url('../images/g3.png') no-repeat 0 0;
height: 103px;
left: 149px;
top: 118px;
width: 103px;
-moz-animation-name: ckw;
-moz-animation-duration: 13.5s;
-webkit-animation-name: ckw;
-webkit-animation-duration: 13.5s;
}
#gear4 {
background: url('../images/g4.png') no-repeat 0 0;
height: 144px;
left: 46px;
top: 173px;
width: 144px;
-moz-animation-name: cckw;
-moz-animation-duration: 20.2s;
-webkit-animation-name: cckw;
-webkit-animation-duration: 20.2s;
}
#gear5 {
background: url('../images/g1.png') no-repeat 0 0;
height: 85px;
left: 127px;
top: 292px;
width: 85px;
-moz-animation-name: ckw;
-moz-animation-duration: 10s;
-webkit-animation-name: ckw;
-webkit-animation-duration: 10s;
}
#gear6 {
background: url('../images/g2.png') no-repeat 0 0;
height: 125px;
left: 200px;
top: 283px;
width: 125px;
-moz-animation-name: cckw;
-moz-animation-duration: 16.84s;
-webkit-animation-name: cckw;
-webkit-animation-duration: 16.84s;
}
#gear7 {
background: url('../images/g3.png') no-repeat 0 0;
height: 103px;
left: 277px;
top: 217px;
width: 103px;
-moz-animation-name: ckw;
-moz-animation-duration: 13.5s;
-webkit-animation-name: ckw;
-webkit-animation-duration: 13.5s;
} | zzy-code-test | html5/css3-gear/css/layout.css | CSS | gpl2 | 4,015 |
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8" />
<title>CSS3 Animated Gears</title>
<link href="css/layout.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<h2>CSS3 Animated Gears</h2>
<a href="http://www.html5war.com" class="stuts">go back<span>HTML5WAR</span></a>
</header>
<div class="container">
<div class="gear" id="gear1"></div>
<div class="gear" id="gear2"></div>
<div class="gear" id="gear3"></div>
<div class="gear" id="gear4"></div>
<div class="gear" id="gear5"></div>
<div class="gear" id="gear6"></div>
<div class="gear" id="gear7"></div>
</div>
</body>
</html>
| zzy-code-test | html5/css3-gear/index.html | HTML | gpl2 | 811 |
#!/bin/bash
# Tetris Game
# 10.21.2003 xhchen<xhchen@winbond.com.tw>
#颜色定义
cRed=1
cGreen=2
cYellow=3
cBlue=4
cFuchsia=5
cCyan=6
cWhite=7
colorTable=( $cRed $cGreen $cYellow $cBlue $cFuchsia $cCyan $cWhite )
#位置和大小
iLeft=3
iTop=2
((iTrayLeft = iLeft + 2))
((iTrayTop = iTop + 1))
((iTrayWidth = 10))
((iTrayHeight = 15))
#颜色设置
cBorder=$cGreen
cScore=$cFuchsia
cScorevalue=$cCyan
#控制信号
#改游戏使用两个进程,一个用于接收输入,一个用于游戏流程和显示界面;
#当前者接收到上下左右等按键时,通过向后者发送signal的方式通知后者。
sigRotate=25
sigLeft=26
sigRight=27
sigDown=28
sigAllDown=29
sigExit=30
#七中不同的方块的定义
#通过旋转,每种方块的显示的样式可能有几种
box0=(0 0 0 1 1 0 1 1)
box1=(0 2 1 2 2 2 3 2 1 0 1 1 1 2 1 3)
box2=(0 0 0 1 1 1 1 2 0 1 1 0 1 1 2 0)
box3=(0 1 0 2 1 0 1 1 0 0 1 0 1 1 2 1)
box4=(0 1 0 2 1 1 2 1 1 0 1 1 1 2 2 2 0 1 1 1 2 0 2 1 0 0 1 0 1 1 1 2)
box5=(0 1 1 1 2 1 2 2 1 0 1 1 1 2 2 0 0 0 0 1 1 1 2 1 0 2 1 0 1 1 1 2)
box6=(0 1 1 1 1 2 2 1 1 0 1 1 1 2 2 1 0 1 1 0 1 1 2 1 0 1 1 0 1 1 1 2)
#所有其中方块的定义都放到box变量中
box=(${box0[@]} ${box1[@]} ${box2[@]} ${box3[@]} ${box4[@]} ${box5[@]} ${box6[@]})
#各种方块旋转后可能的样式数目
countBox=(1 2 2 2 4 4 4)
#各种方块再box数组中的偏移
offsetBox=(0 1 3 5 7 11 15)
#每提高一个速度级需要积累的分数
iScoreEachLevel=50 #be greater than 7
#运行时数据
sig=0 #接收到的signal
iScore=0 #总分
iLevel=0 #速度级
boxNew=() #新下落的方块的位置定义
cBoxNew=0 #新下落的方块的颜色
iBoxNewType=0 #新下落的方块的种类
iBoxNewRotate=0 #新下落的方块的旋转角度
boxCur=() #当前方块的位置定义
cBoxCur=0 #当前方块的颜色
iBoxCurType=0 #当前方块的种类
iBoxCurRotate=0 #当前方块的旋转角度
boxCurX=-1 #当前方块的x坐标位置
boxCurY=-1 #当前方块的y坐标位置
iMap=() #背景方块图表
#初始化所有背景方块为-1, 表示没有方块
for ((i = 0; i < iTrayHeight * iTrayWidth; i++)); do
iMap[$i]=-1;
done
#
#
function DrawChars()
{
local chars x y char_color
chars="$1"
y=$2
x=$3
if [[ $# -gt 3 ]]; then
char_color=$4
echo -ne "\E[3${char_color}m"
fi
echo -ne "\E[${y};${x}H${chars}"
}
#接收输入的进程的主函数
function RunAsKeyReceiver()
{
local pidDisplayer key aKey sig cESC sTTY
pidDisplayer=$1
aKey=(0 0 0)
cESC=`echo -ne "\E"`
cSpace=`echo -ne "\L"`
#保存终端属性。在read -s读取终端键时,终端的属性会被暂时改变。
#如果在read -s时程序被不幸杀掉,可能会导致终端混乱,
#需要在程序退出时恢复终端属性。
sTTY=`stty -g`
#捕捉退出信号
trap "MyExit;" INT TERM
trap "MyExitNoSub;" $sigExit
#隐藏光标
echo -ne "\E[?25l"
while (( 1 )) ; do
#读取输入。注-s不回显,-n读到一个字符立即返回
read -s -n 1 key
aKey[0]=${aKey[1]}
aKey[1]=${aKey[2]}
aKey[2]=$key
sig=0
#判断输入了何种键
if [[ $key == $cESC && ${aKey[1]} == $cESC ]] ; then
#ESC键
MyExit
elif [[ ${aKey[0]} == $cESC && ${aKey[1]} == "[" ]] ; then
case $key in
"A") sig=$sigRotate ;; #<向上键>
"B") sig=$sigDown ;; #<向下键>
"D") sig=$sigLeft ;; #<向左键>
"C") sig=$sigRight ;; #<向右键>
*) ;;
esac
else
case $key in
W|w) sig=$sigRotate ;; #W, w
S|s) sig=$sigDown ;; #W, w
A|a) sig=$sigLeft ;; #W, w
D|d) sig=$sigRight ;; #W, w
"") sig=$sigAllDown;; #W, w
Q|q) MyExit ;; #W, w
*) ;;
esac
fi
if [[ $sig != 0 ]] ; then
#向另一进程发送消息
kill -$sig $pidDisplayer
fi
done
}
#退出前的恢复
function MyExitNoSub()
{
local y
#恢复终端属性
stty $sTTY
((y = iTop + iTrayHeight + 4))
#显示光标
echo -e "\E[?25h\E[${y};0H"
exit
}
function MyExit()
{
#通知显示进程需要退出
kill -$sigExit $pidDisplayer
MyExitNoSub
}
#处理显示和游戏流程的主函数
function RunAsDisplayer()
{
local sigThis
#
InitDraw
#挂载各种信号的处理函数
trap "sig=$sigRotate;" $sigRotate
trap "sig=$sigLeft;" $sigLeft
trap "sig=$sigRight;" $sigRight
trap "sig=$sigDown;" $sigDown
trap "sig=$sigAllDown;" $sigAllDown
trap "ShowExit;" $sigExit
while (( 1 )) ; do
#根据当前的速度级iLevel不同,设定相应的循环的次数
for ((i = 0; i < 21 - iLevel; i++)) ; do
sleep 0.02
sigThis=$sig
sig=0
#根sig变量判断是否接受到相应的信号
case $sigThis in
$sigRotate) BoxRotate ;; #旋转
$sigLeft) BoxLeft ;; #左移一列
$sigRight) BoxRight ;; #右移一列
$sigDown) BoxDown ;; #下落一行
$sigAllDown) BoxAllDown ;; #下落到底
*) ;;
esac
done
#kill -$sigDown $$
BoxDown #下落一行
done
}
#BoxMove(y, x), 测试是否可以把移动中的方块移到(x, y)的位置,
#返回0则可以, 1不可以
function BoxMove()
{
local j i x y xTest yTest
yTest=$1
xTest=$2
for ((j = 0; j < 8; j += 2)) ; do
((i = j + 1))
((y = ${boxCur[$j]} + yTest))
((x = ${boxCur[$i]} + xTest))
#撞到墙壁了
if (( y < 0 || y >= iTrayHeight || x < 0 || x >= iTrayWidth)) ; then
return 1
fi
#撞到其他已经存在的方块了
if ((${iMap[y * iTrayWidth + x]} != -1 )) ; then
return 1
fi
done
return 0;
}
#将当前移动中的方块放到背景方块中去,
#并计算新的分数和速度级。(即一次方块落到底部)
function Box2Map()
{
local j i x y xp yp line
#将当前移动中的方块放到背景方块中去
for ((j = 0; j < 8; j += 2)) ;do
((i = j + 1))
((y = ${boxCur[$j]} + boxCurY))
((x = ${boxCur[$i]} + boxCurX))
((i = y * iTrayWidth + x))
iMap[$i]=$cBoxCur
done
#消去可被消去的行
line=0
for ((j = 0; j < iTrayWidth * iTrayHeight; j += iTrayWidth)) ; do
for ((i = j + iTrayWidth - 1; i >= j; i--)) ; do
if ((${iMap[$i]} == -1)); then break; fi
done
if ((i >= j)); then continue; fi
((line++))
for ((i = j - 1; i >= 0; i--)) ;do
((x = i + iTrayWidth))
iMap[$x]=${iMap[$i]}
done
for ((i = 0; i < iTrayWidth; i++)) ;do
iMap[$i]=-1
done
done
if ((line == 0)); then return; fi
#根据消去的行数line计算分数和速度级
((x = iLeft + iTrayWidth * 2 + 7))
((y = iTop + 11))
((iScore += line * 2 - 1))
#显示新的分数
echo -ne "\E[1m"
DrawChars "${iScore} " ${y} ${x} ${cScorevalue}
if ((iScore % iScoreEachLevel < line * 2 - 1)) ; then
if ((iLevel < 20)) ; then
((iLevel++))
((y = iTop + 14))
#显示新的速度级
DrawChars "${iLevel} " ${y} ${x} ${cScorevalue}
fi
fi
echo -ne "\E[0m"
#重新显示背景方块
for ((y = 0; y < iTrayHeight; y++)) ; do
((yp = y + iTrayTop + 1))
((xp = iTrayLeft + 1))
((i = y * iTrayWidth))
DrawChars "" ${yp} ${xp}
# echo -ne "\E[${yp};${xp}H"
for ((x = 0; x < iTrayWidth; x++)) ; do
((j = i + x))
if ((${iMap[$j]} == -1)) ; then
echo -ne " "
else
echo -ne "\E[1m\E[7m\E[3${iMap[$j]}m\E[4${iMap[$j]}m[]\E[0m"
fi
done
done
}
#下落一行
function BoxDown()
{
local y s
((y = boxCurY + 1)) #新的y坐标
if BoxMove $y $boxCurX #测试是否可以下落一行
then
s="`DrawCurBox 0`" #将旧的方块抹去
((boxCurY = y))
s="$s`DrawCurBox 1`" #显示新的下落后方块
echo -ne $s
else
#走到这儿, 如果不能下落了
Box2Map #将当前移动中的iu方块贴到背景方块中
RandomBox #产生新的方块
fi
}
#左移一列
function BoxLeft()
{
local x s
((x = boxCurX - 1))
if BoxMove $boxCurY $x
then
s=`DrawCurBox 0`
((boxCurX = x))
s=$s`DrawCurBox 1`
echo -ne $s
fi
}
#右移一列
function BoxRight()
{
local x s
((x = boxCurX + 1))
if BoxMove $boxCurY $x
then
s=`DrawCurBox 0`
((boxCurX = x))
s=$s`DrawCurBox 1`
echo -ne $s
fi
}
#下落到底
function BoxAllDown()
{
local k j i x y iDown s
iDown=$iTrayHeight
#计算一共需要下落多少行
for ((j = 0; j < 8; j += 2))
do
((i = j + 1))
((y = ${boxCur[$j]} + boxCurY))
((x = ${boxCur[$i]} + boxCurX))
for ((k = y + 1; k < iTrayHeight; k++))
do
((i = k * iTrayWidth + x))
if (( ${iMap[$i]} != -1)); then break; fi
done
((k -= y + 1))
if (( $iDown > $k )); then iDown=$k; fi
done
s=`DrawCurBox 0` #将旧的方块抹去
((boxCurY += iDown))
s=$s`DrawCurBox 1` #显示新的下落后的方块
echo -ne $s
Box2Map #将当前移动中的方块贴到背景方块中
RandomBox #产生新的方块
}
#旋转方块
function BoxRotate()
{
local iCount iTestRotate boxTest j i s
iCount=${countBox[$iBoxCurType]} #当前的方块经旋转可以产生的样式的数目
#计算旋转后的新的样式
((iTestRotate = iBoxCurRotate + 1))
if ((iTestRotate >= iCount))
then
((iTestRotate = 0))
fi
#更新到新的样式, 保存老的样式(但不显示)
for ((j = 0, i = (${offsetBox[$iBoxCurType]} + $iTestRotate) * 8; j < 8; j++, i++))
do
boxTest[$j]=${boxCur[$j]}
boxCur[$j]=${box[$i]}
done
if BoxMove $boxCurY $boxCurX #测试旋转后是否有空间放的下
then
#抹去旧的方块
for ((j = 0; j < 8; j++))
do
boxCur[$j]=${boxTest[$j]}
done
s=`DrawCurBox 0`
#画上新的方块
for ((j = 0, i = (${offsetBox[$iBoxCurType]} + $iTestRotate) * 8; j < 8; j++, i++))
do
boxCur[$j]=${box[$i]}
done
s=$s`DrawCurBox 1`
echo -ne $s
iBoxCurRotate=$iTestRotate
else
#不能旋转,还是继续使用老的样式
for ((j = 0; j < 8; j++))
do
boxCur[$j]=${boxTest[$j]}
done
fi
}
#DrawCurBox(bDraw), 绘制当前移动中的方块, bDraw为1, 画上, bDraw为0, 抹去方块。
function DrawCurBox()
{
local i j t bDraw sBox s
bDraw=$1
s=""
if (( bDraw == 0 ))
then
sBox="\040\040"
else
sBox="[]"
s=$s"\E[1m\E[7m\E[3${cBoxCur}m\E[4${cBoxCur}m"
fi
for ((j = 0; j < 8; j += 2))
do
((i = iTrayTop + 1 + ${boxCur[$j]} + boxCurY))
((t = iTrayLeft + 1 + 2 * (boxCurX + ${boxCur[$j + 1]})))
#\E[y;xH, 光标到(x, y)处
s=$s"\E[${i};${t}H${sBox}"
done
s=$s"\E[0m"
echo -n $s
}
#更新新的方块
function RandomBox()
{
local i j t
#更新当前移动的方块
iBoxCurType=${iBoxNewType}
iBoxCurRotate=${iBoxNewRotate}
cBoxCur=${cBoxNew}
for ((j = 0; j < ${#boxNew[@]}; j++)) ; do
boxCur[$j]=${boxNew[$j]}
done
#显示当前移动的方块
if (( ${#boxCur[@]} == 8 )) ; then
#计算当前方块该从顶端哪一行"冒"出来
for ((j = 0, t = 4; j < 8; j += 2)) ;do
if ((${boxCur[$j]} < t)); then t=${boxCur[$j]}; fi
done
((boxCurY = -t))
for ((j = 1, i = -4, t = 20; j < 8; j += 2)) ; do
if ((${boxCur[$j]} > i)); then i=${boxCur[$j]}; fi
if ((${boxCur[$j]} < t)); then t=${boxCur[$j]}; fi
done
((boxCurX = (iTrayWidth - 1 - i - t) / 2))
#显示当前移动的方块
echo -ne `DrawCurBox 1`
#如果方块一出来就没处放,Game over!
if ! BoxMove $boxCurY $boxCurX ; then
kill -$sigExit ${PPID}
ShowExit
fi
fi
#清除右边预显示的方块
for ((j = 0; j < 4; j++)) ; do
((i = iTop + 1 + j))
((t = iLeft + 2 * iTrayWidth + 7))
echo -ne "\E[${i};${t}H "
done
#随机产生新的方块
((iBoxNewType = RANDOM % ${#offsetBox[@]}))
((iBoxNewRotate = RANDOM % ${countBox[$iBoxNewType]}))
for ((j = 0, i = (${offsetBox[$iBoxNewType]} + $iBoxNewRotate) * 8; j < 8; j++, i++)) ; do
boxNew[$j]=${box[$i]};
done
((cBoxNew = ${colorTable[RANDOM % ${#colorTable[@]}]}))
#显示右边预显示的方块
echo -ne "\E[1m\E[7m\E[3${cBoxNew}m\E[4${cBoxNew}m"
for ((j = 0; j < 8; j += 2)) ; do
((i = iTop + 1 + ${boxNew[$j]}))
((t = iLeft + 2 * iTrayWidth + 7 + 2 * ${boxNew[$j + 1]}))
echo -ne "\E[${i};${t}H[]"
done
echo -ne "\E[0m"
}
#初始绘制
function InitDraw()
{
local i t1 t2 t3
clear
RandomBox #随机产生方块,这时右边预显示窗口中有方快了
RandomBox #再随机产生方块,右边预显示窗口中的方块被更新,原先的方块将开始下落
#显示边框
echo -ne "\E[1m"
echo -ne "\E[3${cBorder}m\E[4${cBorder}m"
((t2 = iLeft + 1))
((t3 = iLeft + iTrayWidth * 2 + 3))
for ((i = 0; i < iTrayHeight; i++)) ; do
((t1 = i + iTop + 2))
DrawChars "||" ${t1} ${t2}
DrawChars "||" ${t1} ${t3}
done
((t2 = iTop + iTrayHeight + 2))
for ((i = 0; i < iTrayWidth + 2; i++)) ; do
((t1 = i * 2 + iLeft + 1))
DrawChars "==" ${iTrayTop} ${t1}
DrawChars "==" ${t2} ${t1}
done
echo -ne "\E[0m"
#显示"Score"和"Level"字样
echo -ne "\E[1m"
((t1 = iLeft + iTrayWidth * 2 + 7))
((t2 = iTop + 10))
DrawChars "Score" ${t2} ${t1} ${cScore}
((t2 = iTop + 11))
DrawChars $iScore ${t2} ${t1} ${cScorevalue}
((t2 = iTop + 13))
DrawChars "Level" ${t2} ${t1} ${cScore}
((t2 = iTop + 14))
DrawChars $iLevel ${t2} ${t1} ${cScorevalue}
echo -ne "\E[0m"
}
#退出时显示GameOVer!
function ShowExit()
{
local y
((y = iTrayHeight + iTrayTop + 3))
DrawChars "GameOver!" ${y} 0
exit
}
#游戏主程序在这儿开始.
if [[ $1 != "--show" ]] ; then
bash $0 --show& #以参数--show将本程序再运行一遍
RunAsKeyReceiver $! #以上一行产生的进程的进程号作为参数
exit
else
#当发现具有参数--show时,运行显示函数
RunAsDisplayer
exit
fi
| zzy-code-test | bash/tetris/tetris.sh | Shell | gpl2 | 13,753 |
<!DOCTYPE html>
<html>
<head>
<title>Binary to Hexadecimal and Hexadecimal to Binary Conversion Practice</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
/*
COLORS:
GRAY: #5E6E7B;
BLACK: #13253D;
YELLOW: #FEFF9F;
RED: #E8515B;
GREEN: #51E853;
PURPLE: #554359;
*/
* { padding: 0px; margin: 0px; }
body {
font-family: "Verdana", "Arial", sans-serif;
font-size: 11px;
text-align: auto;
background: #000;
color: #FEFF9F;
}
a {
color: #FEFF9F;
}
#footer {
text-align: center;
padding: 5px;
background: #554359;
}
#content {
width: 800px;
margin: 25px auto;
text-align: left;
background: #13253d;
}
h1 {
font-size: 14px;
text-align: center;
background: #554359;
}
h2 {
font-size: 13px;
}
h3 {
font-size: 12px;
}
p, h1, h2, h3 {
padding: 5px;
}
.notice {
font-style: italic;
}
input {
margin: 0px 5px;
}
textarea {
margin: 10px;
background: #5E6E7B;
border: 0px;
outline-width: 0px;
padding: 5px;
width: 760px;
color: #FEFF9F;
font-size: 12px;
}
input.text {
margin: 10px;
background: #5E6E7B;
border: 0px;
outline-width: 0px;
padding: 5px;
width: 760px;
line-height: 150%;
color: #FEFF9F;
font-size: 12px;
}
#problemContainer {
margin: 10px 0px;
}
#problemView {
font-size: 20px;
text-align: center;
background: #554359;
}
.right, .wrong {
display: inline-block;
font-size: 13px;
font-weight: bold;
margin: 10px 0px;
padding: 5px 15px;
}
.wrong {
color: #E8515B;
}
.right {
color: #51E853;
}
#solutionComparison {
padding: 10px;
background: #554359;
}
#problemView, .computedSolution, .userSolution, #solutionInput, textarea {
font-family: "Courier", monospace;
}
.hidden {
display: none !important;
}
</style>
</head>
<body>
<div id="content">
<h1>Binary to Hexadecimal and Hexadecimal to Binary Conversion Practice</h1>
<h2>Generate Problem:</h2>
<form id="problemGenerator">
<h3>Conversion Type</h3>
<p>
<input value="hexToBin" checked="checked" id="hexToBinary" type="radio" name="conversionType" /><label for="hexToBinary">Hex to Binary</label>
<input value="binToHex" id="binaryToHex" type="radio" name="conversionType" /><label for="binaryToHex">Binary to Hex</label>
</p>
<h3>Number of Bytes</h3>
<p>
<input id="oneByte" value="1" checked="checked" type="radio" name="numBytes" /><label for="oneByte">One byte</label>
<input id="twoBytes" value="2" type="radio" name="numBytes" /><label for="twoBytes">Two bytes</label>
<input id="threeBytes" value="3" type="radio" name="numBytes" /><label for="threeBytes">Three bytes</label>
<input id="fourBytes" value="4" type="radio" name="numBytes" /><label for="fourBytes">Four bytes</label>
</p>
<p><input type="submit" value="Generate Problem" name="Generate Problem" /></p>
</form>
<div id="problemContainer" class="hidden">
<h2>Problem:</h2>
<p id="problemView"></p>
</div>
<div id="workspaceContainer" class="hidden">
<h2>Check Solution</h2>
<form id="solutionChecker">
<h3>Scratch Pad</h3>
<p>
<label class="notice">Scratch pad form is not checked, just a place to work out your solution</label><br />
<textarea cols="100" rows="10" id="scratchPad"></textarea>
</p>
<p><a target="_blank" href="http://blog.apphackers.com/2010/02/26/binary-decimal-and-hexadecimal-conversion/">Conversion table</a></p>
<h3>Your Solution</h3>
<p>
<input class="text" type="text" id="solutionInput" />
</p>
<p class="notice">Please separate bytes with a space and add leading 0's so that hex bytes always have two digits and binary bytes have eight.</p>
<p><input type="submit" value="Check Solution" name="Check Solution" /></p>
</form>
</div>
<div id="solutionContainer" class="hidden">
<h2>Problem Solution</h2>
<p id="solutionView"></p>
</div>
<div id="footer">
Created by <a href="http://blog.apphackers.com">Apphacker</a> | <a href="http://code.google.com/p/computer-systems-book/source/checkout">Source</a>
</div>
</div>
<script type="text/javascript">
var conv;
conv = { };
conv.init = function ( ) {
conv.bindUI( );
};
conv.CONSTANTS = {
CONVERSION_TYPE: {
HEX_TO_BIN: "hexToBin",
BIN_TO_HEX: "binToHex"
}
};
conv.conversionType = null;
conv.generateProblem = function ( event ) {
var numBytes;
event.preventDefault( );
event.stopPropagation( );
conv.conversionType = null;
if ( $( "#oneByte" ).get( 0 ).checked === true ) {
numBytes = 1;
} else if ( $( "#twoBytes" ).get( 0 ).checked === true ) {
numBytes = 2;
} else if ( $( "#threeBytes" ).get( 0 ).checked === true ) {
numBytes = 3;
} else {
numBytes = 4;
}
if ( $( "#hexToBinary" ).get( 0 ).checked === true ) {
conv.conversionType = conv.CONSTANTS.CONVERSION_TYPE.HEX_TO_BIN;
conv.generateHexToBinProblem( numBytes );
} else {
conv.conversionType = conv.CONSTANTS.CONVERSION_TYPE.BIN_TO_HEX;
conv.generateBinToHexProblem( numBytes );
}
};
conv.problem = null;
conv.generateHexToBinProblem = function ( numBytes ) {
conv.generateAnyProblem( numBytes, 16 );
};
conv.generateBinToHexProblem = function ( numBytes ) {
conv.generateAnyProblem( numBytes, 2 );
};
conv.generateAnyProblem = function ( numBytes, base ) {
var problemR, i, val, problemHTML;
conv.clearWorkSpace( );
problemR = [ ];
problemHTML = [ ];
for ( i = 0; i < numBytes; i++ ) {
val = conv.getRandom( 0, 255 );
problemR.push( val );
val = val.toString( base );
if ( base === 16 && val.length === 1 ) {
val = "0" + val;
} else if( base === 2 ) {
while ( val.length < 8 ) {
val = "0" + val;
}
}
problemHTML.push( val )
}
conv.problem = problemR;
$( "#problemView" ).html( problemHTML.join( " " ) );
};
conv.getRandom = function ( min, max ) {
return Math.floor( Math.random( ) * ( max - min + 1 ) ) + min;
};
conv.getSolutionForProblem = function ( ) {
var i, problemString, val, base;
problemString = [ ];
if ( conv.conversionType === conv.CONSTANTS.CONVERSION_TYPE.BIN_TO_HEX ) {
base = 16;
} else {
base = 2;
}
for ( i = 0; i < conv.problem.length; i++ ) {
val = conv.problem[ i ];
val = val.toString( base );
if ( base === 16 && val.length === 1 ) {
val = "0" + val;
} else if( base === 2 ) {
while ( val.length < 8 ) {
val = "0" + val;
}
}
problemString.push( val )
}
return problemString.join( " " );
};
conv.clearWorkSpace = function ( ) {
conv.problem = null;
$( "#problemView" ).html( "" );
$( "#workspaceContainer" ).removeClass( "hidden" );
$( "#problemContainer" ).removeClass( "hidden" );
$( "#solutionContainer" ).addClass( "hidden" );
$( "#scratchPad" ).value = "";
$( "#solutionInput" ).value = "";
$( "#solutionView" ).html( "" );
};
conv.checkSolution = function ( event ) {
var solutionString, userSolution, returnHTML;
event.preventDefault( );
event.stopPropagation( );
returnHTML = [ ];
solutionString = conv.getSolutionForProblem( );
userSolution = $.trim( $( "#solutionInput" ).val( ) );
if ( userSolution.toLowerCase( ) === solutionString.toLowerCase( ) ) {
returnHTML.push( '<span class="right">Right answer.</span><br/>' );
} else {
returnHTML.push( '<span class="wrong">Wrong answer.</span><br/>' );
}
returnHTML.push( [
'<div id="solutionComparison">',
'<span class="computedSolution">',
solutionString,
' <-- computed solution.</span><br/>',
'<span class="userSolution">',
userSolution,
' <-- your solution.</span>',
'</div>'
].join( "" ) );
$( "#solutionView" ).html( returnHTML.join( "" ) );
$( "#solutionContainer" ).removeClass( "hidden" );
};
conv.bindUI = function ( ) {
$( "#problemGenerator" ).bind( "submit", conv.generateProblem );
$( "#solutionChecker" ).bind( "submit", conv.checkSolution );
};
$( document ).ready( conv.init );
</script>
</body>
</html>
| zzilcs-csapp2 | chapter_2/2_1/practice.html | HTML | mit | 8,207 |
#include <stdio.h>
int main ( ) {
int x = -1;
unsigned y = 0;
if ( x > (int) y ) {
printf( "x is greater than y" ); //this executes!
} else {
printf( "x is less than y" );
}
printf( "\n" );
return 1;
}
| zzilcs-csapp2 | chapter_2/2_20/test.c | C | mit | 227 |
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes( byte_pointer start, int len ) {
int i;
for ( i = 0; i < len; i++ ) {
printf( " %.2x", start[ i ] );
}
printf( "\n" );
}
void show_int ( int x ) {
show_bytes( ( byte_pointer ) &x, sizeof( int ) );
}
void show_float ( float x ) {
show_bytes( ( byte_pointer ) &x, sizeof( float ) );
}
void show_pointer ( void *x ) {
show_bytes( ( byte_pointer ) &x, sizeof( void * ) );
}
void test_show_bytes ( int val ) {
int ival = val;
float fval = ( float ) ival;
int *pval = &ival;
show_int( ival );
show_float( fval );
show_pointer( pval );
}
int main ( ) {
printf( "123456:\n" );
test_show_bytes( 12345 );
printf( "Little endian:\n" );
test_show_bytes( 0x12345678 );
}
| zzilcs-csapp2 | chapter_2/2_5/show_bytes.c | C | mit | 777 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ns3/core-module.h"
NS_LOG_COMPONENT_DEFINE ("ScratchSimulator");
using namespace ns3;
int
main (int argc, char *argv[])
{
NS_LOG_UNCOND ("Scratch Simulator");
}
| zy901002-gpsr | scratch/scratch-simulator.cc | C++ | gpl2 | 899 |
# topsort - dependency (topological) sorting and cycle finding functions
# Copyright (C) 2007 RADLogic
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;
# version 2.1 of the License.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# See http://www.fsf.org/licensing/licenses/lgpl.txt for full license text.
"""Provide toplogical sorting (i.e. dependency sorting) functions.
The topsort function is based on code posted on Usenet by Tim Peters.
Modifications:
- added doctests
- changed some bits to use current Python idioms
(listcomp instead of filter, +=/-=, inherit from Exception)
- added a topsort_levels version that ports items in each dependency level
into a sub-list
- added find_cycles to aid in cycle debugging
Run this module directly to run the doctests (unittests).
Make sure they all pass before checking in any modifications.
Requires Python >= 2.2
(For Python 2.2 also requires separate sets.py module)
This requires the rad_util.py module.
"""
# Provide support for Python 2.2*
from __future__ import generators
__version__ = '$Revision: 0.9 $'
__date__ = '$Date: 2007/03/27 04:15:26 $'
__credits__ = '''Tim Peters -- original topsort code
Tim Wegener -- doctesting, updating to current idioms, topsort_levels,
find_cycles
'''
# Make Python 2.3 sets look like Python 2.4 sets.
try:
set
except NameError:
from sets import Set as set
from rad_util import is_rotated
class CycleError(Exception):
"""Cycle Error"""
pass
def topsort(pairlist):
"""Topologically sort a list of (parent, child) pairs.
Return a list of the elements in dependency order (parent to child order).
>>> print topsort( [(1,2), (3,4), (5,6), (1,3), (1,5), (1,6), (2,5)] )
[1, 2, 3, 5, 4, 6]
>>> print topsort( [(1,2), (1,3), (2,4), (3,4), (5,6), (4,5)] )
[1, 2, 3, 4, 5, 6]
>>> print topsort( [(1,2), (2,3), (3,2)] )
Traceback (most recent call last):
CycleError: ([1], {2: 1, 3: 1}, {2: [3], 3: [2]})
"""
num_parents = {} # element -> # of predecessors
children = {} # element -> list of successors
for parent, child in pairlist:
# Make sure every element is a key in num_parents.
if not num_parents.has_key( parent ):
num_parents[parent] = 0
if not num_parents.has_key( child ):
num_parents[child] = 0
# Since child has a parent, increment child's num_parents count.
num_parents[child] += 1
# ... and parent gains a child.
children.setdefault(parent, []).append(child)
# Suck up everything without a parent.
answer = [x for x in num_parents.keys() if num_parents[x] == 0]
# For everything in answer, knock down the parent count on its children.
# Note that answer grows *in* the loop.
for parent in answer:
del num_parents[parent]
if children.has_key( parent ):
for child in children[parent]:
num_parents[child] -= 1
if num_parents[child] == 0:
answer.append( child )
# Following "del" isn't needed; just makes
# CycleError details easier to grasp.
del children[parent]
if num_parents:
# Everything in num_parents has at least one child ->
# there's a cycle.
raise CycleError(answer, num_parents, children)
return answer
def topsort_levels(pairlist):
"""Topologically sort a list of (parent, child) pairs into depth levels.
This returns a generator.
Turn this into a an iterator using the iter built-in function.
(if you iterate over the iterator, each element gets generated when
it is asked for, rather than generating the whole list up-front.)
Each generated element is a list of items at that dependency level.
>>> dependency_pairs = [(1,2), (3,4), (5,6), (1,3), (1,5), (1,6), (2,5)]
>>> for level in iter(topsort_levels( dependency_pairs )):
... print level
[1]
[2, 3]
[4, 5]
[6]
>>> dependency_pairs = [(1,2), (1,3), (2,4), (3,4), (5,6), (4,5)]
>>> for level in iter(topsort_levels( dependency_pairs )):
... print level
[1]
[2, 3]
[4]
[5]
[6]
>>> dependency_pairs = [(1,2), (2,3), (3,4), (4, 3)]
>>> try:
... for level in iter(topsort_levels( dependency_pairs )):
... print level
... except CycleError, exc:
... print 'CycleError:', exc
[1]
[2]
CycleError: ({3: 1, 4: 1}, {3: [4], 4: [3]})
The cycle error should look like.
CycleError: ({3: 1, 4: 1}, {3: [4], 4: [3]})
# todo: Make the doctest more robust (i.e. handle arbitrary dict order).
"""
num_parents = {} # element -> # of predecessors
children = {} # element -> list of successors
for parent, child in pairlist:
# Make sure every element is a key in num_parents.
if not num_parents.has_key( parent ):
num_parents[parent] = 0
if not num_parents.has_key( child ):
num_parents[child] = 0
# Since child has a parent, increment child's num_parents count.
num_parents[child] += 1
# ... and parent gains a child.
children.setdefault(parent, []).append(child)
return topsort_levels_core(num_parents, children)
def topsort_levels_core(num_parents, children):
"""Topologically sort a bunch of interdependent items based on dependency.
This returns a generator.
Turn this into a an iterator using the iter built-in function.
(if you iterate over the iterator, each element gets generated when
it is asked for, rather than generating the whole list up-front.)
Each generated element is a list of items at that dependency level.
>>> list(topsort_levels_core(
... {1: 0, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2},
... {1: [2, 3, 5, 6], 2: [5], 3: [4], 4: [], 5: [6]}))
[[1], [2, 3], [4, 5], [6]]
>>> list(topsort_levels_core(
... {1: 0, 2: 2, 3: 1},
... {1: [2], 2: [3], 3: [2]}))
Traceback (most recent call last):
CycleError: ({2: 1, 3: 1}, {2: [3], 3: [2]})
This function has a more complicated interface than topsort_levels,
but is useful if the data is easier to generate in this form.
Arguments:
num_parents -- key: item, value: number of parents (predecessors)
children -- key: item, value: list of children (successors)
"""
while 1:
# Suck up everything without a predecessor.
level_parents = [x for x in num_parents.keys() if num_parents[x] == 0]
if not level_parents:
break
# Offer the next generated item,
# which is a list of the items at this dependency level.
yield level_parents
# For everything item in this level,
# decrement the parent count,
# since we have accounted for its parent.
for level_parent in level_parents:
del num_parents[level_parent]
if children.has_key(level_parent):
for level_parent_child in children[level_parent]:
num_parents[level_parent_child] -= 1
del children[level_parent]
if num_parents:
# Everything in num_parents has at least one child ->
# there's a cycle.
raise CycleError(num_parents, children)
else:
# This is the end of the generator.
raise StopIteration
def find_cycles(parent_children):
"""Yield cycles. Each result is a list of items comprising a cycle.
Use a 'stack' based approach to find all the cycles.
This is a generator, so yields each cycle as it finds it.
It is implicit that the last item in each cycle list is a parent of the
first item (thereby forming a cycle).
Arguments:
parent_children -- parent -> collection of children
Simplest cycle:
>>> cycles = list(find_cycles({'A': ['B'], 'B': ['A']}))
>>> len(cycles)
1
>>> cycle = cycles[0]
>>> cycle.sort()
>>> print cycle
['A', 'B']
Simplest cycle with extra baggage at the start and the end:
>>> cycles = list(find_cycles(parent_children={'A': ['B'],
... 'B': ['C'],
... 'C': ['B', 'D'],
... 'D': [],
... }))
>>> len(cycles)
1
>>> cycle = cycles[0]
>>> cycle.sort()
>>> print cycle
['B', 'C']
Double cycle:
>>> cycles = list(find_cycles(parent_children={'A': ['B'],
... 'B': ['C1', 'C2'],
... 'C1': ['D1'],
... 'D1': ['E1'],
... 'E1': ['D1'],
... 'C2': ['D2'],
... 'D2': ['E2'],
... 'E2': ['D2'],
... }))
>>> len(cycles)
2
>>> for cycle in cycles:
... cycle.sort()
>>> cycles.sort()
>>> cycle1 = cycles[0]
>>> cycle1.sort()
>>> print cycle1
['D1', 'E1']
>>> cycle2 = cycles[1]
>>> cycle2.sort()
>>> print cycle2
['D2', 'E2']
Simple cycle with children not specified for one item:
# todo: Should this barf instead?
>>> cycles = list(find_cycles(parent_children={'A': ['B'],
... 'B': ['A'],
... 'C': ['D']}))
>>> len(cycles)
1
>>> cycle = cycles[0]
>>> cycle.sort()
>>> print cycle
['A', 'B']
Diamond cycle
>>> cycles = list(find_cycles(parent_children={'A': ['B1', 'B2'],
... 'B1': ['C'],
... 'B2': ['C'],
... 'C': ['A', 'B1']}))
>>> len(cycles)
3
>>> sorted_cycles = []
>>> for cycle in cycles:
... cycle = list(cycle)
... cycle.sort()
... sorted_cycles.append(cycle)
>>> sorted_cycles.sort()
>>> for cycle in sorted_cycles:
... print cycle
['A', 'B1', 'C']
['A', 'B2', 'C']
['B1', 'C']
Hairy case (order can matter if something is wrong):
(Note order of B and C in the list.)
>>> cycles = list(find_cycles(parent_children={
... 'TD': ['DD'],
... 'TC': ['DC'],
... 'DC': ['DQ'],
... 'C': ['DQ'],
... 'DQ': ['IA', 'TO'],
... 'IA': ['A'],
... 'A': ['B', 'C'],
... }))
>>> len(cycles)
1
>>> cycle = cycles[0]
>>> cycle.sort()
>>> print cycle
['A', 'C', 'DQ', 'IA']
"""
cycles = []
visited_nodes = set()
for parent in parent_children:
if parent in visited_nodes:
# This node is part of a path that has already been traversed.
continue
paths = [[parent]]
while paths:
path = paths.pop()
parent = path[-1]
try:
children = parent_children[parent]
except KeyError:
continue
for child in children:
# Keeping a set of the path nodes, for O(1) lookups at the
# expense of more memory and complexity, actually makes speed
# worse. (Due to construction of sets.)
# This is O(N).
if child in path:
# This is a cycle.
cycle = path[path.index(child):]
# Check that this is not a dup cycle.
is_dup = False
for other_cycle in cycles:
if is_rotated(other_cycle, cycle):
is_dup = True
break
if not is_dup:
cycles.append(cycle)
yield cycle
else:
# Push this new path onto the 'stack'.
# This is probably the most expensive part of the algorithm
# (a list copy).
paths.append(path + [child])
# Mark the node as visited.
visited_nodes.add(child)
if __name__ == '__main__':
# Run the doctest tests.
import sys
import doctest
doctest.testmod(sys.modules['__main__'])
| zy901002-gpsr | bindings/python/topsort.py | Python | gpl2 | 13,288 |
#! /usr/bin/env python
import sys
import os.path
import pybindgen.settings
from pybindgen.gccxmlparser import ModuleParser, PygenClassifier, PygenSection, WrapperWarning, find_declaration_from_name
from pybindgen.typehandlers.codesink import FileCodeSink
from pygccxml.declarations import templates
from pygccxml.declarations.enumeration import enumeration_t
from pygccxml.declarations.class_declaration import class_t
from pygccxml.declarations.calldef import free_function_t, member_function_t, constructor_t, calldef_t
## we need the smart pointer type transformation to be active even
## during gccxml scanning.
import ns3modulegen_core_customizations
## silence gccxmlparser errors; we only want error handling in the
## generated python script, not while scanning.
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, dummy_wrapper, dummy_exception, dummy_traceback_):
return True
pybindgen.settings.error_handler = ErrorHandler()
import warnings
warnings.filterwarnings(category=WrapperWarning, action='ignore')
import ns3modulescan
type_annotations = ns3modulescan.type_annotations
def get_ns3_relative_path(path):
l = []
head = path
while head:
new_head, tail = os.path.split(head)
if new_head == head:
raise ValueError
head = new_head
if tail == 'ns3':
return os.path.join(*l)
l.insert(0, tail)
raise AssertionError("is the path %r inside ns3?!" % path)
class PreScanHook:
def __init__(self, headers_map, module):
self.headers_map = headers_map
self.module = module
def __call__(self, module_parser,
pygccxml_definition,
global_annotations,
parameter_annotations):
try:
ns3_header = get_ns3_relative_path(pygccxml_definition.location.file_name)
except ValueError: # the header is not from ns3
return # ignore the definition, it's not ns-3 def.
definition_module = self.headers_map[ns3_header]
## Note: we don't include line numbers in the comments because
## those numbers are very likely to change frequently, which would
## cause needless changes, since the generated python files are
## kept under version control.
#global_annotations['pygen_comment'] = "%s:%i: %s" % \
# (ns3_header, pygccxml_definition.location.line, pygccxml_definition)
global_annotations['pygen_comment'] = "%s (module %r): %s" % \
(ns3_header, definition_module, pygccxml_definition)
## handle ns3::Object::GetObject (left to its own devices,
## pybindgen will generate a mangled name containing the template
## argument type name).
if isinstance(pygccxml_definition, member_function_t) \
and pygccxml_definition.parent.name == 'Object' \
and pygccxml_definition.name == 'GetObject':
template_args = templates.args(pygccxml_definition.demangled_name)
if template_args == ['ns3::Object']:
global_annotations['template_instance_names'] = 'ns3::Object=>GetObject'
## Don't wrap Simulator::Schedule* (manually wrapped)
if isinstance(pygccxml_definition, member_function_t) \
and pygccxml_definition.parent.name == 'Simulator' \
and pygccxml_definition.name.startswith('Schedule'):
global_annotations['ignore'] = None
# manually wrapped
if isinstance(pygccxml_definition, member_function_t) \
and pygccxml_definition.parent.name == 'Simulator' \
and pygccxml_definition.name == 'Run':
global_annotations['ignore'] = True
## http://www.gccxml.org/Bug/view.php?id=9915
if isinstance(pygccxml_definition, calldef_t):
for arg in pygccxml_definition.arguments:
if arg.default_value is None:
continue
elif arg.default_value == "ns3::MilliSeconds( )":
arg.default_value = "ns3::MilliSeconds(0)"
elif arg.default_value == "ns3::Seconds( )":
arg.default_value = "ns3::Seconds(0)"
## classes
if isinstance(pygccxml_definition, class_t):
print >> sys.stderr, pygccxml_definition
# no need for helper classes to allow subclassing in Python, I think...
#if pygccxml_definition.name.endswith('Helper'):
# global_annotations['allow_subclassing'] = 'false'
#
# If a class is template instantiation, even if the
# template was defined in some other module, if a template
# argument belongs to this module then the template
# instantiation will belong to this module.
#
if templates.is_instantiation(pygccxml_definition.decl_string):
cls_name, template_parameters = templates.split(pygccxml_definition.name)
template_parameters_decls = [find_declaration_from_name(module_parser.global_ns, templ_param)
for templ_param in template_parameters]
#print >> sys.stderr, "********************", cls_name, repr(template_parameters_decls)
template_parameters_modules = []
for templ in template_parameters_decls:
if not hasattr(templ, 'location'):
continue
try:
h = get_ns3_relative_path(templ.location.file_name)
except ValueError:
continue
template_parameters_modules.append(self.headers_map[h])
for templ_mod in template_parameters_modules:
if templ_mod == self.module:
definition_module = templ_mod
break
#print >> sys.stderr, "********************", cls_name, repr(template_parameters_modules)
if definition_module != self.module:
global_annotations['import_from_module'] = 'ns.%s' % (definition_module.replace('-', '_'),)
if pygccxml_definition.decl_string.startswith('::ns3::SimpleRefCount<'):
global_annotations['incref_method'] = 'Ref'
global_annotations['decref_method'] = 'Unref'
global_annotations['peekref_method'] = 'GetReferenceCount'
global_annotations['automatic_type_narrowing'] = 'true'
return
if pygccxml_definition.decl_string.startswith('::ns3::Callback<'):
# manually handled in ns3modulegen_core_customizations.py
global_annotations['ignore'] = None
return
if pygccxml_definition.decl_string.startswith('::ns3::TracedCallback<'):
global_annotations['ignore'] = None
return
if pygccxml_definition.decl_string.startswith('::ns3::Ptr<'):
# handled by pybindgen "type transformation"
global_annotations['ignore'] = None
return
# table driven class customization
try:
annotations = type_annotations[pygccxml_definition.decl_string]
except KeyError:
pass
else:
global_annotations.update(annotations)
## enums
if isinstance(pygccxml_definition, enumeration_t):
if definition_module != self.module:
global_annotations['import_from_module'] = 'ns.%s' % definition_module
## free functions
if isinstance(pygccxml_definition, free_function_t):
if definition_module != self.module:
global_annotations['ignore'] = None
return
if pygccxml_definition.name == 'PeekPointer':
global_annotations['ignore'] = None
return
## table driven methods/constructors/functions customization
if isinstance(pygccxml_definition, (free_function_t, member_function_t, constructor_t)):
try:
annotations = type_annotations[str(pygccxml_definition)]
except KeyError:
pass
else:
for key,value in annotations.items():
if key == 'params':
parameter_annotations.update (value)
del annotations['params']
global_annotations.update(annotations)
# def post_scan_hook(dummy_module_parser, dummy_pygccxml_definition, pybindgen_wrapper):
# ## classes
# if isinstance(pybindgen_wrapper, CppClass):
# if pybindgen_wrapper.name.endswith('Checker'):
# print >> sys.stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", pybindgen_wrapper
# #pybindgen_wrapper.set_instance_creation_function(AttributeChecker_instance_creation_function)
def scan_callback_classes(module_parser, callback_classes_file):
callback_classes_file.write("callback_classes = [\n")
for cls in module_parser.module_namespace.classes(function=module_parser.location_filter,
recursive=False):
if not cls.name.startswith("Callback<"):
continue
assert templates.is_instantiation(cls.decl_string), "%s is not a template instantiation" % cls
dummy_cls_name, template_parameters = templates.split(cls.decl_string)
callback_classes_file.write(" %r,\n" % template_parameters)
callback_classes_file.write("]\n")
def ns3_module_scan(top_builddir, module_name, headers_map, output_file_name, cflags):
module_parser = ModuleParser('ns.%s' % module_name.replace('-', '_'), 'ns3')
module_parser.add_pre_scan_hook(PreScanHook(headers_map, module_name))
#module_parser.add_post_scan_hook(post_scan_hook)
gccxml_options = dict(
include_paths=[top_builddir],
define_symbols={
#'NS3_ASSERT_ENABLE': None,
#'NS3_LOG_ENABLE': None,
},
cflags=('--gccxml-cxxflags "%s -DPYTHON_SCAN"' % cflags)
)
try:
os.unlink(output_file_name)
except OSError:
pass
try:
os.makedirs(os.path.dirname(output_file_name))
except OSError:
pass
output_file = open(output_file_name, "wt")
output_sink = FileCodeSink(output_file)
# if there exists a scan-header.h file in src/<module>/bindings,
# scan it, otherwise scan ns3/xxxx-module.h.
scan_header = os.path.join(os.path.dirname(output_file_name), "scan-header.h")
if not os.path.exists(scan_header):
scan_header = os.path.join(top_builddir, "ns3", "%s-module.h" % module_name)
module_parser.parse_init([scan_header],
None, whitelist_paths=[top_builddir],
#includes=['"ns3/everything.h"'],
pygen_sink=output_sink,
gccxml_options=gccxml_options)
module_parser.scan_types()
callback_classes_file = open(os.path.join(os.path.dirname(output_file_name), "callbacks_list.py"), "wt")
scan_callback_classes(module_parser, callback_classes_file)
callback_classes_file.close()
module_parser.scan_methods()
module_parser.scan_functions()
module_parser.parse_finalize()
output_file.close()
os.chmod(output_file_name, 0400)
if __name__ == '__main__':
if len(sys.argv) != 6:
print "ns3modulescan-modular.py top_builddir module_path module_headers output_file_name cflags"
sys.exit(1)
ns3_module_scan(sys.argv[1], sys.argv[2], eval(sys.argv[3]), sys.argv[4], sys.argv[5])
sys.exit(0)
| zy901002-gpsr | bindings/python/ns3modulescan-modular.py | Python | gpl2 | 11,846 |
LOCAL_MODULES = [
#'my_extra_api_definitions',
]
import sys
import os
sys.path.insert(0, sys.argv[2])
from pybindgen import FileCodeSink, write_preamble
from pybindgen.module import MultiSectionFactory
import pybindgen.settings
pybindgen.settings.deprecated_virtuals = False
from ns3modulegen_generated import module_init, register_types, register_methods, register_functions
import ns3modulegen_core_customizations
import callbacks_list
import traceback
this_script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
print >> sys.stderr
print >> sys.stderr, "---- location:"
traceback.print_stack()
print >> sys.stderr, "---- error:"
traceback.print_tb(traceback_)
try:
stack = wrapper.stack_where_defined
except AttributeError:
print >> sys.stderr, "??:??: %s / %r" % (wrapper, exception)
else:
stack = list(stack)
stack.reverse()
for (filename, line_number, function_name, text) in stack:
file_dir = os.path.dirname(os.path.abspath(filename))
if file_dir.startswith(this_script_dir):
print >> sys.stderr, "%s:%i: %r" % (os.path.join("..", "bindings", "python", os.path.basename(filename)),
line_number, exception)
break
return True
pybindgen.settings.error_handler = ErrorHandler()
pybindgen.settings.wrapper_registry = pybindgen.settings.StdMapWrapperRegistry
class MyMultiSectionFactory(MultiSectionFactory):
def __init__(self, main_file_name, modules):
super(MyMultiSectionFactory, self).__init__()
self.main_file_name = main_file_name
self.main_sink = FileCodeSink(open(main_file_name, "wt"))
self.header_name = "ns3module.h"
header_file_name = os.path.join(os.path.dirname(self.main_file_name), 'pch', self.header_name)
self.header_sink = FileCodeSink(open(header_file_name, "wt"))
self.section_sinks = {'__main__': self.main_sink}
for module in modules:
section_name = 'ns3_module_%s' % module.replace('-', '_')
file_name = os.path.join(os.path.dirname(self.main_file_name), "%s.cc" % section_name)
sink = FileCodeSink(open(file_name, "wt"))
self.section_sinks[section_name] = sink
def get_section_code_sink(self, section_name):
return self.section_sinks[section_name]
def get_main_code_sink(self):
return self.main_sink
def get_common_header_code_sink(self):
return self.header_sink
def get_common_header_include(self):
return '"%s"' % self.header_name
def close(self):
self.header_sink.file.close()
self.main_sink.file.close()
for sink in self.section_sinks.itervalues():
sink.file.close()
def main():
out = MyMultiSectionFactory(sys.argv[1], sys.argv[3:])
root_module = module_init()
root_module.add_include('"everything.h"')
register_types(root_module)
ns3modulegen_core_customizations.Simulator_customizations(root_module)
ns3modulegen_core_customizations.CommandLine_customizations(root_module)
ns3modulegen_core_customizations.TypeId_customizations(root_module)
ns3modulegen_core_customizations.add_std_ofstream(root_module)
ns3modulegen_core_customizations.add_ipv4_address_tp_hash(root_module)
for local_module in LOCAL_MODULES:
mod = __import__(local_module)
mod.register_types(root_module)
ns3modulegen_core_customizations.generate_callback_classes(root_module.after_forward_declarations,
callbacks_list.callback_classes)
register_methods(root_module)
for local_module in LOCAL_MODULES:
mod = __import__(local_module)
mod.register_methods(root_module)
ns3modulegen_core_customizations.Object_customizations(root_module)
ns3modulegen_core_customizations.Attribute_customizations(root_module)
register_functions(root_module)
for local_module in LOCAL_MODULES:
mod = __import__(local_module)
mod.register_functions(root_module)
enabled_features = os.environ['NS3_ENABLED_FEATURES'].split(',')
# if GtkConfigStore support is disabled, disable the class wrapper
if 'GtkConfigStore' not in enabled_features:
try:
root_module.classes.remove(root_module['ns3::GtkConfigStore'])
except KeyError:
pass
# if no sqlite, the class SqliteDataOutput is disabled
if 'SqliteDataOutput' not in enabled_features:
try:
root_module.classes.remove(root_module['ns3::SqliteDataOutput'])
except KeyError:
pass
if 'Threading' not in enabled_features:
for clsname in ['SystemThread', 'SystemMutex', 'SystemCondition', 'CriticalSection',
'SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >']:
root_module.classes.remove(root_module['ns3::%s' % clsname])
if 'EmuNetDevice' not in enabled_features:
for clsname in ['EmuNetDevice', 'EmuHelper']:
root_module.classes.remove(root_module['ns3::%s' % clsname])
root_module.enums.remove(root_module['ns3::EmuNetDevice::EncapsulationMode'])
if 'RealTime' not in enabled_features:
for clsname in ['WallClockSynchronizer', 'RealtimeSimulatorImpl']:
root_module.classes.remove(root_module['ns3::%s' % clsname])
root_module.enums.remove(root_module['ns3::RealtimeSimulatorImpl::SynchronizationMode'])
if 'TapBridge' not in enabled_features:
for clsname in ['TapBridge', 'TapBridgeHelper', 'TapBridgeFdReader']:
root_module.classes.remove(root_module['ns3::%s' % clsname])
root_module.enums.remove(root_module['ns3::TapBridge::Mode'])
root_module.generate(out, '_ns3')
out.close()
if __name__ == '__main__':
if 0:
try:
import cProfile as profile
except ImportError:
main()
else:
print >> sys.stderr, "** running under profiler"
profile.run('main()', 'ns3modulegen.pstat')
else:
main()
| zy901002-gpsr | bindings/python/ns3modulegen.py | Python | gpl2 | 6,413 |
from pybindgen import Module, FileCodeSink, write_preamble, param, retval
def register_types(module):
module.add_class('MyClass')
def register_methods(root_module):
MyClass = root_module['MyClass']
MyClass.add_constructor([], visibility='public')
MyClass.add_constructor([param('double', 's'), param('double', 'l'), param('double', 'mean')], visibility='public')
def register_functions(module):
module.add_function('SomeFunction', 'int', [param('int', 'xpto')])
| zy901002-gpsr | bindings/python/my_extra_api_definitions.py | Python | gpl2 | 490 |
import warnings
import sys
import os
import pybindgen.settings
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
from pybindgen.module import MultiSectionFactory
import ns3modulegen_core_customizations
pybindgen.settings.wrapper_registry = pybindgen.settings.StdMapWrapperRegistry
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
return True
pybindgen.settings.error_handler = ErrorHandler()
#print >> sys.stderr, ">>>>>>>>>>>>>>>>>>>>>>>>>>>> ", bool(eval(os.environ["GCC_RTTI_ABI_COMPLETE"]))
pybindgen.settings.gcc_rtti_abi_complete = bool(eval(os.environ["GCC_RTTI_ABI_COMPLETE"]))
class MyMultiSectionFactory(MultiSectionFactory):
def __init__(self, main_file_name):
super(MyMultiSectionFactory, self).__init__()
self.main_file_name = main_file_name
self.main_sink = FileCodeSink(open(main_file_name, "wt"))
self.header_name = "ns3module.h"
header_file_name = os.path.join(os.path.dirname(self.main_file_name), self.header_name)
#print >> sys.stderr, ">>>>>>>>>>>>>>>>>", header_file_name, main_file_name
self.header_sink = FileCodeSink(open(header_file_name, "wt"))
def get_section_code_sink(self, section_name):
return self.main_sink
def get_main_code_sink(self):
return self.main_sink
def get_common_header_code_sink(self):
return self.header_sink
def get_common_header_include(self):
return '"%s"' % self.header_name
def close(self):
self.header_sink.file.close()
self.main_sink.file.close()
def main(argv):
module_abs_src_path, target, extension_name, output_cc_file_name = argv[1:]
module_name = os.path.basename(module_abs_src_path)
out = MyMultiSectionFactory(output_cc_file_name)
sys.path.insert(0, os.path.join(module_abs_src_path, "bindings"))
try:
module_apidefs = __import__("modulegen__%s" % target)
del sys.modules["modulegen__%s" % target]
try:
module_customization = __import__("modulegen_customizations")
del sys.modules["modulegen_customizations"]
except ImportError:
module_customization = object()
try:
from callbacks_list import callback_classes
except ImportError, ex:
print >> sys.stderr, "***************", repr(ex)
callback_classes = []
else:
print >> sys.stderr, ">>>>>>>>>>>>>>>>", repr(callback_classes)
finally:
sys.path.pop(0)
root_module = module_apidefs.module_init()
root_module.set_name(extension_name)
root_module.add_include('"ns3/%s-module.h"' % module_name)
ns3modulegen_core_customizations.add_std_ios_openmode(root_module)
# -----------
module_apidefs.register_types(root_module)
if hasattr(module_customization, 'post_register_types'):
module_customization.post_register_types(root_module)
# register Callback<...> type handlers
ns3modulegen_core_customizations.generate_callback_classes(root_module.after_forward_declarations,
callback_classes)
# -----------
module_apidefs.register_methods(root_module)
if hasattr(module_customization, 'post_register_methods'):
module_customization.post_register_methods(root_module)
ns3modulegen_core_customizations.Object_customizations(root_module)
ns3modulegen_core_customizations.Attribute_customizations(root_module)
# -----------
module_apidefs.register_functions(root_module)
if hasattr(module_customization, 'post_register_functions'):
module_customization.post_register_functions(root_module)
# -----------
root_module.generate(out)
if __name__ == '__main__':
import sys
main(sys.argv)
| zy901002-gpsr | bindings/python/ns3modulegen-modular.py | Python | gpl2 | 3,971 |
# Copyright (c) 2007 RADLogic
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Provide various handy Python functions.
Running this script directly will execute the doctests.
Functions:
int2bin(i, n) -- Convert integer to binary string.
bin2int(bin_string) -- Convert binary string to integer.
reverse(input_string) -- Reverse a string.
transpose(matrix) -- Transpose a list of lists.
polygon_area(points_list) -- Calculate the area of an arbitrary polygon.
timestamp() -- Return string containing current time stamp.
pt2str(point) -- Return prettier string version of point tuple.
gcf(a, b) -- Return the greatest common factor of two numbers.
lcm(a, b) -- Return the least common multiple of two numbers.
permutations(input_list) -- Generate all permutations of a list of items.
reduce_fraction(fraction) -- Reduce fraction (num, denom) to simplest form.
quantile(l, p) -- Return p quantile of list l. E.g. p=0.25 for q1.
trim(l) -- Discard values in list more than 1.5*IQR outside IQR.
nice_units(value) -- Return value converted to human readable units.
uniquify(seq) -- Return sequence with duplicate items in sequence seq removed.
reverse_dict(d) -- Return the dictionary with the items as keys and vice-versa.
lsb(x, n) -- Return the n least significant bits of x.
gray_encode(i) -- Gray encode the given integer.
random_vec(bits, max_value=None) -- Return a random binary vector.
binary_range(bits) -- Return list of all possible binary numbers width=bits.
float_range([start], stop, [step]) -- Return range of floats.
find_common_fixes(s1, s2) -- Find common (prefix, suffix) of two strings.
is_rotated(seq1, seq2) -- Return true if the list is a rotation of other list.
getmodule(obj) -- Return the module that contains the object definition of obj.
(use inspect.getmodule instead, though)
get_args(argv) -- Store command-line args in a dictionary.
This module requires Python >= 2.2
"""
__author__ = 'Tim Wegener <twegener@radlogic.com.au>'
__date__ = '$Date: 2007/03/27 03:15:06 $'
__version__ = '$Revision: 0.45 $'
__credits__ = """
David Chandler, for polygon area algorithm.
(http://www.davidchandler.com/AreaOfAGeneralPolygon.pdf)
"""
import re
import sys
import time
import random
try:
True, False
except NameError:
True, False = (1==1, 0==1)
def int2bin(i, n):
"""Convert decimal integer i to n-bit binary number (string).
>>> int2bin(0, 8)
'00000000'
>>> int2bin(123, 8)
'01111011'
>>> int2bin(123L, 8)
'01111011'
>>> int2bin(15, 2)
Traceback (most recent call last):
ValueError: Value too large for given number of bits.
"""
hex2bin = {'0': '0000', '1': '0001', '2': '0010', '3': '0011',
'4': '0100', '5': '0101', '6': '0110', '7': '0111',
'8': '1000', '9': '1001', 'a': '1010', 'b': '1011',
'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111'}
# Convert to hex then map each hex digit to binary equivalent.
result = ''.join([hex2bin[x] for x in hex(i).lower().replace('l','')[2:]])
# Shrink result to appropriate length.
# Raise an error if the value is changed by the truncation.
if '1' in result[:-n]:
raise ValueError("Value too large for given number of bits.")
result = result[-n:]
# Zero-pad if length longer than mapped result.
result = '0'*(n-len(result)) + result
return result
def bin2int(bin_string):
"""Convert binary number string to decimal integer.
Note: Python > v2 has int(bin_string, 2)
>>> bin2int('1111')
15
>>> bin2int('0101')
5
"""
## result = 0
## bin_list = list(bin_string)
## if len(filter(lambda x: x in ('1','0'), bin_list)) < len(bin_list):
## raise Exception ("bin2int: Error - not a binary number: %s"
## % bin_string)
## bit_list = map(int, bin_list)
## bit_list.reverse() # Make most significant bit have highest index.
## for bit_place in range(len(bit_list)):
## result = result + ((2**bit_place) * bit_list[bit_place])
## return result
return int(bin_string, 2)
def reverse(input_string):
"""Reverse a string. Useful for strings of binary numbers.
>>> reverse('abc')
'cba'
"""
str_list = list(input_string)
str_list.reverse()
return ''.join(str_list)
def transpose(matrix):
"""Transpose a list of lists.
>>> transpose([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']])
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]
>>> transpose([['a', 'b', 'c'], ['d', 'e', 'f']])
[['a', 'd'], ['b', 'e'], ['c', 'f']]
>>> transpose([['a', 'b'], ['d', 'e'], ['g', 'h']])
[['a', 'd', 'g'], ['b', 'e', 'h']]
"""
result = zip(*matrix)
# Convert list of tuples to list of lists.
# map is faster than a list comprehension since it is being used with
# a built-in function as an argument.
result = map(list, result)
return result
def polygon_area(points_list, precision=100):
"""Calculate area of an arbitrary polygon using an algorithm from the web.
Return the area of the polygon as a positive float.
Arguments:
points_list -- list of point tuples [(x0, y0), (x1, y1), (x2, y2), ...]
(Unclosed polygons will be closed automatically.
precision -- Internal arithmetic precision (integer arithmetic).
>>> polygon_area([(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 0), (0, 0)])
3.0
Credits:
Area of a General Polygon by David Chandler
http://www.davidchandler.com/AreaOfAGeneralPolygon.pdf
"""
# Scale up co-ordinates and convert them to integers.
for i in range(len(points_list)):
points_list[i] = (int(points_list[i][0] * precision),
int(points_list[i][1] * precision))
# Close polygon if not closed.
if points_list[-1] != points_list[0]:
points_list.append(points_list[0])
# Calculate area.
area = 0
for i in range(len(points_list)-1):
(x_i, y_i) = points_list[i]
(x_i_plus_1, y_i_plus_1) = points_list[i+1]
area = area + (x_i_plus_1 * y_i) - (y_i_plus_1 * x_i)
area = abs(area / 2)
# Unscale area.
area = float(area)/(precision**2)
return area
def timestamp():
"""Return string containing current time stamp.
Note: In Python 2 onwards can use time.asctime() with no arguments.
"""
return time.asctime()
def pt2str(point):
"""Return prettier string version of point tuple.
>>> pt2str((1.8, 1.9))
'(1.8, 1.9)'
"""
return "(%s, %s)" % (str(point[0]), str(point[1]))
def gcf(a, b, epsilon=1e-16):
"""Return the greatest common factor of a and b, using Euclidean algorithm.
Arguments:
a, b -- two numbers
If both numbers are integers return an integer result,
otherwise return a float result.
epsilon -- floats less than this magnitude are considered to be zero
(default: 1e-16)
Examples:
>>> gcf(12, 34)
2
>>> gcf(13.5, 4)
0.5
>>> gcf(-2, 4)
2
>>> gcf(5, 0)
5
By (a convenient) definition:
>>> gcf(0, 0)
0
"""
result = max(a, b)
remainder = min(a, b)
while remainder and abs(remainder) > epsilon:
new_remainder = result % remainder
result = remainder
remainder = new_remainder
return abs(result)
def lcm(a, b, precision=None):
"""Return the least common multiple of a and b, using the gcf function.
Arguments:
a, b -- two numbers. If both are integers return an integer result,
otherwise a return a float result.
precision -- scaling factor if a and/or b are floats.
>>> lcm(21, 6)
42
>>> lcm(2.5, 3.5)
17.5
>>> str(lcm(1.5e-8, 2.5e-8, precision=1e9))
'7.5e-08'
By (an arbitary) definition:
>>> lcm(0, 0)
0
"""
# Note: Dummy precision argument is for backwards compatibility.
# Do the division first.
# (See http://en.wikipedia.org/wiki/Least_common_multiple )
denom = gcf(a, b)
if denom == 0:
result = 0
else:
result = a * (b / denom)
return result
def permutations(input_list):
"""Return a list containing all permutations of the input list.
Note: This is a recursive function.
>>> perms = permutations(['a', 'b', 'c'])
>>> perms.sort()
>>> for perm in perms:
... print perm
['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['b', 'c', 'a']
['c', 'a', 'b']
['c', 'b', 'a']
"""
out_lists = []
if len(input_list) > 1:
# Extract first item in list.
item = input_list[0]
# Find all permutations of remainder of list. (Recursive call.)
sub_lists = permutations(input_list[1:])
# For every permutation of the sub list...
for sub_list in sub_lists:
# Insert the extracted first item at every position of the list.
for i in range(len(input_list)):
new_list = sub_list[:]
new_list.insert(i, item)
out_lists.append(new_list)
else:
# Termination condition: only one item in input list.
out_lists = [input_list]
return out_lists
def reduce_fraction(fraction):
"""Reduce fraction tuple to simplest form. fraction=(num, denom)
>>> reduce_fraction((14, 7))
(2, 1)
>>> reduce_fraction((-2, 4))
(-1, 2)
>>> reduce_fraction((0, 4))
(0, 1)
>>> reduce_fraction((4, 0))
(1, 0)
"""
(numerator, denominator) = fraction
common_factor = abs(gcf(numerator, denominator))
result = (numerator/common_factor, denominator/common_factor)
return result
def quantile(l, p):
"""Return p quantile of list l. E.g. p=0.25 for q1.
See:
http://rweb.stat.umn.edu/R/library/base/html/quantile.html
"""
l_sort = l[:]
l_sort.sort()
n = len(l)
r = 1 + ((n - 1) * p)
i = int(r)
f = r - i
if i < n:
result = (1-f)*l_sort[i-1] + f*l_sort[i]
else:
result = l_sort[i-1]
return result
def trim(l):
"""Discard values in list more than 1.5*IQR outside IQR.
(IQR is inter-quartile-range)
This function uses rad_util.quantile
1.5*IQR -- mild outlier
3*IQR -- extreme outlier
See:
http://wind.cc.whecn.edu/~pwildman/statnew/section_7_-_exploratory_data_analysis.htm
"""
l_sort = l[:]
l_sort.sort()
# Calculate medianscore (based on stats.py lmedianscore by Gary Strangman)
if len(l_sort) % 2 == 0:
# If even number of scores, average middle 2.
index = int(len(l_sort) / 2) # Integer division correct
median = float(l_sort[index] + l_sort[index-1]) / 2
else:
# int divsion gives mid value when count from 0
index = int(len(l_sort) / 2)
median = l_sort[index]
# Calculate IQR.
q1 = quantile(l_sort, 0.25)
q3 = quantile(l_sort, 0.75)
iqr = q3 - q1
iqr_extra = iqr * 1.5
def in_interval(x, i=iqr_extra, q1=q1, q3=q3):
return (x >= q1-i and x <= q3+i)
l_trimmed = [x for x in l_sort if in_interval(x)]
return l_trimmed
def nice_units(value, dp=0, sigfigs=None, suffix='', space=' ',
use_extra_prefixes=False, use_full_name=False, mode='si'):
"""Return value converted to human readable units eg milli, micro, etc.
Arguments:
value -- number in base units
dp -- number of decimal places to display (rounded)
sigfigs -- number of significant figures to display (rounded)
This overrides dp if set.
suffix -- optional unit suffix to append to unit multiplier
space -- seperator between value and unit multiplier (default: ' ')
use_extra_prefixes -- use hecto, deka, deci and centi as well if set.
(default: False)
use_full_name -- use full name for multiplier symbol,
e.g. milli instead of m
(default: False)
mode -- 'si' for SI prefixes, 'bin' for binary multipliers (1024, etc.)
(Default: 'si')
SI prefixes from:
http://physics.nist.gov/cuu/Units/prefixes.html
(Greek mu changed to u.)
Binary prefixes based on:
http://physics.nist.gov/cuu/Units/binary.html
>>> nice_units(2e-11)
'20 p'
>>> nice_units(2e-11, space='')
'20p'
"""
si_prefixes = {1e24: ('Y', 'yotta'),
1e21: ('Z', 'zetta'),
1e18: ('E', 'exa'),
1e15: ('P', 'peta'),
1e12: ('T', 'tera'),
1e9: ('G', 'giga'),
1e6: ('M', 'mega'),
1e3: ('k', 'kilo'),
1e-3: ('m', 'milli'),
1e-6: ('u', 'micro'),
1e-9: ('n', 'nano'),
1e-12: ('p', 'pico'),
1e-15: ('f', 'femto'),
1e-18: ('a', 'atto'),
1e-21: ('z', 'zepto'),
1e-24: ('y', 'yocto')
}
if use_extra_prefixes:
si_prefixes.update({1e2: ('h', 'hecto'),
1e1: ('da', 'deka'),
1e-1: ('d', 'deci'),
1e-2: ('c', 'centi')
})
bin_prefixes = {2**10: ('K', 'kilo'),
2**20: ('M', 'mega'),
2**30: ('G', 'mega'),
2**40: ('T', 'tera'),
2**50: ('P', 'peta'),
2**60: ('E', 'exa')
}
if mode == 'bin':
prefixes = bin_prefixes
else:
prefixes = si_prefixes
prefixes[1] = ('', '') # Unity.
# Determine appropriate multiplier.
multipliers = prefixes.keys()
multipliers.sort()
mult = None
for i in range(len(multipliers) - 1):
lower_mult = multipliers[i]
upper_mult = multipliers[i+1]
if lower_mult <= value < upper_mult:
mult_i = i
break
if mult is None:
if value < multipliers[0]:
mult_i = 0
elif value >= multipliers[-1]:
mult_i = len(multipliers) - 1
mult = multipliers[mult_i]
# Convert value for this multiplier.
new_value = value / mult
# Deal with special case due to rounding.
if sigfigs is None:
if mult_i < (len(multipliers) - 1) and \
round(new_value, dp) == \
round((multipliers[mult_i+1] / mult), dp):
mult = multipliers[mult_i + 1]
new_value = value / mult
# Concatenate multiplier symbol.
if use_full_name:
label_type = 1
else:
label_type = 0
# Round and truncate to appropriate precision.
if sigfigs is None:
str_value = eval('"%.'+str(dp)+'f" % new_value', locals(), {})
else:
str_value = eval('"%.'+str(sigfigs)+'g" % new_value', locals(), {})
return str_value + space + prefixes[mult][label_type] + suffix
def uniquify(seq, preserve_order=False):
"""Return sequence with duplicate items in sequence seq removed.
The code is based on usenet post by Tim Peters.
This code is O(N) if the sequence items are hashable, O(N**2) if not.
Peter Bengtsson has a blog post with an empirical comparison of other
approaches:
http://www.peterbe.com/plog/uniqifiers-benchmark
If order is not important and the sequence items are hashable then
list(set(seq)) is readable and efficient.
If order is important and the sequence items are hashable generator
expressions can be used (in py >= 2.4) (useful for large sequences):
seen = set()
do_something(x for x in seq if x not in seen or seen.add(x))
Arguments:
seq -- sequence
preserve_order -- if not set the order will be arbitrary
Using this option will incur a speed penalty.
(default: False)
Example showing order preservation:
>>> uniquify(['a', 'aa', 'b', 'b', 'ccc', 'ccc', 'd'], preserve_order=True)
['a', 'aa', 'b', 'ccc', 'd']
Example using a sequence of un-hashable items:
>>> uniquify([['z'], ['x'], ['y'], ['z']], preserve_order=True)
[['z'], ['x'], ['y']]
The sorted output or the non-order-preserving approach should equal
that of the sorted order-preserving approach output:
>>> unordered = uniquify([3, 3, 1, 2], preserve_order=False)
>>> unordered.sort()
>>> ordered = uniquify([3, 3, 1, 2], preserve_order=True)
>>> ordered.sort()
>>> ordered
[1, 2, 3]
>>> int(ordered == unordered)
1
"""
try:
# Attempt fast algorithm.
d = {}
if preserve_order:
# This is based on Dave Kirby's method (f8) noted in the post:
# http://www.peterbe.com/plog/uniqifiers-benchmark
return [x for x in seq if (x not in d) and not d.__setitem__(x, 0)]
else:
for x in seq:
d[x] = 0
return d.keys()
except TypeError:
# Have an unhashable object, so use slow algorithm.
result = []
app = result.append
for x in seq:
if x not in result:
app(x)
return result
# Alias to noun form for backward compatibility.
unique = uniquify
def reverse_dict(d):
"""Reverse a dictionary so the items become the keys and vice-versa.
Note: The results will be arbitrary if the items are not unique.
>>> d = reverse_dict({'a': 1, 'b': 2})
>>> d_items = d.items()
>>> d_items.sort()
>>> d_items
[(1, 'a'), (2, 'b')]
"""
result = {}
for key, value in d.items():
result[value] = key
return result
def lsb(x, n):
"""Return the n least significant bits of x.
>>> lsb(13, 3)
5
"""
return x & ((2 ** n) - 1)
def gray_encode(i):
"""Gray encode the given integer."""
return i ^ (i >> 1)
def random_vec(bits, max_value=None):
"""Generate a random binary vector of length bits and given max value."""
vector = ""
for _ in range(int(bits / 10) + 1):
i = int((2**10) * random.random())
vector += int2bin(i, 10)
if max_value and (max_value < 2 ** bits - 1):
vector = int2bin((int(vector, 2) / (2 ** bits - 1)) * max_value, bits)
return vector[0:bits]
def binary_range(bits):
"""Return a list of all possible binary numbers in order with width=bits.
It would be nice to extend it to match the
functionality of python's range() built-in function.
"""
l = []
v = ['0'] * bits
toggle = [1] + [0] * bits
while toggle[bits] != 1:
v_copy = v[:]
v_copy.reverse()
l.append(''.join(v_copy))
toggle = [1] + [0]*bits
i = 0
while i < bits and toggle[i] == 1:
if toggle[i]:
if v[i] == '0':
v[i] = '1'
toggle[i+1] = 0
else:
v[i] = '0'
toggle[i+1] = 1
i += 1
return l
def float_range(start, stop=None, step=None):
"""Return a list containing an arithmetic progression of floats.
Return a list of floats between 0.0 (or start) and stop with an
increment of step.
This is in functionality to python's range() built-in function
but can accept float increments.
As with range(), stop is omitted from the list.
"""
if stop is None:
stop = float(start)
start = 0.0
if step is None:
step = 1.0
cur = float(start)
l = []
while cur < stop:
l.append(cur)
cur += step
return l
def find_common_fixes(s1, s2):
"""Find common (prefix, suffix) of two strings.
>>> find_common_fixes('abc', 'def')
('', '')
>>> find_common_fixes('abcelephantdef', 'abccowdef')
('abc', 'def')
>>> find_common_fixes('abcelephantdef', 'abccow')
('abc', '')
>>> find_common_fixes('elephantdef', 'abccowdef')
('', 'def')
"""
prefix = []
suffix = []
i = 0
common_len = min(len(s1), len(s2))
while i < common_len:
if s1[i] != s2[i]:
break
prefix.append(s1[i])
i += 1
i = 1
while i < (common_len + 1):
if s1[-i] != s2[-i]:
break
suffix.append(s1[-i])
i += 1
suffix.reverse()
prefix = ''.join(prefix)
suffix = ''.join(suffix)
return (prefix, suffix)
def is_rotated(seq1, seq2):
"""Return true if the first sequence is a rotation of the second sequence.
>>> seq1 = ['A', 'B', 'C', 'D']
>>> seq2 = ['C', 'D', 'A', 'B']
>>> int(is_rotated(seq1, seq2))
1
>>> seq2 = ['C', 'D', 'B', 'A']
>>> int(is_rotated(seq1, seq2))
0
>>> seq1 = ['A', 'B', 'C', 'A']
>>> seq2 = ['A', 'A', 'B', 'C']
>>> int(is_rotated(seq1, seq2))
1
>>> seq2 = ['A', 'B', 'C', 'A']
>>> int(is_rotated(seq1, seq2))
1
>>> seq2 = ['A', 'A', 'C', 'B']
>>> int(is_rotated(seq1, seq2))
0
"""
# Do a sanity check.
if len(seq1) != len(seq2):
return False
# Look for occurrences of second sequence head item in first sequence.
start_indexes = []
head_item = seq2[0]
for index1 in range(len(seq1)):
if seq1[index1] == head_item:
start_indexes.append(index1)
# Check that wrapped sequence matches.
double_seq1 = seq1 + seq1
for index1 in start_indexes:
if double_seq1[index1:index1+len(seq1)] == seq2:
return True
return False
def getmodule(obj):
"""Return the module that contains the object definition of obj.
Note: Use inspect.getmodule instead.
Arguments:
obj -- python obj, generally a class or a function
Examples:
A function:
>>> module = getmodule(random.choice)
>>> module.__name__
'random'
>>> module is random
1
A class:
>>> module = getmodule(random.Random)
>>> module.__name__
'random'
>>> module is random
1
A class inheriting from a class in another module:
(note: The inheriting class must define at least one function.)
>>> class MyRandom(random.Random):
... def play(self):
... pass
>>> module = getmodule(MyRandom)
>>> if __name__ == '__main__':
... name = 'rad_util'
... else:
... name = module.__name__
>>> name
'rad_util'
>>> module is sys.modules[__name__]
1
Discussion:
This approach is slightly hackish, and won't work in various situations.
However, this was the approach recommended by GvR, so it's as good as
you'll get.
See GvR's post in this thread:
http://groups.google.com.au/group/comp.lang.python/browse_thread/thread/966a7bdee07e3b34/c3cab3f41ea84236?lnk=st&q=python+determine+class+module&rnum=4&hl=en#c3cab3f41ea84236
"""
if hasattr(obj, 'func_globals'):
func = obj
else:
# Handle classes.
func = None
for item in obj.__dict__.values():
if hasattr(item, 'func_globals'):
func = item
break
if func is None:
raise ValueError("No functions attached to object: %r" % obj)
module_name = func.func_globals['__name__']
# Get module.
module = sys.modules[module_name]
return module
def round_grid(value, grid, mode=0):
"""Round off the given value to the given grid size.
Arguments:
value -- value to be roudne
grid -- result must be a multiple of this
mode -- 0 nearest, 1 up, -1 down
Examples:
>>> round_grid(7.5, 5)
10
>>> round_grid(7.5, 5, mode=-1)
5
>>> round_grid(7.3, 5, mode=1)
10
>>> round_grid(7.3, 5.0, mode=1)
10.0
"""
off_grid = value % grid
if mode == 0:
add_one = int(off_grid >= (grid / 2.0))
elif mode == 1 and off_grid:
add_one = 1
elif mode == -1 and off_grid:
add_one = 0
result = ((int(value / grid) + add_one) * grid)
return result
def get_args(argv):
"""Store command-line args in a dictionary.
-, -- prefixes are removed
Items not prefixed with - or -- are stored as a list, indexed by 'args'
For options that take a value use --option=value
Consider using optparse or getopt (in Python standard library) instead.
"""
d = {}
args = []
for arg in argv:
if arg.startswith('-'):
parts = re.sub(r'^-+', '', arg).split('=')
if len(parts) == 2:
d[parts[0]] = parts[1]
else:
d[parts[0]] = None
else:
args.append(arg)
d['args'] = args
return d
if __name__ == '__main__':
import doctest
doctest.testmod(sys.modules['__main__'])
| zy901002-gpsr | bindings/python/rad_util.py | Python | gpl2 | 26,013 |
#! /usr/bin/env python
import sys
import os.path
import pybindgen.settings
from pybindgen.gccxmlparser import ModuleParser, PygenClassifier, PygenSection, WrapperWarning
from pybindgen.typehandlers.codesink import FileCodeSink
from pygccxml.declarations import templates
from pygccxml.declarations.class_declaration import class_t
from pygccxml.declarations.calldef import free_function_t, member_function_t, constructor_t, calldef_t
## we need the smart pointer type transformation to be active even
## during gccxml scanning.
import ns3modulegen_core_customizations
## silence gccxmlparser errors; we only want error handling in the
## generated python script, not while scanning.
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, dummy_wrapper, dummy_exception, dummy_traceback_):
return True
pybindgen.settings.error_handler = ErrorHandler()
import warnings
warnings.filterwarnings(category=WrapperWarning, action='ignore')
type_annotations = {
'::ns3::AttributeChecker': {
'automatic_type_narrowing': 'true',
'allow_subclassing': 'false',
},
'::ns3::AttributeValue': {
'automatic_type_narrowing': 'true',
'allow_subclassing': 'false',
},
'::ns3::CommandLine': {
'allow_subclassing': 'true', # needed so that AddValue is able to set attributes on the object
},
'::ns3::NscTcpL4Protocol': {
'ignore': 'true', # this class is implementation detail
},
'ns3::RandomVariable::RandomVariable(ns3::RandomVariableBase const & variable) [constructor]': {
'ignore': None,
},
'ns3::RandomVariableBase * ns3::RandomVariable::Peek() const [member function]': {
'ignore': None,
},
'void ns3::RandomVariable::GetSeed(uint32_t * seed) const [member function]': {
'params': {'seed':{'direction':'out',
'array_length':'6'}}
},
'bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInfo * info) const [member function]': {
'params': {'info':{'transfer_ownership': 'false'}}
},
'static bool ns3::TypeId::LookupByNameFailSafe(std::string name, ns3::TypeId * tid) [member function]': {
'ignore': None, # manually wrapped in
},
'bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]': {
'params': {'obj': {'transfer_ownership':'false'}}
},
'bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]': {
'params': {'obj': {'transfer_ownership':'false'}}
},
'bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]': {
'params': {'obj': {'transfer_ownership':'false'}}
},
'bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]': {
'params': {'obj': {'transfer_ownership':'false'}}
},
'bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]': {
'params': {'object': {'transfer_ownership':'false'}}
},
'ns3::EmpiricalVariable::EmpiricalVariable(ns3::RandomVariableBase const & variable) [constructor]': {
'ignore': None
},
'static ns3::AttributeList * ns3::AttributeList::GetGlobal() [member function]': {
'caller_owns_return': 'false'
},
'void ns3::CommandLine::Parse(int argc, char * * argv) const [member function]': {
'ignore': None # manually wrapped
},
'extern void ns3::PythonCompleteConstruct(ns3::Ptr<ns3::Object> object, ns3::TypeId typeId, ns3::AttributeList const & attributes) [free function]': {
'ignore': None # used transparently by, should not be wrapped
},
'ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4ListRouting::GetRoutingProtocol(uint32_t index, int16_t & priority) const [member function]': {
'params': {'priority':{'direction':'out'}}
},
'ns3::Ipv4RoutingTableEntry * ns3::GlobalRouter::GetInjectedRoute(uint32_t i) [member function]': {
'params': {'return': { 'caller_owns_return': 'false',}},
},
'ns3::Ipv4RoutingTableEntry * ns3::Ipv4GlobalRouting::GetRoute(uint32_t i) const [member function]': {
'params': {'return': { 'caller_owns_return': 'false',}},
},
'::ns3::TestCase': {
'ignore': 'true', # we don't need to write test cases in Python
},
'::ns3::TestRunner': {
'ignore': 'true', # we don't need to write test cases in Python
},
'::ns3::TestSuite': {
'ignore': 'true', # we don't need to write test cases in Python
},
}
def get_ns3_relative_path(path):
l = []
head = path
while head:
head, tail = os.path.split(head)
if tail == 'ns3':
return os.path.join(*l)
l.insert(0, tail)
raise AssertionError("is the path %r inside ns3?!" % path)
def pre_scan_hook(dummy_module_parser,
pygccxml_definition,
global_annotations,
parameter_annotations):
ns3_header = get_ns3_relative_path(pygccxml_definition.location.file_name)
## Note: we don't include line numbers in the comments because
## those numbers are very likely to change frequently, which would
## cause needless changes, since the generated python files are
## kept under version control.
#global_annotations['pygen_comment'] = "%s:%i: %s" % \
# (ns3_header, pygccxml_definition.location.line, pygccxml_definition)
global_annotations['pygen_comment'] = "%s: %s" % \
(ns3_header, pygccxml_definition)
## handle ns3::Object::GetObject (left to its own devices,
## pybindgen will generate a mangled name containing the template
## argument type name).
if isinstance(pygccxml_definition, member_function_t) \
and pygccxml_definition.parent.name == 'Object' \
and pygccxml_definition.name == 'GetObject':
template_args = templates.args(pygccxml_definition.demangled_name)
if template_args == ['ns3::Object']:
global_annotations['template_instance_names'] = 'ns3::Object=>GetObject'
## Don't wrap Simulator::Schedule* (manually wrapped)
if isinstance(pygccxml_definition, member_function_t) \
and pygccxml_definition.parent.name == 'Simulator' \
and pygccxml_definition.name.startswith('Schedule'):
global_annotations['ignore'] = None
# manually wrapped
if isinstance(pygccxml_definition, member_function_t) \
and pygccxml_definition.parent.name == 'Simulator' \
and pygccxml_definition.name == 'Run':
global_annotations['ignore'] = True
## http://www.gccxml.org/Bug/view.php?id=9915
if isinstance(pygccxml_definition, calldef_t):
for arg in pygccxml_definition.arguments:
if arg.default_value is None:
continue
if "ns3::MilliSeconds( )" == arg.default_value:
arg.default_value = "ns3::MilliSeconds(0)"
if "ns3::Seconds( )" == arg.default_value:
arg.default_value = "ns3::Seconds(0)"
## classes
if isinstance(pygccxml_definition, class_t):
# no need for helper classes to allow subclassing in Python, I think...
#if pygccxml_definition.name.endswith('Helper'):
# global_annotations['allow_subclassing'] = 'false'
if pygccxml_definition.decl_string.startswith('::ns3::SimpleRefCount<'):
global_annotations['incref_method'] = 'Ref'
global_annotations['decref_method'] = 'Unref'
global_annotations['peekref_method'] = 'GetReferenceCount'
global_annotations['automatic_type_narrowing'] = 'true'
return
if pygccxml_definition.decl_string.startswith('::ns3::Callback<'):
# manually handled in ns3modulegen_core_customizations.py
global_annotations['ignore'] = None
return
if pygccxml_definition.decl_string.startswith('::ns3::TracedCallback<'):
global_annotations['ignore'] = None
return
if pygccxml_definition.decl_string.startswith('::ns3::Ptr<'):
# handled by pybindgen "type transformation"
global_annotations['ignore'] = None
return
# table driven class customization
try:
annotations = type_annotations[pygccxml_definition.decl_string]
except KeyError:
pass
else:
global_annotations.update(annotations)
## free functions
if isinstance(pygccxml_definition, free_function_t):
if pygccxml_definition.name == 'PeekPointer':
global_annotations['ignore'] = None
return
## table driven methods/constructors/functions customization
if isinstance(pygccxml_definition, (free_function_t, member_function_t, constructor_t)):
try:
annotations = type_annotations[str(pygccxml_definition)]
except KeyError:
pass
else:
for key,value in annotations.items():
if key == 'params':
parameter_annotations.update (value)
del annotations['params']
global_annotations.update(annotations)
# def post_scan_hook(dummy_module_parser, dummy_pygccxml_definition, pybindgen_wrapper):
# ## classes
# if isinstance(pybindgen_wrapper, CppClass):
# if pybindgen_wrapper.name.endswith('Checker'):
# print >> sys.stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", pybindgen_wrapper
# #pybindgen_wrapper.set_instance_creation_function(AttributeChecker_instance_creation_function)
def scan_callback_classes(module_parser, callback_classes_file):
callback_classes_file.write("callback_classes = [\n")
for cls in module_parser.module_namespace.classes(function=module_parser.location_filter,
recursive=False):
if not cls.name.startswith("Callback<"):
continue
assert templates.is_instantiation(cls.decl_string), "%s is not a template instantiation" % cls
dummy_cls_name, template_parameters = templates.split(cls.decl_string)
callback_classes_file.write(" %r,\n" % template_parameters)
callback_classes_file.write("]\n")
class MyPygenClassifier(PygenClassifier):
def __init__(self, headers_map, section_precendences):
self.headers_map = headers_map
self.section_precendences = section_precendences
def classify(self, pygccxml_definition):
name = os.path.basename(pygccxml_definition.location.file_name)
try:
return self.headers_map[name]
except KeyError:
return '__main__'
def get_section_precedence(self, section_name):
if section_name == '__main__':
return -1
return self.section_precendences[section_name]
def ns3_module_scan(top_builddir, pygen_file_name, everything_h, cflags):
ns3_modules = eval(sys.stdin.readline())
## do a topological sort on the modules graph
from topsort import topsort
graph = []
module_names = ns3_modules.keys()
module_names.sort()
for ns3_module_name in module_names:
ns3_module_deps = list(ns3_modules[ns3_module_name][0])
ns3_module_deps.sort()
for dep in ns3_module_deps:
graph.append((dep, ns3_module_name))
sorted_ns3_modules = topsort(graph)
#print >> sys.stderr, "******* topological sort: ", sorted_ns3_modules
sections = [PygenSection('__main__', FileCodeSink(open(pygen_file_name, "wt")))]
headers_map = {} # header_name -> section_name
section_precendences = {} # section_name -> precedence
for prec, ns3_module in enumerate(sorted_ns3_modules):
section_name = "ns3_module_%s" % ns3_module.replace('-', '_')
file_name = os.path.join(os.path.dirname(pygen_file_name), "%s.py" % section_name)
sections.append(PygenSection(section_name, FileCodeSink(open(file_name, "wt")),
section_name + "__local"))
for header in ns3_modules[ns3_module][1]:
headers_map[header] = section_name
section_precendences[section_name] = prec
module_parser = ModuleParser('ns3', 'ns3')
module_parser.add_pre_scan_hook(pre_scan_hook)
#module_parser.add_post_scan_hook(post_scan_hook)
gccxml_options = dict(
include_paths=[top_builddir],
define_symbols={
#'NS3_ASSERT_ENABLE': None,
#'NS3_LOG_ENABLE': None,
},
cflags=('--gccxml-cxxflags "%s -DPYTHON_SCAN"' % cflags)
)
module_parser.parse_init([everything_h],
None, whitelist_paths=[top_builddir, os.path.dirname(everything_h)],
#includes=['"ns3/everything.h"'],
pygen_sink=sections,
pygen_classifier=MyPygenClassifier(headers_map, section_precendences),
gccxml_options=gccxml_options)
module_parser.scan_types()
callback_classes_file = open(os.path.join(os.path.dirname(pygen_file_name), "callbacks_list.py"), "wt")
scan_callback_classes(module_parser, callback_classes_file)
callback_classes_file.close()
module_parser.scan_methods()
module_parser.scan_functions()
module_parser.parse_finalize()
for section in sections:
section.code_sink.file.close()
if __name__ == '__main__':
ns3_module_scan(sys.argv[1], sys.argv[3], sys.argv[2], sys.argv[4])
| zy901002-gpsr | bindings/python/ns3modulescan.py | Python | gpl2 | 13,937 |
from _ns3 import *
import atexit
atexit.register(Simulator.Destroy)
del atexit
| zy901002-gpsr | bindings/python/ns3__init__.py | Python | gpl2 | 82 |
import re
from pybindgen.typehandlers import base as typehandlers
from pybindgen import ReturnValue, Parameter
from pybindgen.cppmethod import CustomCppMethodWrapper, CustomCppConstructorWrapper
from pybindgen.typehandlers.codesink import MemoryCodeSink
from pybindgen.typehandlers import ctypeparser
from pybindgen import cppclass
import warnings
from pybindgen.typehandlers.base import CodeGenerationError
import sys
class SmartPointerTransformation(typehandlers.TypeTransformation):
"""
This class provides a "type transformation" that tends to support
NS-3 smart pointers. Parameters such as "Ptr<Foo> foo" are
transformed into something like Parameter.new("Foo*", "foo",
transfer_ownership=False). Return values such as Ptr<Foo> are
transformed into ReturnValue.new("Foo*",
caller_owns_return=False). Since the underlying objects have
reference counting, PyBindGen does the right thing.
"""
def __init__(self):
super(SmartPointerTransformation, self).__init__()
self.rx = re.compile(r'(ns3::|::ns3::|)Ptr<([^>]+)>\s*$')
def _get_untransformed_type_traits(self, name):
m = self.rx.match(name)
is_const = False
if m is None:
return None, False
else:
name1 = m.group(2).strip()
if name1.startswith('const '):
name1 = name1[len('const '):]
is_const = True
if name1.endswith(' const'):
name1 = name1[:-len(' const')]
is_const = True
new_name = name1+' *'
if new_name.startswith('::'):
new_name = new_name[2:]
return new_name, is_const
def get_untransformed_name(self, name):
new_name, dummy_is_const = self._get_untransformed_type_traits(name)
return new_name
def create_type_handler(self, type_handler, *args, **kwargs):
if issubclass(type_handler, Parameter):
kwargs['transfer_ownership'] = False
elif issubclass(type_handler, ReturnValue):
kwargs['caller_owns_return'] = False
else:
raise AssertionError
## fix the ctype, add ns3:: namespace
orig_ctype, is_const = self._get_untransformed_type_traits(args[0])
if is_const:
correct_ctype = 'ns3::Ptr< %s const >' % orig_ctype[:-2]
else:
correct_ctype = 'ns3::Ptr< %s >' % orig_ctype[:-2]
args = tuple([correct_ctype] + list(args[1:]))
handler = type_handler(*args, **kwargs)
handler.set_tranformation(self, orig_ctype)
return handler
def untransform(self, type_handler, declarations, code_block, expression):
return 'const_cast<%s> (ns3::PeekPointer (%s))' % (type_handler.untransformed_ctype, expression)
def transform(self, type_handler, declarations, code_block, expression):
assert type_handler.untransformed_ctype[-1] == '*'
return 'ns3::Ptr< %s > (%s)' % (type_handler.untransformed_ctype[:-1], expression)
## register the type transformation
transf = SmartPointerTransformation()
typehandlers.return_type_matcher.register_transformation(transf)
typehandlers.param_type_matcher.register_transformation(transf)
del transf
class ArgvParam(Parameter):
"""
Converts a python list-of-strings argument to a pair of 'int argc,
char *argv[]' arguments to pass into C.
One Python argument becomes two C function arguments -> it's a miracle!
Note: this parameter type handler is not registered by any name;
must be used explicitly.
"""
DIRECTIONS = [Parameter.DIRECTION_IN]
CTYPES = []
def convert_c_to_python(self, wrapper):
raise NotImplementedError
def convert_python_to_c(self, wrapper):
py_name = wrapper.declarations.declare_variable('PyObject*', 'py_' + self.name)
argc_var = wrapper.declarations.declare_variable('int', 'argc')
name = wrapper.declarations.declare_variable('char**', self.name)
idx = wrapper.declarations.declare_variable('Py_ssize_t', 'idx')
wrapper.parse_params.add_parameter('O!', ['&PyList_Type', '&'+py_name], self.name)
#wrapper.before_call.write_error_check('!PyList_Check(%s)' % py_name) # XXX
wrapper.before_call.write_code("%s = (char **) malloc(sizeof(char*)*PyList_Size(%s));"
% (name, py_name))
wrapper.before_call.add_cleanup_code('free(%s);' % name)
wrapper.before_call.write_code('''
for (%(idx)s = 0; %(idx)s < PyList_Size(%(py_name)s); %(idx)s++)
{
''' % vars())
wrapper.before_call.sink.indent()
wrapper.before_call.write_code('''
PyObject *item = PyList_GET_ITEM(%(py_name)s, %(idx)s);
''' % vars())
#wrapper.before_call.write_error_check('item == NULL')
wrapper.before_call.write_error_check(
'!PyString_Check(item)',
failure_cleanup=('PyErr_SetString(PyExc_TypeError, '
'"argument %s must be a list of strings");') % self.name)
wrapper.before_call.write_code(
'%s[%s] = PyString_AsString(item);' % (name, idx))
wrapper.before_call.sink.unindent()
wrapper.before_call.write_code('}')
wrapper.before_call.write_code('%s = PyList_Size(%s);' % (argc_var, py_name))
wrapper.call_params.append(argc_var)
wrapper.call_params.append(name)
class CallbackImplProxyMethod(typehandlers.ReverseWrapperBase):
"""
Class that generates a proxy virtual method that calls a similarly named python method.
"""
def __init__(self, return_value, parameters):
super(CallbackImplProxyMethod, self).__init__(return_value, parameters)
def generate_python_call(self):
"""code to call the python method"""
build_params = self.build_params.get_parameters(force_tuple_creation=True)
if build_params[0][0] == '"':
build_params[0] = '(char *) ' + build_params[0]
args = self.before_call.declare_variable('PyObject*', 'args')
self.before_call.write_code('%s = Py_BuildValue(%s);'
% (args, ', '.join(build_params)))
self.before_call.add_cleanup_code('Py_DECREF(%s);' % args)
self.before_call.write_code('py_retval = PyObject_CallObject(m_callback, %s);' % args)
self.before_call.write_error_check('py_retval == NULL')
self.before_call.add_cleanup_code('Py_DECREF(py_retval);')
def generate_callback_classes(out, callbacks):
for callback_impl_num, template_parameters in enumerate(callbacks):
sink = MemoryCodeSink()
cls_name = "ns3::Callback< %s >" % ', '.join(template_parameters)
#print >> sys.stderr, "***** trying to register callback: %r" % cls_name
class_name = "PythonCallbackImpl%i" % callback_impl_num
sink.writeln('''
class %s : public ns3::CallbackImpl<%s>
{
public:
PyObject *m_callback;
%s(PyObject *callback)
{
Py_INCREF(callback);
m_callback = callback;
}
virtual ~%s()
{
Py_DECREF(m_callback);
m_callback = NULL;
}
virtual bool IsEqual(ns3::Ptr<const ns3::CallbackImplBase> other_base) const
{
const %s *other = dynamic_cast<const %s*> (ns3::PeekPointer (other_base));
if (other != NULL)
return (other->m_callback == m_callback);
else
return false;
}
''' % (class_name, ', '.join(template_parameters), class_name, class_name, class_name, class_name))
sink.indent()
callback_return = template_parameters[0]
return_ctype = ctypeparser.parse_type(callback_return)
if ('const' in return_ctype.remove_modifiers()):
kwargs = {'is_const': True}
else:
kwargs = {}
try:
return_type = ReturnValue.new(str(return_ctype), **kwargs)
except (typehandlers.TypeLookupError, typehandlers.TypeConfigurationError), ex:
warnings.warn("***** Unable to register callback; Return value '%s' error (used in %s): %r"
% (callback_return, cls_name, ex),
Warning)
continue
arguments = []
ok = True
callback_parameters = [arg for arg in template_parameters[1:] if arg != 'ns3::empty']
for arg_num, arg_type in enumerate(callback_parameters):
arg_name = 'arg%i' % (arg_num+1)
param_ctype = ctypeparser.parse_type(arg_type)
if ('const' in param_ctype.remove_modifiers()):
kwargs = {'is_const': True}
else:
kwargs = {}
try:
arguments.append(Parameter.new(str(param_ctype), arg_name, **kwargs))
except (typehandlers.TypeLookupError, typehandlers.TypeConfigurationError), ex:
warnings.warn("***** Unable to register callback; parameter '%s %s' error (used in %s): %r"
% (arg_type, arg_name, cls_name, ex),
Warning)
ok = False
if not ok:
continue
wrapper = CallbackImplProxyMethod(return_type, arguments)
wrapper.generate(sink, 'operator()', decl_modifiers=[])
sink.unindent()
sink.writeln('};\n')
sink.flush_to(out)
class PythonCallbackParameter(Parameter):
"Class handlers"
CTYPES = [cls_name]
print >> sys.stderr, "***** registering callback handler: %r" % ctypeparser.normalize_type_string(cls_name)
DIRECTIONS = [Parameter.DIRECTION_IN]
PYTHON_CALLBACK_IMPL_NAME = class_name
TEMPLATE_ARGS = template_parameters
def convert_python_to_c(self, wrapper):
"parses python args to get C++ value"
assert isinstance(wrapper, typehandlers.ForwardWrapperBase)
if self.default_value is None:
py_callback = wrapper.declarations.declare_variable('PyObject*', self.name)
wrapper.parse_params.add_parameter('O', ['&'+py_callback], self.name)
wrapper.before_call.write_error_check(
'!PyCallable_Check(%s)' % py_callback,
'PyErr_SetString(PyExc_TypeError, "parameter \'%s\' must be callbale");' % self.name)
callback_impl = wrapper.declarations.declare_variable(
'ns3::Ptr<%s>' % self.PYTHON_CALLBACK_IMPL_NAME,
'%s_cb_impl' % self.name)
wrapper.before_call.write_code("%s = ns3::Create<%s> (%s);"
% (callback_impl, self.PYTHON_CALLBACK_IMPL_NAME, py_callback))
wrapper.call_params.append(
'ns3::Callback<%s> (%s)' % (', '.join(self.TEMPLATE_ARGS), callback_impl))
else:
py_callback = wrapper.declarations.declare_variable('PyObject*', self.name, 'NULL')
wrapper.parse_params.add_parameter('O', ['&'+py_callback], self.name, optional=True)
value = wrapper.declarations.declare_variable(
'ns3::Callback<%s>' % ', '.join(self.TEMPLATE_ARGS),
self.name+'_value',
self.default_value)
wrapper.before_call.write_code("if (%s) {" % (py_callback,))
wrapper.before_call.indent()
wrapper.before_call.write_error_check(
'!PyCallable_Check(%s)' % py_callback,
'PyErr_SetString(PyExc_TypeError, "parameter \'%s\' must be callbale");' % self.name)
wrapper.before_call.write_code("%s = ns3::Callback<%s> (ns3::Create<%s> (%s));"
% (value, ', '.join(self.TEMPLATE_ARGS),
self.PYTHON_CALLBACK_IMPL_NAME, py_callback))
wrapper.before_call.unindent()
wrapper.before_call.write_code("}") # closes: if (py_callback) {
wrapper.call_params.append(value)
def convert_c_to_python(self, wrapper):
raise typehandlers.NotSupportedError("Reverse wrappers for ns3::Callback<...> types "
"(python using callbacks defined in C++) not implemented.")
# def write_preamble(out):
# pybindgen.write_preamble(out)
# out.writeln("#include \"ns3/everything.h\"")
def Simulator_customizations(module):
Simulator = module['ns3::Simulator']
## Simulator::Schedule(delay, callback, ...user..args...)
Simulator.add_custom_method_wrapper("Schedule", "_wrap_Simulator_Schedule",
flags=["METH_VARARGS", "METH_KEYWORDS", "METH_STATIC"])
## Simulator::ScheduleNow(callback, ...user..args...)
Simulator.add_custom_method_wrapper("ScheduleNow", "_wrap_Simulator_ScheduleNow",
flags=["METH_VARARGS", "METH_KEYWORDS", "METH_STATIC"])
## Simulator::ScheduleDestroy(callback, ...user..args...)
Simulator.add_custom_method_wrapper("ScheduleDestroy", "_wrap_Simulator_ScheduleDestroy",
flags=["METH_VARARGS", "METH_KEYWORDS", "METH_STATIC"])
Simulator.add_custom_method_wrapper("Run", "_wrap_Simulator_Run",
flags=["METH_VARARGS", "METH_KEYWORDS", "METH_STATIC"])
def CommandLine_customizations(module):
CommandLine = module['ns3::CommandLine']
CommandLine.add_method('Parse', None, [ArgvParam(None, 'argv')],
is_static=False)
CommandLine.add_custom_method_wrapper("AddValue", "_wrap_CommandLine_AddValue",
flags=["METH_VARARGS", "METH_KEYWORDS"])
def Object_customizations(module):
## ---------------------------------------------------------------------
## Here we generate custom constructor code for all classes that
## derive from ns3::Object. The custom constructors are needed in
## order to support kwargs only and to translate kwargs into ns3
## attributes, etc.
## ---------------------------------------------------------------------
try:
Object = module['ns3::Object']
except KeyError:
return
## add a GetTypeId method to all generatd helper classes
def helper_class_hook(helper_class):
decl = """
static ns3::TypeId GetTypeId (void)
{
static ns3::TypeId tid = ns3::TypeId ("%s")
.SetParent< %s > ()
;
return tid;
}""" % (helper_class.name, helper_class.class_.full_name)
helper_class.add_custom_method(decl)
helper_class.add_post_generation_code(
"NS_OBJECT_ENSURE_REGISTERED (%s);" % helper_class.name)
Object.add_helper_class_hook(helper_class_hook)
def ns3_object_instance_creation_function(cpp_class, code_block, lvalue,
parameters, construct_type_name):
assert lvalue
assert not lvalue.startswith('None')
if cpp_class.cannot_be_constructed:
raise CodeGenerationError("%s cannot be constructed (%s)"
% cpp_class.full_name)
if cpp_class.incomplete_type:
raise CodeGenerationError("%s cannot be constructed (incomplete type)"
% cpp_class.full_name)
code_block.write_code("%s = new %s(%s);" % (lvalue, construct_type_name, parameters))
code_block.write_code("%s->Ref ();" % (lvalue))
def ns3_object_post_instance_creation_function(cpp_class, code_block, lvalue,
parameters, construct_type_name):
code_block.write_code("ns3::CompleteConstruct(%s);" % (lvalue, ))
Object.set_instance_creation_function(ns3_object_instance_creation_function)
Object.set_post_instance_creation_function(ns3_object_post_instance_creation_function)
def Attribute_customizations(module):
# Fix up for the "const AttributeValue &v = EmptyAttribute()"
# case, as used extensively by helper classes.
# Here's why we need to do this: pybindgen.gccxmlscanner, when
# scanning parameter default values, is only provided with the
# value as a simple C expression string. (py)gccxml does not
# report the type of the default value.
# As a workaround, here we iterate over all parameters of all
# methods of all classes and tell pybindgen what is the type of
# the default value for attributes.
for cls in module.classes:
for meth in cls.get_all_methods():
for param in meth.parameters:
if isinstance(param, cppclass.CppClassRefParameter):
if param.cpp_class.name == 'AttributeValue' \
and param.default_value is not None \
and param.default_value_type is None:
param.default_value_type = 'ns3::EmptyAttributeValue'
def TypeId_customizations(module):
TypeId = module['ns3::TypeId']
TypeId.add_custom_method_wrapper("LookupByNameFailSafe", "_wrap_TypeId_LookupByNameFailSafe",
flags=["METH_VARARGS", "METH_KEYWORDS", "METH_STATIC"])
def add_std_ofstream(module):
module.add_include('<fstream>')
ostream = module.add_class('ostream', foreign_cpp_namespace='::std')
ostream.set_cannot_be_constructed("abstract base class")
ofstream = module.add_class('ofstream', foreign_cpp_namespace='::std', parent=ostream)
ofstream.add_enum('openmode', [
('app', 'std::ios_base::app'),
('ate', 'std::ios_base::ate'),
('binary', 'std::ios_base::binary'),
('in', 'std::ios_base::in'),
('out', 'std::ios_base::out'),
('trunc', 'std::ios_base::trunc'),
])
ofstream.add_constructor([Parameter.new("const char *", 'filename'),
Parameter.new("::std::ofstream::openmode", 'mode', default_value="std::ios_base::out")])
ofstream.add_method('close', None, [])
add_std_ios_openmode(module)
def add_std_ios_openmode(module):
import pybindgen.typehandlers.base
for alias in "std::_Ios_Openmode", "std::ios::openmode":
pybindgen.typehandlers.base.param_type_matcher.add_type_alias(alias, "int")
for flag in 'in', 'out', 'ate', 'app', 'trunc', 'binary':
module.after_init.write_code('PyModule_AddIntConstant(m, (char *) "STD_IOS_%s", std::ios::%s);'
% (flag.upper(), flag))
def add_ipv4_address_tp_hash(module):
module.body.writeln('''
long
_ns3_Ipv4Address_tp_hash (PyObject *obj)
{
PyNs3Ipv4Address *addr = reinterpret_cast<PyNs3Ipv4Address *> (obj);
return static_cast<long> (ns3::Ipv4AddressHash () (*addr->obj));
}
''')
module.header.writeln('long _ns3_Ipv4Address_tp_hash (PyObject *obj);')
module['Ipv4Address'].pytype.slots['tp_hash'] = "_ns3_Ipv4Address_tp_hash"
| zy901002-gpsr | bindings/python/ns3modulegen_core_customizations.py | Python | gpl2 | 19,290 |
#include "ns3module.h"
#include "ns3/ref-count-base.h"
namespace ns3{
void PythonCompleteConstruct (Ptr<Object> object, TypeId typeId, const AttributeList &attributes)
{
object->SetTypeId (typeId);
object->Object::Construct (attributes);
}
}
class PythonEventImpl : public ns3::EventImpl
{
private:
PyObject *m_callback;
PyObject *m_args;
public:
PythonEventImpl (PyObject *callback, PyObject *args)
{
m_callback = callback;
Py_INCREF(m_callback);
m_args = args;
Py_INCREF(m_args);
}
virtual ~PythonEventImpl ()
{
PyGILState_STATE __py_gil_state;
__py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0);
Py_DECREF(m_callback);
Py_DECREF(m_args);
if (PyEval_ThreadsInitialized())
PyGILState_Release(__py_gil_state);
}
virtual void Notify ()
{
PyGILState_STATE __py_gil_state;
__py_gil_state = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0);
PyObject *retval = PyObject_CallObject(m_callback, m_args);
if (retval) {
if (retval != Py_None) {
PyErr_SetString(PyExc_TypeError, "event callback should return None");
PyErr_Print();
}
Py_DECREF(retval);
} else {
PyErr_Print();
}
if (PyEval_ThreadsInitialized())
PyGILState_Release(__py_gil_state);
}
};
PyObject *
_wrap_Simulator_Schedule(PyNs3Simulator *PYBINDGEN_UNUSED(dummy), PyObject *args, PyObject *kwargs,
PyObject **return_exception)
{
PyObject *exc_type, *traceback;
PyObject *py_time;
PyObject *py_callback;
PyObject *user_args;
ns3::Ptr<PythonEventImpl> py_event_impl;
PyNs3EventId *py_EventId;
if (kwargs && PyObject_Length(kwargs) > 0) {
PyErr_SetString(PyExc_TypeError, "keyword arguments not supported");
goto error;
}
if (PyTuple_GET_SIZE(args) < 2) {
PyErr_SetString(PyExc_TypeError, "ns3.Simulator.Schedule needs at least 2 arguments");
goto error;
}
py_time = PyTuple_GET_ITEM(args, 0);
py_callback = PyTuple_GET_ITEM(args, 1);
if (!PyObject_IsInstance(py_time, (PyObject*) &PyNs3Time_Type)) {
PyErr_SetString(PyExc_TypeError, "Parameter 1 should be a ns3.Time instance");
goto error;
}
if (!PyCallable_Check(py_callback)) {
PyErr_SetString(PyExc_TypeError, "Parameter 2 should be callable");
goto error;
}
user_args = PyTuple_GetSlice(args, 2, PyTuple_GET_SIZE(args));
py_event_impl = ns3::Create<PythonEventImpl>(py_callback, user_args);
Py_DECREF(user_args);
py_EventId = PyObject_New(PyNs3EventId, &PyNs3EventId_Type);
py_EventId->obj = new ns3::EventId(
ns3::Simulator::Schedule(*((PyNs3Time *) py_time)->obj, py_event_impl));
return (PyObject *) py_EventId;
error:
PyErr_Fetch(&exc_type, return_exception, &traceback);
Py_XDECREF(exc_type);
Py_XDECREF(traceback);
return NULL;
}
PyObject *
_wrap_Simulator_ScheduleNow(PyNs3Simulator *PYBINDGEN_UNUSED(dummy), PyObject *args, PyObject *kwargs,
PyObject **return_exception)
{
PyObject *exc_type, *traceback;
PyObject *py_callback;
PyObject *user_args;
ns3::Ptr<PythonEventImpl> py_event_impl;
PyNs3EventId *py_EventId;
if (kwargs && PyObject_Length(kwargs) > 0) {
PyErr_SetString(PyExc_TypeError, "keyword arguments not supported");
goto error;
}
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError, "ns3.Simulator.Schedule needs at least 1 argument");
goto error;
}
py_callback = PyTuple_GET_ITEM(args, 0);
if (!PyCallable_Check(py_callback)) {
PyErr_SetString(PyExc_TypeError, "Parameter 2 should be callable");
goto error;
}
user_args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
py_event_impl = ns3::Create<PythonEventImpl>(py_callback, user_args);
Py_DECREF(user_args);
py_EventId = PyObject_New(PyNs3EventId, &PyNs3EventId_Type);
py_EventId->obj = new ns3::EventId(ns3::Simulator::ScheduleNow(py_event_impl));
return (PyObject *) py_EventId;
error:
PyErr_Fetch(&exc_type, return_exception, &traceback);
Py_XDECREF(exc_type);
Py_XDECREF(traceback);
return NULL;
}
PyObject *
_wrap_Simulator_ScheduleDestroy(PyNs3Simulator *PYBINDGEN_UNUSED(dummy), PyObject *args, PyObject *kwargs,
PyObject **return_exception)
{
PyObject *exc_type, *traceback;
PyObject *py_callback;
PyObject *user_args;
ns3::Ptr<PythonEventImpl> py_event_impl;
PyNs3EventId *py_EventId;
if (kwargs && PyObject_Length(kwargs) > 0) {
PyErr_SetString(PyExc_TypeError, "keyword arguments not supported");
goto error;
}
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError, "ns3.Simulator.Schedule needs at least 1 argument");
goto error;
}
py_callback = PyTuple_GET_ITEM(args, 0);
if (!PyCallable_Check(py_callback)) {
PyErr_SetString(PyExc_TypeError, "Parameter 2 should be callable");
goto error;
}
user_args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
py_event_impl = ns3::Create<PythonEventImpl>(py_callback, user_args);
Py_DECREF(user_args);
py_EventId = PyObject_New(PyNs3EventId, &PyNs3EventId_Type);
py_EventId->obj = new ns3::EventId(ns3::Simulator::ScheduleDestroy(py_event_impl));
return (PyObject *) py_EventId;
error:
PyErr_Fetch(&exc_type, return_exception, &traceback);
Py_XDECREF(exc_type);
Py_XDECREF(traceback);
return NULL;
}
PyObject *
_wrap_TypeId_LookupByNameFailSafe(PyNs3TypeId *PYBINDGEN_UNUSED(dummy), PyObject *args, PyObject *kwargs,
PyObject **return_exception)
{
bool ok;
const char *name;
Py_ssize_t name_len;
ns3::TypeId tid;
PyNs3TypeId *py_tid;
const char *keywords[] = {"name", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "s#", (char **) keywords, &name, &name_len)) {
PyObject *exc_type, *traceback;
PyErr_Fetch(&exc_type, return_exception, &traceback);
Py_XDECREF(exc_type);
Py_XDECREF(traceback);
return NULL;
}
ok = ns3::TypeId::LookupByNameFailSafe(std::string(name, name_len), &tid);
if (!ok)
{
PyErr_Format(PyExc_KeyError, "The ns3 type with name `%s' is not registered", name);
return NULL;
}
py_tid = PyObject_New(PyNs3TypeId, &PyNs3TypeId_Type);
py_tid->obj = new ns3::TypeId (tid);
PyNs3TypeId_wrapper_registry[(void *) py_tid->obj] = (PyObject *) py_tid;
return (PyObject *) py_tid;
}
class CommandLinePythonValueSetter : public ns3::RefCountBase
{
PyObject *m_namespace;
std::string m_variable;
public:
CommandLinePythonValueSetter (PyObject *ns, std::string const &variable) {
Py_INCREF(ns);
m_namespace = ns;
m_variable = variable;
}
bool Parse (std::string value) {
PyObject *pyvalue = PyString_FromStringAndSize (value.data(), value.size());
PyObject_SetAttrString (m_namespace, (char *) m_variable.c_str(), pyvalue);
if (PyErr_Occurred()) {
PyErr_Print();
return false;
}
return true;
}
virtual ~CommandLinePythonValueSetter () {
Py_DECREF (m_namespace);
m_namespace = NULL;
}
};
PyObject *
_wrap_CommandLine_AddValue(PyNs3CommandLine *self, PyObject *args, PyObject *kwargs,
PyObject **return_exception)
{
const char *name, *help, *variable = NULL;
PyObject *py_namespace = NULL;
const char *keywords[] = {"name", "help", "variable", "namespace", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "ss|sO", (char **) keywords, &name, &help, &variable, &py_namespace)) {
PyObject *exc_type, *traceback;
PyErr_Fetch(&exc_type, return_exception, &traceback);
Py_XDECREF(exc_type);
Py_XDECREF(traceback);
return NULL;
}
if (variable == NULL) {
variable = name;
}
if (py_namespace == NULL) {
py_namespace = (PyObject *) self;
}
ns3::Ptr<CommandLinePythonValueSetter> setter = ns3::Create<CommandLinePythonValueSetter> (py_namespace, variable);
self->obj->AddValue (name, help, ns3::MakeCallback (&CommandLinePythonValueSetter::Parse, setter));
Py_INCREF(Py_None);
return Py_None;
}
PyObject *
_wrap_Simulator_Run(PyNs3Simulator *PYBINDGEN_UNUSED(dummy), PyObject *args, PyObject *kwargs,
PyObject **return_exception)
{
const char *keywords[] = {"signal_check_frequency", NULL};
int signal_check_frequency;
ns3::Ptr<ns3::DefaultSimulatorImpl> defaultSim =
ns3::DynamicCast<ns3::DefaultSimulatorImpl> (ns3::Simulator::GetImplementation ());
if (defaultSim) {
signal_check_frequency = 100;
} else {
signal_check_frequency = -1;
}
if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "|i", (char **) keywords, &signal_check_frequency)) {
PyObject *exc_type, *traceback;
PyErr_Fetch(&exc_type, return_exception, &traceback);
Py_XDECREF(exc_type);
Py_XDECREF(traceback);
return NULL;
}
PyThreadState *py_thread_state = NULL;
if (signal_check_frequency == -1)
{
if (PyEval_ThreadsInitialized ())
py_thread_state = PyEval_SaveThread();
ns3::Simulator::Run();
if (py_thread_state)
PyEval_RestoreThread(py_thread_state);
} else {
while (!ns3::Simulator::IsFinished())
{
if (PyEval_ThreadsInitialized())
py_thread_state = PyEval_SaveThread();
for (int n = signal_check_frequency; n > 0 && !ns3::Simulator::IsFinished(); --n)
{
ns3::Simulator::RunOneEvent();
}
if (py_thread_state)
PyEval_RestoreThread(py_thread_state);
PyErr_CheckSignals();
if (PyErr_Occurred())
return NULL;
}
}
Py_INCREF(Py_None);
return Py_None;
}
| zy901002-gpsr | bindings/python/ns3module_helpers.cc | C++ | gpl2 | 10,406 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
import types
import re
import os
import subprocess
import shutil
import sys
import Task
import Options
import Configure
import TaskGen
import Logs
import Build
import Utils
from waflib.Errors import WafError
## https://launchpad.net/pybindgen/
REQUIRED_PYBINDGEN_VERSION = (0, 15, 0, 795)
REQUIRED_PYGCCXML_VERSION = (0, 9, 5)
from TaskGen import feature, after
import Task
def add_to_python_path(path):
if os.environ.get('PYTHONPATH', ''):
os.environ['PYTHONPATH'] = path + os.pathsep + os.environ.get('PYTHONPATH')
else:
os.environ['PYTHONPATH'] = path
def set_pybindgen_pythonpath(env):
if env['WITH_PYBINDGEN']:
add_to_python_path(env['WITH_PYBINDGEN'])
def options(opt):
opt.tool_options('python', ["waf-tools"])
opt.add_option('--disable-python',
help=("Don't build Python bindings."),
action="store_true", default=False,
dest='python_disable')
opt.add_option('--apiscan',
help=("Rescan the API for the indicated module(s), for Python bindings. "
"Needs working GCCXML / pygccxml environment. "
"The metamodule 'all' expands to all available ns-3 modules."),
default=None, dest='apiscan', metavar="MODULE[,MODULE...]")
opt.add_option('--with-pybindgen',
help=('Path to an existing pybindgen source tree to use.'),
default=None,
dest='with_pybindgen', type="string")
opt.add_option('--with-python',
help=('Path to the Python interpreter to use.'),
default=None, dest='with_python', type="string")
def configure(conf):
conf.env['ENABLE_PYTHON_BINDINGS'] = False
if Options.options.python_disable:
conf.report_optional_feature("python", "Python Bindings", False,
"disabled by user request")
return
# Disable python in static builds (bug #1253)
if ((conf.env['ENABLE_STATIC_NS3']) or \
(conf.env['ENABLE_SHARED_AND_STATIC_NS3'])):
conf.report_optional_feature("python", "Python Bindings", False,
"bindings incompatible with static build")
return
enabled_modules = list(conf.env['NS3_ENABLED_MODULES'])
enabled_modules.sort()
available_modules = list(conf.env['NS3_MODULES'])
available_modules.sort()
all_modules_enabled = (enabled_modules == available_modules)
conf.check_tool('misc', tooldir=['waf-tools'])
if sys.platform == 'cygwin':
conf.report_optional_feature("python", "Python Bindings", False,
"unsupported platform 'cygwin'")
Logs.warn("Python is not supported in CygWin environment. Try MingW instead.")
return
## Check for Python
if Options.options.with_python is not None:
conf.env.PYTHON = Options.options.with_python
try:
conf.check_tool('python', ["waf-tools"])
conf.check_python_version((2,3))
conf.check_python_headers()
except Configure.ConfigurationError, ex:
conf.report_optional_feature("python", "Python Bindings", False, str(ex))
return
# stupid Mac OSX Python wants to build extensions as "universal
# binaries", i386, x86_64, and ppc, but this way the type
# __uint128_t is not available. We need to disable the multiarch
# crap by removing the -arch parameters.
for flags_var in ["CFLAGS_PYEXT", "CFLAGS_PYEMBED", "CXXFLAGS_PYEMBED",
"CXXFLAGS_PYEXT", "LINKFLAGS_PYEMBED", "LINKFLAGS_PYEXT"]:
flags = conf.env[flags_var]
i = 0
while i < len(flags):
if flags[i] == '-arch':
del flags[i]
del flags[i]
continue
i += 1
conf.env[flags_var] = flags
# -fvisibility=hidden optimization
if (conf.env['CXX_NAME'] == 'gcc' and [int(x) for x in conf.env['CC_VERSION']] >= [4,0,0]
and conf.check_compilation_flag('-fvisibility=hidden')):
conf.env.append_value('CXXFLAGS_PYEXT', '-fvisibility=hidden')
conf.env.append_value('CCFLAGS_PYEXT', '-fvisibility=hidden')
# Check for the location of pybindgen
if Options.options.with_pybindgen is not None:
if os.path.isdir(Options.options.with_pybindgen):
conf.msg("Checking for pybindgen location", ("%s (given)" % Options.options.with_pybindgen))
conf.env['WITH_PYBINDGEN'] = os.path.abspath(Options.options.with_pybindgen)
else:
# ns-3-dev uses ../pybindgen, while ns-3 releases use ../REQUIRED_PYBINDGEN_VERSION
pybindgen_dir = os.path.join('..', "pybindgen")
pybindgen_release_str = "pybindgen-" + '.'.join([str(x) for x in REQUIRED_PYBINDGEN_VERSION])
pybindgen_release_dir = os.path.join('..', pybindgen_release_str)
if os.path.isdir(pybindgen_dir):
conf.msg("Checking for pybindgen location", ("%s (guessed)" % pybindgen_dir))
conf.env['WITH_PYBINDGEN'] = os.path.abspath(pybindgen_dir)
elif os.path.isdir(pybindgen_release_dir):
conf.msg("Checking for pybindgen location", ("%s (guessed)" % pybindgen_release_dir))
conf.env['WITH_PYBINDGEN'] = os.path.abspath(pybindgen_release_dir)
del pybindgen_dir
del pybindgen_release_dir
if not conf.env['WITH_PYBINDGEN']:
conf.msg("Checking for pybindgen location", False)
# Check for pybindgen
set_pybindgen_pythonpath(conf.env)
try:
conf.check_python_module('pybindgen')
except Configure.ConfigurationError:
Logs.warn("pybindgen missing => no python bindings")
conf.report_optional_feature("python", "Python Bindings", False,
"PyBindGen missing")
return
else:
out = subprocess.Popen([conf.env['PYTHON'][0], "-c",
"import pybindgen.version; "
"print '.'.join([str(x) for x in pybindgen.version.__version__])"],
stdout=subprocess.PIPE).communicate()[0]
pybindgen_version_str = out.strip()
pybindgen_version = tuple([int(x) for x in pybindgen_version_str.split('.')])
conf.msg('Checking for pybindgen version', pybindgen_version_str)
if not (pybindgen_version == REQUIRED_PYBINDGEN_VERSION):
Logs.warn("pybindgen (found %s), (need %s)" %
(pybindgen_version_str,
'.'.join([str(x) for x in REQUIRED_PYBINDGEN_VERSION])))
conf.report_optional_feature("python", "Python Bindings", False,
"PyBindGen version not correct and newer version could not be retrieved")
return
def test(t1, t2):
test_program = '''
#include <stdint.h>
#include <vector>
int main ()
{
std::vector< %(type1)s > t = std::vector< %(type2)s > ();
return 0;
}
''' % dict(type1=t1, type2=t2)
try:
ret = conf.run_c_code(code=test_program,
env=conf.env.copy(), compile_filename='test.cc',
features='cxx cprogram', execute=False)
except Configure.ConfigurationError:
ret = 1
conf.msg('Checking for types %s and %s equivalence' % (t1, t2), (ret and 'no' or 'yes'))
return not ret
uint64_is_long = test("uint64_t", "unsigned long")
uint64_is_long_long = test("uint64_t", "unsigned long long")
if uint64_is_long:
conf.env['PYTHON_BINDINGS_APIDEFS'] = 'gcc-LP64'
elif uint64_is_long_long:
conf.env['PYTHON_BINDINGS_APIDEFS'] = 'gcc-ILP32'
else:
conf.env['PYTHON_BINDINGS_APIDEFS'] = None
if conf.env['PYTHON_BINDINGS_APIDEFS'] is None:
msg = 'none available'
else:
msg = conf.env['PYTHON_BINDINGS_APIDEFS']
conf.msg('Checking for the apidefs that can be used for Python bindings', msg)
if conf.env['PYTHON_BINDINGS_APIDEFS'] is None:
conf.report_optional_feature("python", "Python Bindings", False,
"No apidefs are available that can be used in this system")
return
## If all has gone well, we finally enable the Python bindings
conf.env['ENABLE_PYTHON_BINDINGS'] = True
conf.report_optional_feature("python", "Python Bindings", True, None)
# check cxxabi stuff (which Mac OS X Lion breaks)
fragment = r"""
# include <cxxabi.h>
int main ()
{
const abi::__si_class_type_info *_typeinfo __attribute__((unused)) = NULL;
return 0;
}
"""
gcc_rtti_abi = conf.check_nonfatal(fragment=fragment, msg="Checking for internal GCC cxxabi",
okmsg="complete", errmsg='incomplete',
mandatory=False)
conf.env["GCC_RTTI_ABI_COMPLETE"] = str(bool(gcc_rtti_abi))
## Check for pygccxml
try:
conf.check_python_module('pygccxml')
except Configure.ConfigurationError:
conf.report_optional_feature("pygccxml", "Python API Scanning Support", False,
"Missing 'pygccxml' Python module")
return
out = subprocess.Popen([conf.env['PYTHON'][0], "-c",
"import pygccxml; print pygccxml.__version__"],
stdout=subprocess.PIPE).communicate()[0]
pygccxml_version_str = out.strip()
pygccxml_version = tuple([int(x) for x in pygccxml_version_str.split('.')])
conf.msg('Checking for pygccxml version', pygccxml_version_str)
if not (pygccxml_version >= REQUIRED_PYGCCXML_VERSION):
Logs.warn("pygccxml (found %s) is too old (need %s) => "
"automatic scanning of API definitions will not be possible" %
(pygccxml_version_str,
'.'.join([str(x) for x in REQUIRED_PYGCCXML_VERSION])))
conf.report_optional_feature("pygccxml", "Python API Scanning Support", False,
"pygccxml too old")
return
## Check gccxml version
try:
gccxml = conf.find_program('gccxml', var='GCCXML')
except WafError:
gccxml = None
if not gccxml:
Logs.warn("gccxml missing; automatic scanning of API definitions will not be possible")
conf.report_optional_feature("pygccxml", "Python API Scanning Support", False,
"gccxml missing")
return
gccxml_version_line = os.popen(gccxml + " --version").readline().strip()
m = re.match( "^GCC-XML version (\d\.\d(\.\d)?)$", gccxml_version_line)
gccxml_version = m.group(1)
gccxml_version_ok = ([int(s) for s in gccxml_version.split('.')] >= [0, 9])
conf.msg('Checking for gccxml version', gccxml_version)
if not gccxml_version_ok:
Logs.warn("gccxml too old, need version >= 0.9; automatic scanning of API definitions will not be possible")
conf.report_optional_feature("pygccxml", "Python API Scanning Support", False,
"gccxml too old")
return
## If we reached
conf.env['ENABLE_PYTHON_SCANNING'] = True
conf.report_optional_feature("pygccxml", "Python API Scanning Support", True, None)
# ---------------------
def get_headers_map(bld):
headers_map = {} # header => module
for ns3headers in bld.all_task_gen:
if 'ns3header' in getattr(ns3headers, "features", []):
if ns3headers.module.endswith('-test'):
continue
for h in ns3headers.to_list(ns3headers.headers):
headers_map[os.path.basename(h)] = ns3headers.module
return headers_map
def get_module_path(bld, module):
for ns3headers in bld.all_task_gen:
if 'ns3header' in getattr(ns3headers, "features", []):
if ns3headers.module == module:
break
else:
raise ValueError("Module %r not found" % module)
return ns3headers.path.abspath()
class apiscan_task(Task.TaskBase):
"""Uses gccxml to scan the file 'everything.h' and extract API definitions.
"""
after = 'gen_ns3_module_header ns3header'
before = 'cc cxx command'
color = "BLUE"
def __init__(self, curdirnode, env, bld, target, cflags, module):
self.bld = bld
super(apiscan_task, self).__init__(generator=self)
self.curdirnode = curdirnode
self.env = env
self.target = target
self.cflags = cflags
self.module = module
def display(self):
return 'api-scan-%s\n' % (self.target,)
def run(self):
top_builddir = self.bld.bldnode.abspath()
module_path = get_module_path(self.bld, self.module)
headers_map = get_headers_map(self.bld)
scan_header = os.path.join(top_builddir, "ns3", "%s-module.h" % self.module)
if not os.path.exists(scan_header):
Logs.error("Cannot apiscan module %r: %s does not exist" % (self.module, scan_header))
return 0
argv = [
self.env['PYTHON'][0],
os.path.join(self.curdirnode.abspath(), 'ns3modulescan-modular.py'), # scanning script
top_builddir,
self.module,
repr(get_headers_map(self.bld)),
os.path.join(module_path, "bindings", 'modulegen__%s.py' % (self.target)), # output file
self.cflags,
]
scan = subprocess.Popen(argv, stdin=subprocess.PIPE)
retval = scan.wait()
return retval
def get_modules_and_headers(bld):
"""
Gets a dict of
module_name => ([module_dep1, module_dep2, ...], [module_header1, module_header2, ...])
tuples, one for each module.
"""
retval = {}
for module in bld.all_task_gen:
if not module.name.startswith('ns3-'):
continue
if module.name.endswith('-test'):
continue
module_name = module.name[4:] # strip the ns3- prefix
## find the headers object for this module
headers = []
for ns3headers in bld.all_task_gen:
if 'ns3header' not in getattr(ns3headers, "features", []):
continue
if ns3headers.module != module_name:
continue
for source in ns3headers.to_list(ns3headers.headers):
headers.append(os.path.basename(source))
retval[module_name] = (list(module.module_deps), headers)
return retval
class python_scan_task_collector(Task.TaskBase):
"""Tasks that waits for the python-scan-* tasks to complete and then signals WAF to exit
"""
after = 'apiscan'
before = 'cc cxx'
color = "BLUE"
def __init__(self, curdirnode, env, bld):
self.bld = bld
super(python_scan_task_collector, self).__init__(generator=self)
self.curdirnode = curdirnode
self.env = env
def display(self):
return 'python-scan-collector\n'
def run(self):
# signal stop (we generated files into the source dir and WAF
# can't cope with it, so we have to force the user to restart
# WAF)
self.bld.producer.stop = 1
self.bld.producer.free_task_pool()
return 0
class gen_ns3_compat_pymod_task(Task.Task):
"""Generates a 'ns3.py' compatibility module."""
before = 'cc cxx'
color = 'BLUE'
def run(self):
assert len(self.outputs) == 1
outfile = file(self.outputs[0].abspath(), "w")
print >> outfile, "import warnings"
print >> outfile, 'warnings.warn("the ns3 module is a compatibility layer '\
'and should not be used in newly written code", DeprecationWarning, stacklevel=2)'
print >> outfile
for module in self.bld.env['PYTHON_MODULES_BUILT']:
print >> outfile, "from ns.%s import *" % (module.replace('-', '_'))
outfile.close()
return 0
def build(bld):
if Options.options.python_disable:
return
env = bld.env
curdir = bld.path.abspath()
set_pybindgen_pythonpath(env)
if Options.options.apiscan:
if not env['ENABLE_PYTHON_SCANNING']:
raise WafError("Cannot re-scan python bindings: (py)gccxml not available")
scan_targets = []
if sys.platform == 'cygwin':
scan_targets.append(('gcc_cygwin', ''))
else:
import struct
if struct.calcsize('I') == 4 and struct.calcsize('L') == 8 and struct.calcsize('P') == 8:
scan_targets.extend([('gcc_ILP32', '-m32'), ('gcc_LP64', '-m64')])
elif struct.calcsize('I') == 4 and struct.calcsize('L') == 4 and struct.calcsize('P') == 4:
scan_targets.append(('gcc_ILP32', ''))
else:
raise WafError("Cannot scan python bindings for unsupported data model")
test_module_path = bld.path.find_dir("../../src/test")
if Options.options.apiscan == 'all':
scan_modules = []
for mod in bld.all_task_gen:
if not mod.name.startswith('ns3-'):
continue
if mod.path.is_child_of(test_module_path):
continue
if mod.name.endswith('-test'):
continue
bindings_enabled = (mod.name in env.MODULAR_BINDINGS_MODULES)
#print mod.name, bindings_enabled
if bindings_enabled:
scan_modules.append(mod.name.split('ns3-')[1])
else:
scan_modules = Options.options.apiscan.split(',')
print "Modules to scan: ", scan_modules
for target, cflags in scan_targets:
group = bld.get_group(bld.current_group)
for module in scan_modules:
group.append(apiscan_task(bld.path, env, bld, target, cflags, module))
group.append(python_scan_task_collector(bld.path, env, bld))
return
if env['ENABLE_PYTHON_BINDINGS']:
task = gen_ns3_compat_pymod_task(env=env.derive())
task.set_outputs(bld.path.find_or_declare("ns3.py"))
task.dep_vars = ['PYTHON_MODULES_BUILT']
task.bld = bld
grp = bld.get_group(bld.current_group)
grp.append(task)
bld.new_task_gen(features='copy',
source="ns__init__.py",
target='ns/__init__.py')
bld.install_as('${PYTHONDIR}/ns/__init__.py', 'ns__init__.py')
# note: the actual build commands for the python bindings are in
# src/wscript, not here.
| zy901002-gpsr | bindings/python/wscript | Python | gpl2 | 18,718 |
#! /usr/bin/env python
# These methods are used by test.py and waf to look for and read the
# .ns3rc configuration file, which is used to specify the modules that
# should be enabled
import os
import sys
def get_list_from_file(file_path, list_name):
'''Looks for a Python list called list_name in the file specified
by file_path and returns it.
If the file or list name aren't found, this function will return
an empty list.
'''
list = []
# Read in the file if it exists.
if os.path.exists(file_path):
file_in = open(file_path, "r")
# Look for the list.
list_string = ""
parsing_multiline_list = False
for line in file_in:
if list_name in line or parsing_multiline_list:
list_string += line
# Handle multiline lists.
if ']' not in list_string:
parsing_multiline_list = True
else:
# Evaluate the list once its end is reached.
# Make the split function only split it once.
list = eval(list_string.split('=', 1)[1].strip())
break
# Close the file
file_in.close()
return list
def get_bool_from_file(file_path, bool_name, value_if_missing):
'''Looks for a Python boolean variable called bool_name in the
file specified by file_path and returns its value.
If the file or boolean variable aren't found, this function will
return value_if_missing.
'''
# Read in the file if it exists.
if os.path.exists(file_path):
file_in = open(file_path, "r")
# Look for the boolean variable.
bool_found = False
for line in file_in:
if bool_name in line:
# Evaluate the variable's line once it is found. Make
# the split function only split it once.
bool = eval(line.split('=', 1)[1].strip())
bool_found = True
break
# Close the file
file_in.close()
if bool_found:
return bool
else:
return value_if_missing
# Reads the NS-3 configuration file and returns a list of enabled modules.
#
# This function first looks for the ns3 configuration file (.ns3rc) in
# the current working directory and then looks in the ~ directory.
def read_config_file():
# By default, all modules will be enabled, examples will be disabled,
# and tests will be disabled.
modules_enabled = ['all_modules']
examples_enabled = False
tests_enabled = False
# See if the ns3 configuration file exists in the current working
# directory and then look for it in the ~ directory.
config_file_exists = False
dot_ns3rc_name = '.ns3rc'
dot_ns3rc_path = dot_ns3rc_name
if not os.path.exists(dot_ns3rc_path):
dot_ns3rc_path = os.path.expanduser('~/') + dot_ns3rc_name
if not os.path.exists(dot_ns3rc_path):
# Return all of the default values if the .ns3rc file can't be found.
return (config_file_exists, modules_enabled, examples_enabled, tests_enabled)
config_file_exists = True
# Read in the enabled modules.
modules_enabled = get_list_from_file(dot_ns3rc_path, 'modules_enabled')
if not modules_enabled:
# Enable all modules if the modules_enabled line can't be found.
modules_enabled = ['all_modules']
# Read in whether examples should be enabled or not.
value_if_missing = False
examples_enabled = get_bool_from_file(dot_ns3rc_path, 'examples_enabled', value_if_missing)
# Read in whether tests should be enabled or not.
value_if_missing = False
tests_enabled = get_bool_from_file(dot_ns3rc_path, 'tests_enabled', value_if_missing)
return (config_file_exists, modules_enabled, examples_enabled, tests_enabled)
| zy901002-gpsr | utils.py | Python | gpl2 | 3,892 |
#! /usr/bin/env python
# encoding: utf-8
"""
Waf 1.6
Try to detect if the project directory was relocated, and if it was,
change the node representing the project directory. Just call:
waf configure build
Note that if the project directory name changes, the signatures for the tasks using
files in that directory will change, causing a partial build.
"""
import os
from waflib import Build, ConfigSet, Task, Utils, Errors
from waflib.TaskGen import feature, before_method, after_method
EXTRA_LOCK = '.old_srcdir'
old1 = Build.BuildContext.store
def store(self):
old1(self)
db = os.path.join(self.variant_dir, EXTRA_LOCK)
env = ConfigSet.ConfigSet()
env.SRCDIR = self.srcnode.abspath()
env.store(db)
Build.BuildContext.store = store
old2 = Build.BuildContext.init_dirs
def init_dirs(self):
if not (os.path.isabs(self.top_dir) and os.path.isabs(self.out_dir)):
raise Errors.WafError('The project was not configured: run "waf configure" first!')
srcdir = None
db = os.path.join(self.variant_dir, EXTRA_LOCK)
env = ConfigSet.ConfigSet()
try:
env.load(db)
srcdir = env.SRCDIR
except:
pass
if srcdir:
d = self.root.find_node(srcdir)
if d and srcdir != self.top_dir and getattr(d, 'children', ''):
srcnode = self.root.make_node(self.top_dir)
print("relocating the source directory %r -> %r" % (srcdir, self.top_dir))
srcnode.children = {}
for (k, v) in d.children.items():
srcnode.children[k] = v
v.parent = srcnode
d.children = {}
old2(self)
Build.BuildContext.init_dirs = init_dirs
def uid(self):
try:
return self.uid_
except AttributeError:
# this is not a real hot zone, but we want to avoid surprizes here
m = Utils.md5()
up = m.update
up(self.__class__.__name__.encode())
for x in self.inputs + self.outputs:
up(x.path_from(x.ctx.srcnode).encode())
self.uid_ = m.digest()
return self.uid_
Task.Task.uid = uid
@feature('c', 'cxx', 'd', 'go', 'asm', 'fc', 'includes')
@after_method('propagate_uselib_vars', 'process_source')
def apply_incpaths(self):
lst = self.to_incnodes(self.to_list(getattr(self, 'includes', [])) + self.env['INCLUDES'])
self.includes_nodes = lst
bld = self.bld
self.env['INCPATHS'] = [x.is_child_of(bld.srcnode) and x.path_from(bld.srcnode) or x.abspath() for x in lst]
| zy901002-gpsr | waf-tools/relocation.py | Python | gpl2 | 2,282 |
#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2007-2010 (ita)
# Gustavo Carneiro (gjc), 2007
#
# NS-3 Note: this python tool was added only for including a bug fix:
# http://code.google.com/p/waf/issues/detail?id=1045
# Once waf 1.6.8 comes out and ns-3 upgrades to it, this copy of the python tool can be removed
#
"""
Support for Python, detect the headers and libraries and provide
*use* variables to link C/C++ programs against them::
def options(opt):
opt.load('compiler_c python')
def configure(conf):
conf.load('compiler_c python')
conf.check_python_version((2,4,2))
conf.check_python_headers()
def build(bld):
bld.program(features='pyembed', source='a.c', target='myprog')
bld.shlib(features='pyext', source='b.c', target='mylib')
"""
import os, sys
from waflib import Utils, Options, Errors
from waflib.Logs import debug, warn, info, error
from waflib.TaskGen import extension, before_method, after_method, feature
from waflib.Configure import conf
FRAG = '''
#include <Python.h>
#ifdef __cplusplus
extern "C" {
#endif
void Py_Initialize(void);
void Py_Finalize(void);
#ifdef __cplusplus
}
#endif
int main()
{
Py_Initialize();
Py_Finalize();
return 0;
}
'''
"""
Piece of C/C++ code used in :py:func:`waflib.Tools.python.check_python_headers`
"""
INST = '''
import sys, py_compile
py_compile.compile(sys.argv[1], sys.argv[2], sys.argv[3])
'''
"""
Piece of Python code used in :py:func:`waflib.Tools.python.install_pyfile` for installing python files
"""
@extension('.py')
def process_py(self, node):
"""
Add a callback using :py:func:`waflib.Tools.python.install_pyfile` to install a python file
"""
try:
if not self.bld.is_install:
return
except:
return
try:
if not self.install_path:
return
except AttributeError:
self.install_path = '${PYTHONDIR}'
# i wonder now why we wanted to do this after the build is over
# issue #901: people want to preserve the structure of installed files
def inst_py(ctx):
install_from = getattr(self, 'install_from', None)
if install_from:
install_from = self.path.find_dir(install_from)
install_pyfile(self, node, install_from)
self.bld.add_post_fun(inst_py)
def install_pyfile(self, node, install_from=None):
"""
Execute the installation of a python file
:param node: python file
:type node: :py:class:`waflib.Node.Node`
"""
from_node = install_from or node.parent
tsk = self.bld.install_as(self.install_path + '/' + node.path_from(from_node), node, postpone=False)
path = tsk.get_install_path()
if self.bld.is_install < 0:
info("+ removing byte compiled python files")
for x in 'co':
try:
os.remove(path + x)
except OSError:
pass
if self.bld.is_install > 0:
try:
st1 = os.stat(path)
except:
error('The python file is missing, this should not happen')
for x in ['c', 'o']:
do_inst = self.env['PY' + x.upper()]
try:
st2 = os.stat(path + x)
except OSError:
pass
else:
if st1.st_mtime <= st2.st_mtime:
do_inst = False
if do_inst:
lst = (x == 'o') and [self.env['PYFLAGS_OPT']] or []
(a, b, c) = (path, path + x, tsk.get_install_path(destdir=False) + x)
argv = self.env['PYTHON'] + lst + ['-c', INST, a, b, c]
info('+ byte compiling %r' % (path + x))
ret = Utils.subprocess.Popen(argv).wait()
if ret:
raise Errors.WafError('py%s compilation failed %r' % (x, path))
@feature('py')
def feature_py(self):
"""
Dummy feature which does nothing
"""
pass
@feature('pyext')
@before_method('propagate_uselib_vars', 'apply_link')
@after_method('apply_bundle')
def init_pyext(self):
"""
Change the values of *cshlib_PATTERN* and *cxxshlib_PATTERN* to remove the
*lib* prefix from library names.
"""
try:
if not self.install_path:
return
except AttributeError:
self.install_path = '${PYTHONARCHDIR}'
self.uselib = self.to_list(getattr(self, 'uselib', []))
if not 'PYEXT' in self.uselib:
self.uselib.append('PYEXT')
# override shlib_PATTERN set by the osx module
self.env['cshlib_PATTERN'] = self.env['cxxshlib_PATTERN'] = self.env['macbundle_PATTERN'] = self.env['pyext_PATTERN']
@feature('pyext')
@before_method('apply_link', 'apply_bundle')
def set_bundle(self):
if sys.platform.startswith('darwin'):
self.mac_bundle = True
@before_method('propagate_uselib_vars')
@feature('pyembed')
def init_pyembed(self):
"""
Add the PYEMBED variable.
"""
self.uselib = self.to_list(getattr(self, 'uselib', []))
if not 'PYEMBED' in self.uselib:
self.uselib.append('PYEMBED')
@conf
def get_python_variables(conf, variables, imports=['import sys']):
"""
Execute a python interpreter to dump configuration variables
:param variables: variables to print
:type variables: list of string
:param imports: one import by element
:type imports: list of string
:return: the variable values
:rtype: list of string
"""
program = list(imports)
program.append('')
for v in variables:
program.append("print(repr(%s))" % v)
os_env = dict(os.environ)
try:
del os_env['MACOSX_DEPLOYMENT_TARGET'] # see comments in the OSX tool
except KeyError:
pass
try:
out = conf.cmd_and_log(conf.env.PYTHON + ['-c', '\n'.join(program)], env=os_env)
except Errors.WafError:
conf.fatal('The distutils module is unusable: install "python-devel"?')
return_values = []
for s in out.split('\n'):
s = s.strip()
if not s:
continue
if s == 'None':
return_values.append(None)
elif s[0] == "'" and s[-1] == "'":
return_values.append(s[1:-1])
elif s[0].isdigit():
return_values.append(int(s))
else: break
return return_values
@conf
def check_python_headers(conf):
"""
Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:
* PYEXT: for compiling python extensions
* PYEMBED: for embedding a python interpreter
"""
# FIXME rewrite
if not conf.env['CC_NAME'] and not conf.env['CXX_NAME']:
conf.fatal('load a compiler first (gcc, g++, ..)')
if not conf.env['PYTHON_VERSION']:
conf.check_python_version()
env = conf.env
pybin = conf.env.PYTHON
if not pybin:
conf.fatal('could not find the python executable')
v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split()
try:
lst = conf.get_python_variables(["get_config_var('%s') or ''" % x for x in v],
['from distutils.sysconfig import get_config_var'])
except RuntimeError:
conf.fatal("Python development headers not found (-v for details).")
vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
conf.to_log("Configuration returned from %r:\n%r\n" % (pybin, '\n'.join(vals)))
dct = dict(zip(v, lst))
x = 'MACOSX_DEPLOYMENT_TARGET'
if dct[x]:
conf.env[x] = conf.environ[x] = dct[x]
env['pyext_PATTERN'] = '%s' + dct['SO'] # not a mistake
# Check for python libraries for embedding
all_flags = dct['LDFLAGS'] + ' ' + dct['CFLAGS']
conf.parse_flags(all_flags, 'PYEMBED')
all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
conf.parse_flags(all_flags, 'PYEXT')
result = None
#name = 'python' + env['PYTHON_VERSION']
# TODO simplify this
for name in ('python' + env['PYTHON_VERSION'], 'python' + env['PYTHON_VERSION'].replace('.', '')):
# LIBPATH_PYEMBED is already set; see if it works.
if not result and env['LIBPATH_PYEMBED']:
path = env['LIBPATH_PYEMBED']
conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in LIBPATH_PYEMBED' % name)
if not result and dct['LIBDIR']:
path = [dct['LIBDIR']]
conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in LIBDIR' % name)
if not result and dct['LIBPL']:
path = [dct['LIBPL']]
conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in python_LIBPL' % name)
if not result:
path = [os.path.join(dct['prefix'], "libs")]
conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in $prefix/libs' % name)
if result:
break # do not forget to set LIBPATH_PYEMBED
if result:
env['LIBPATH_PYEMBED'] = path
env.append_value('LIB_PYEMBED', [name])
else:
conf.to_log("\n\n### LIB NOT FOUND\n")
# under certain conditions, python extensions must link to
# python libraries, not just python embedding programs.
if (Utils.is_win32 or sys.platform.startswith('os2')
or dct['Py_ENABLE_SHARED']):
env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED']
env['LIB_PYEXT'] = env['LIB_PYEMBED']
# We check that pythonX.Y-config exists, and if it exists we
# use it to get only the includes, else fall back to distutils.
num = '.'.join(env['PYTHON_VERSION'].split('.')[:2])
conf.find_program(['python%s-config' % num, 'python-config-%s' % num, 'python%sm-config' % num], var='PYTHON_CONFIG', mandatory=False)
includes = []
if conf.env.PYTHON_CONFIG:
for incstr in conf.cmd_and_log([ conf.env.PYTHON_CONFIG, '--includes']).strip().split():
# strip the -I or /I
if (incstr.startswith('-I') or incstr.startswith('/I')):
incstr = incstr[2:]
# append include path, unless already given
if incstr not in includes:
includes.append(incstr)
conf.to_log("Include path for Python extensions "
"(found via python-config --includes): %r\n" % (includes,))
env['INCLUDES_PYEXT'] = includes
env['INCLUDES_PYEMBED'] = includes
else:
conf.to_log("Include path for Python extensions "
"(found via distutils module): %r\n" % (dct['INCLUDEPY'],))
env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
env['INCLUDES_PYEMBED'] = [dct['INCLUDEPY']]
# Code using the Python API needs to be compiled with -fno-strict-aliasing
if env['CC_NAME'] == 'gcc':
env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
if env['CXX_NAME'] == 'gcc':
env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])
if env.CC_NAME == "msvc":
from distutils.msvccompiler import MSVCCompiler
dist_compiler = MSVCCompiler()
dist_compiler.initialize()
env.append_value('CFLAGS_PYEXT', dist_compiler.compile_options)
env.append_value('CXXFLAGS_PYEXT', dist_compiler.compile_options)
env.append_value('LINKFLAGS_PYEXT', dist_compiler.ldflags_shared)
# See if it compiles
try:
conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H',
uselib='PYEMBED', fragment=FRAG,
errmsg='Could not find the python development headers')
except conf.errors.ConfigurationError:
# python3.2, oh yeah
conf.check_cfg(path=conf.env.PYTHON_CONFIG, package='', uselib_store='PYEMBED', args=['--cflags', '--libs'])
conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H', msg='Getting the python flags from python-config',
uselib='PYEMBED', fragment=FRAG,
errmsg='Could not find the python development headers elsewhere')
@conf
def check_python_version(conf, minver=None):
"""
Check if the python interpreter is found matching a given minimum version.
minver should be a tuple, eg. to check for python >= 2.4.2 pass (2,4,2) as minver.
If successful, PYTHON_VERSION is defined as 'MAJOR.MINOR'
(eg. '2.4') of the actual python version found, and PYTHONDIR is
defined, pointing to the site-packages directory appropriate for
this python version, where modules/packages/extensions should be
installed.
:param minver: minimum version
:type minver: tuple of int
"""
assert minver is None or isinstance(minver, tuple)
pybin = conf.env['PYTHON']
if not pybin:
conf.fatal('could not find the python executable')
# Get python version string
cmd = pybin + ['-c', 'import sys\nfor x in sys.version_info: print(str(x))']
debug('python: Running python command %r' % cmd)
lines = conf.cmd_and_log(cmd).split()
assert len(lines) == 5, "found %i lines, expected 5: %r" % (len(lines), lines)
pyver_tuple = (int(lines[0]), int(lines[1]), int(lines[2]), lines[3], int(lines[4]))
# compare python version with the minimum required
result = (minver is None) or (pyver_tuple >= minver)
if result:
# define useful environment variables
pyver = '.'.join([str(x) for x in pyver_tuple[:2]])
conf.env['PYTHON_VERSION'] = pyver
if 'PYTHONDIR' in conf.environ:
pydir = conf.environ['PYTHONDIR']
else:
if Utils.is_win32:
(python_LIBDEST, pydir) = \
conf.get_python_variables(
["get_config_var('LIBDEST') or ''",
"get_python_lib(standard_lib=0, prefix=%r) or ''" % conf.env['PREFIX']],
['from distutils.sysconfig import get_config_var, get_python_lib'])
else:
python_LIBDEST = None
(pydir,) = \
conf.get_python_variables(
["get_python_lib(standard_lib=0, prefix=%r) or ''" % conf.env['PREFIX']],
['from distutils.sysconfig import get_python_lib'])
if python_LIBDEST is None:
if conf.env['LIBDIR']:
python_LIBDEST = os.path.join(conf.env['LIBDIR'], "python" + pyver)
else:
python_LIBDEST = os.path.join(conf.env['PREFIX'], "lib", "python" + pyver)
if 'PYTHONARCHDIR' in conf.environ:
pyarchdir = conf.environ['PYTHONARCHDIR']
else:
(pyarchdir, ) = conf.get_python_variables(
["get_python_lib(plat_specific=1, standard_lib=0, prefix=%r) or ''" % conf.env['PREFIX']],
['from distutils.sysconfig import get_python_lib'])
if not pyarchdir:
pyarchdir = pydir
if hasattr(conf, 'define'): # conf.define is added by the C tool, so may not exist
conf.define('PYTHONDIR', pydir)
conf.define('PYTHONARCHDIR', pyarchdir)
conf.env['PYTHONDIR'] = pydir
conf.env['PYTHONARCHDIR'] = pyarchdir
# Feedback
pyver_full = '.'.join(map(str, pyver_tuple[:3]))
if minver is None:
conf.msg('Checking for python version', pyver_full)
else:
minver_str = '.'.join(map(str, minver))
conf.msg('Checking for python version', pyver_tuple, ">= %s" % (minver_str,) and 'GREEN' or 'YELLOW')
if not result:
conf.fatal('The python version is too old, expecting %r' % (minver,))
PYTHON_MODULE_TEMPLATE = '''
import %s
print(1)
'''
@conf
def check_python_module(conf, module_name):
"""
Check if the selected python interpreter can import the given python module::
def configure(conf):
conf.check_python_module('pygccxml')
:param module_name: module
:type module_name: string
"""
conf.start_msg('Python module %s' % module_name)
try:
conf.cmd_and_log(conf.env['PYTHON'] + ['-c', PYTHON_MODULE_TEMPLATE % module_name])
except:
conf.end_msg(False)
conf.fatal('Could not find the python module %r' % module_name)
conf.end_msg(True)
def configure(conf):
"""
Detect the python interpreter
"""
try:
conf.find_program('python', var='PYTHON')
except conf.errors.ConfigurationError:
warn("could not find a python executable, setting to sys.executable '%s'" % sys.executable)
conf.env.PYTHON = sys.executable
if conf.env.PYTHON != sys.executable:
warn("python executable '%s' different from sys.executable '%s'" % (conf.env.PYTHON, sys.executable))
conf.env.PYTHON = conf.cmd_to_list(conf.env.PYTHON)
v = conf.env
v['PYCMD'] = '"import sys, py_compile;py_compile.compile(sys.argv[1], sys.argv[2])"'
v['PYFLAGS'] = ''
v['PYFLAGS_OPT'] = '-O'
v['PYC'] = getattr(Options.options, 'pyc', 1)
v['PYO'] = getattr(Options.options, 'pyo', 1)
def options(opt):
"""
Add the options ``--nopyc`` and ``--nopyo``
"""
opt.add_option('--nopyc',
action='store_false',
default=1,
help = 'Do not install bytecode compiled .pyc files (configuration) [Default:install]',
dest = 'pyc')
opt.add_option('--nopyo',
action='store_false',
default=1,
help='Do not install optimised compiled .pyo files (configuration) [Default:install]',
dest='pyo')
| zy901002-gpsr | waf-tools/python.py | Python | gpl2 | 16,228 |
# -*- mode: python; encoding: utf-8 -*-
# Gustavo Carneiro (gjamc) 2008
import Options
import Configure
import subprocess
import config_c
import sys
def configure(conf):
pkg_config = conf.find_program('pkg-config', var='PKG_CONFIG')
if not pkg_config: return
@Configure.conf
def pkg_check_modules(conf, uselib_name, expression, mandatory=True):
pkg_config = conf.env['PKG_CONFIG']
if not pkg_config:
if mandatory:
conf.fatal("pkg-config is not available")
else:
return False
if Options.options.verbose:
extra_msg = ' (%s)' % expression
else:
extra_msg = ''
conf.start_msg('Checking for pkg-config flags for %s%s' % (uselib_name, extra_msg))
argv = [pkg_config, '--cflags', '--libs', expression]
cmd = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
retval = cmd.wait()
conf.to_log('%r: %r (exit code %i)\n%s' % (argv, out, retval, err))
if retval != 0:
conf.end_msg(False)
sys.stderr.write(err)
else:
if Options.options.verbose:
conf.end_msg(out)
else:
conf.end_msg(True)
if retval == 0:
conf.parse_flags(out, uselib_name, conf.env)
conf.env[uselib_name] = True
return True
else:
conf.env[uselib_name] = False
if mandatory:
raise Configure.ConfigurationError('pkg-config check failed')
else:
return False
@Configure.conf
def pkg_check_module_variable(conf, module, variable):
pkg_config = conf.env['PKG_CONFIG']
if not pkg_config:
conf.fatal("pkg-config is not available")
argv = [pkg_config, '--variable', variable, module]
cmd = subprocess.Popen(argv, stdout=subprocess.PIPE)
out, dummy = cmd.communicate()
retval = cmd.wait()
out = out.rstrip() # strip the trailing newline
msg_checking = ("Checking for pkg-config variable %r in %s" % (variable, module,))
conf.check_message_custom(msg_checking, '', out)
conf.log.write('%r: %r (exit code %i)\n' % (argv, out, retval))
if retval == 0:
return out
else:
raise Configure.ConfigurationError('pkg-config check failed')
| zy901002-gpsr | waf-tools/pkgconfig.py | Python | gpl2 | 2,015 |
import Logs
import Options
import Utils
class CompilerTraits(object):
def get_warnings_flags(self, level):
"""get_warnings_flags(level) -> list of cflags"""
raise NotImplementedError
def get_optimization_flags(self, level):
"""get_optimization_flags(level) -> list of cflags"""
raise NotImplementedError
def get_debug_flags(self, level):
"""get_debug_flags(level) -> (list of cflags, list of cppdefines)"""
raise NotImplementedError
class GccTraits(CompilerTraits):
def __init__(self):
super(GccTraits, self).__init__()
# cumulative list of warnings per level
self.warnings_flags = [['-Wall'], ['-Werror'], ['-Wextra']]
def get_warnings_flags(self, level):
warnings = []
for l in range(level):
if l < len(self.warnings_flags):
warnings.extend(self.warnings_flags[l])
else:
break
return warnings
def get_optimization_flags(self, level):
if level == 0:
return ['-O0']
elif level == 1:
return ['-O']
elif level == 2:
return ['-O2']
elif level == 3:
return ['-O3']
def get_debug_flags(self, level):
if level == 0:
return (['-g0'], ['NDEBUG'])
elif level == 1:
return (['-g'], [])
elif level >= 2:
return (['-ggdb', '-g3'], ['_DEBUG'])
class IccTraits(CompilerTraits):
def __init__(self):
super(IccTraits, self).__init__()
# cumulative list of warnings per level
# icc is _very_ verbose with -Wall, -Werror is barely achievable
self.warnings_flags = [[], [], ['-Wall']]
def get_warnings_flags(self, level):
warnings = []
for l in range(level):
if l < len(self.warnings_flags):
warnings.extend(self.warnings_flags[l])
else:
break
return warnings
def get_optimization_flags(self, level):
if level == 0:
return ['-O0']
elif level == 1:
return ['-O']
elif level == 2:
return ['-O2']
elif level == 3:
return ['-O3']
def get_debug_flags(self, level):
if level == 0:
return (['-g0'], ['NDEBUG'])
elif level == 1:
return (['-g'], [])
elif level >= 2:
return (['-ggdb', '-g3'], ['_DEBUG'])
class MsvcTraits(CompilerTraits):
def __init__(self):
super(MsvcTraits, self).__init__()
# cumulative list of warnings per level
self.warnings_flags = [['/W2'], ['/WX'], ['/Wall']]
def get_warnings_flags(self, level):
warnings = []
for l in range(level):
if l < len(self.warnings_flags):
warnings.extend(self.warnings_flags[l])
else:
break
return warnings
def get_optimization_flags(self, level):
if level == 0:
return ['/Od']
elif level == 1:
return []
elif level == 2:
return ['/O2']
elif level == 3:
return ['/Ox']
def get_debug_flags(self, level):
if level == 0:
return ([], ['NDEBUG'])
elif level == 1:
return (['/ZI', '/RTC1'], [])
elif level >= 2:
return (['/ZI', '/RTC1'], ['_DEBUG'])
gcc = GccTraits()
icc = IccTraits()
msvc = MsvcTraits()
# how to map env['COMPILER_CC'] or env['COMPILER_CXX'] into a traits object
compiler_mapping = {
'gcc': gcc,
'g++': gcc,
'msvc': msvc,
'icc': icc,
'icpc': icc,
}
profiles = {
# profile name: [optimization_level, warnings_level, debug_level]
'default': [2, 1, 1],
'debug': [0, 2, 3],
'release': [3, 1, 0],
}
default_profile = 'default'
def options(opt):
assert default_profile in profiles
opt.add_option('-d', '--build-profile',
action='store',
default=default_profile,
help=("Specify the build profile. "
"Build profiles control the default compilation flags"
" used for C/C++ programs, if CCFLAGS/CXXFLAGS are not"
" set set in the environment. [Allowed Values: %s]"
% ", ".join([repr(p) for p in profiles.keys()])),
choices=profiles.keys(),
dest='build_profile')
def configure(conf):
cc = conf.env['COMPILER_CC'] or None
cxx = conf.env['COMPILER_CXX'] or None
if not (cc or cxx):
raise Utils.WafError("neither COMPILER_CC nor COMPILER_CXX are defined; "
"maybe the compiler_cc or compiler_cxx tool has not been configured yet?")
try:
compiler = compiler_mapping[cc]
except KeyError:
try:
compiler = compiler_mapping[cxx]
except KeyError:
Logs.warn("No compiler flags support for compiler %r or %r"
% (cc, cxx))
return
opt_level, warn_level, dbg_level = profiles[Options.options.build_profile]
optimizations = compiler.get_optimization_flags(opt_level)
debug, debug_defs = compiler.get_debug_flags(dbg_level)
warnings = compiler.get_warnings_flags(warn_level)
if cc and not conf.env['CCFLAGS']:
conf.env.append_value('CCFLAGS', optimizations)
conf.env.append_value('CCFLAGS', debug)
conf.env.append_value('CCFLAGS', warnings)
conf.env.append_value('CCDEFINES', debug_defs)
if cxx and not conf.env['CXXFLAGS']:
conf.env.append_value('CXXFLAGS', optimizations)
conf.env.append_value('CXXFLAGS', debug)
conf.env.append_value('CXXFLAGS', warnings)
conf.env.append_value('CXXDEFINES', debug_defs)
| zy901002-gpsr | waf-tools/cflags.py | Python | gpl2 | 4,919 |
#!/usr/bin/env python
# encoding: utf-8
#
# partially based on boost.py written by Gernot Vormayr
# written by Ruediger Sonderfeld <ruediger@c-plusplus.de>, 2008
# modified by Bjoern Michaelsen, 2008
# modified by Luca Fossati, 2008
# rewritten for waf 1.5.1, Thomas Nagy, 2008
# rewritten for waf 1.6.2, Sylvain Rouquette, 2011
'''
To add the boost tool to the waf file:
$ ./waf-light --tools=compat15,boost
or, if you have waf >= 1.6.2
$ ./waf update --files=boost
The wscript will look like:
def options(opt):
opt.load('compiler_cxx boost')
def configure(conf):
conf.load('compiler_cxx boost')
conf.check_boost(lib='system filesystem', mt=True, static=True)
def build(bld):
bld(source='main.cpp', target='app', use='BOOST')
'''
import sys
import re
from waflib import Utils, Logs
from waflib.Configure import conf
from waflib.Errors import WafError
BOOST_LIBS = ('/usr/lib', '/usr/local/lib',
'/opt/local/lib', '/sw/lib', '/lib')
BOOST_INCLUDES = ('/usr/include', '/usr/local/include',
'/opt/local/include', '/sw/include')
BOOST_VERSION_FILE = 'boost/version.hpp'
BOOST_VERSION_CODE = '''
#include <iostream>
#include <boost/version.hpp>
int main() { std::cout << BOOST_LIB_VERSION << std::endl; }
'''
# toolsets from {boost_dir}/tools/build/v2/tools/common.jam
PLATFORM = Utils.unversioned_sys_platform()
detect_intel = lambda env: (PLATFORM == 'win32') and 'iw' or 'il'
detect_clang = lambda env: (PLATFORM == 'darwin') and 'clang-darwin' or 'clang'
detect_mingw = lambda env: (re.search('MinGW', env.CXX[0])) and 'mgw' or 'gcc'
BOOST_TOOLSETS = {
'borland': 'bcb',
'clang': detect_clang,
'como': 'como',
'cw': 'cw',
'darwin': 'xgcc',
'edg': 'edg',
'g++': detect_mingw,
'gcc': detect_mingw,
'icpc': detect_intel,
'intel': detect_intel,
'kcc': 'kcc',
'kylix': 'bck',
'mipspro': 'mp',
'mingw': 'mgw',
'msvc': 'vc',
'qcc': 'qcc',
'sun': 'sw',
'sunc++': 'sw',
'tru64cxx': 'tru',
'vacpp': 'xlc'
}
def options(opt):
opt.add_option('--boost-includes', type='string',
default='', dest='boost_includes',
help='''path to the boost directory where the includes are
e.g. /boost_1_45_0/include''')
opt.add_option('--boost-libs', type='string',
default='', dest='boost_libs',
help='''path to the directory where the boost libs are
e.g. /boost_1_45_0/stage/lib''')
opt.add_option('--boost-static', action='store_true',
default=False, dest='boost_static',
help='link static libraries')
opt.add_option('--boost-mt', action='store_true',
default=False, dest='boost_mt',
help='select multi-threaded libraries')
opt.add_option('--boost-abi', type='string', default='', dest='boost_abi',
help='''select libraries with tags (dgsyp, d for debug),
see doc Boost, Getting Started, chapter 6.1''')
opt.add_option('--boost-toolset', type='string',
default='', dest='boost_toolset',
help='force a toolset e.g. msvc, vc90, \
gcc, mingw, mgw45 (default: auto)')
py_version = '%d%d' % (sys.version_info[0], sys.version_info[1])
opt.add_option('--boost-python', type='string',
default=py_version, dest='boost_python',
help='select the lib python with this version \
(default: %s)' % py_version)
@conf
def __boost_get_version_file(self, dir):
try:
return self.root.find_dir(dir).find_node(BOOST_VERSION_FILE)
except:
return None
@conf
def boost_get_version(self, dir):
"""silently retrieve the boost version number"""
re_but = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.*)"$', re.M)
try:
val = re_but.search(self.__boost_get_version_file(dir).read()).group(1)
except:
val = self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[dir],
execute=True, define_ret=True)
return val
@conf
def boost_get_includes(self, *k, **kw):
includes = k and k[0] or kw.get('includes', None)
if includes and self.__boost_get_version_file(includes):
return includes
for dir in BOOST_INCLUDES:
if self.__boost_get_version_file(dir):
return dir
if includes:
self.fatal('headers not found in %s' % includes)
else:
self.fatal('headers not found, use --boost-includes=/path/to/boost')
@conf
def boost_get_toolset(self, cc):
toolset = cc
if not cc:
build_platform = Utils.unversioned_sys_platform()
if build_platform in BOOST_TOOLSETS:
cc = build_platform
else:
cc = self.env.CXX_NAME
if cc in BOOST_TOOLSETS:
toolset = BOOST_TOOLSETS[cc]
return isinstance(toolset, str) and toolset or toolset(self.env)
@conf
def __boost_get_libs_path(self, *k, **kw):
''' return the lib path and all the files in it '''
if 'files' in kw:
return self.root.find_dir('.'), Utils.to_list(kw['files'])
libs = k and k[0] or kw.get('libs', None)
if libs:
path = self.root.find_dir(libs)
files = path.ant_glob('*boost_*')
if not libs or not files:
for dir in BOOST_LIBS:
try:
path = self.root.find_dir(dir)
files = path.ant_glob('*boost_*')
if files:
break
path = self.root.find_dir(dir + '64')
files = path.ant_glob('*boost_*')
if files:
break
except:
path = None
if not path:
if libs:
self.fatal('libs not found in %s' % libs)
else:
self.fatal('libs not found, \
use --boost-includes=/path/to/boost/lib')
return path, files
@conf
def boost_get_libs(self, *k, **kw):
'''
return the lib path and the required libs
according to the parameters
'''
path, files = self.__boost_get_libs_path(**kw)
t = []
if kw.get('mt', False):
t.append('mt')
if kw.get('abi', None):
t.append(kw['abi'])
tags = t and '(-%s)+' % '-'.join(t) or ''
toolset = '(-%s[0-9]{0,3})+' % self.boost_get_toolset(kw.get('toolset', ''))
version = '(-%s)+' % self.env.BOOST_VERSION
def find_lib(re_lib, files):
for file in files:
if re_lib.search(file.name):
return file
return None
def format_lib_name(name):
if name.startswith('lib'):
name = name[3:]
return name.split('.')[0]
libs = []
for lib in Utils.to_list(k and k[0] or kw.get('lib', None)):
py = (lib == 'python') and '(-py%s)+' % kw['python'] or ''
# Trying libraries, from most strict match to least one
for pattern in ['boost_%s%s%s%s%s' % (lib, toolset, tags, py, version),
'boost_%s%s%s%s' % (lib, tags, py, version),
'boost_%s%s%s' % (lib, tags, version),
# Give up trying to find the right version
'boost_%s%s%s%s' % (lib, toolset, tags, py),
'boost_%s%s%s' % (lib, tags, py),
'boost_%s%s' % (lib, tags)]:
file = find_lib(re.compile(pattern), files)
if file:
libs.append(format_lib_name(file.name))
break
else:
self.fatal('lib %s not found in %s' % (lib, path))
return path.abspath(), libs
@conf
def check_boost(self, *k, **kw):
"""
initialize boost
You can pass the same parameters as the command line (without "--boost-"),
but the command line has the priority.
"""
if not self.env['CXX']:
self.fatal('load a c++ compiler first, conf.load("compiler_cxx")')
params = {'lib': k and k[0] or kw.get('lib', None)}
for key, value in self.options.__dict__.items():
if not key.startswith('boost_'):
continue
key = key[len('boost_'):]
params[key] = value and value or kw.get(key, '')
var = kw.get('uselib_store', 'BOOST')
self.start_msg('Checking boost includes')
try:
self.env['INCLUDES_%s' % var] = self.boost_get_includes(**params)
self.env.BOOST_VERSION = self.boost_get_version(self.env['INCLUDES_%s' % var])
except WafError:
self.end_msg("not found", 'YELLOW')
raise
self.end_msg(self.env.BOOST_VERSION)
if Logs.verbose:
Logs.pprint('CYAN', ' path : %s' % self.env['INCLUDES_%s' % var])
if not params['lib']:
return
self.start_msg('Checking boost libs')
try:
suffix = params.get('static', 'ST') or ''
path, libs = self.boost_get_libs(**params)
except WafError:
self.end_msg("not found", 'YELLOW')
raise
self.env['%sLIBPATH_%s' % (suffix, var)] = [path]
self.env['%sLIB_%s' % (suffix, var)] = libs
self.end_msg('ok')
if Logs.verbose:
Logs.pprint('CYAN', ' path : %s' % path)
Logs.pprint('CYAN', ' libs : %s' % libs)
| zy901002-gpsr | waf-tools/boost.py | Python | gpl2 | 8,365 |
# Copyright (C) 2008 Gustavo J. A. M. Carneiro <gjcarneiro@gmail.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import shlex
import subprocess
import sys
import re
import os
env_var_rx = re.compile(r"^([a-zA-Z0-9_]+)=(\S+)$")
def debug(message):
print >> sys.stderr, message
if sys.platform == 'win32':
dev_null = open("NUL:", "w")
else:
dev_null = open("/dev/null", "w")
fcntl = fd = fl = None
try:
import fcntl
except ImportError:
pass
else:
fd = dev_null.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, fl | fcntl.FD_CLOEXEC)
del fcntl, fd, fl
def _open_out_file(filename):
if filename in ['NUL:', '/dev/null']:
return dev_null
else:
return open(filename, 'wb')
class Node(object):
pass
class Op(Node):
pass
class Pipe(Op):
pass
class And(Op):
pass
class Or(Op):
pass
class Command(Node):
class PIPE(object):
pass # PIPE is a constant
class STDOUT(object):
pass # PIPE is a constant
def __init__(self, name):
super(Command, self).__init__()
self.name = name # command name
self.argv = [name] # command argv
self.stdin = None
self.stdout = None
self.stderr = None
self.env_vars = None
def __repr__(self):
return "Command(%r, argv=%r, stdin=%r, stdout=%r, stderr=%r)" \
% (self.name, self.argv, self.stdin, self.stdout, self.stderr)
class Chdir(Node):
def __init__(self):
super(Chdir, self).__init__()
self.dir = None
def __repr__(self):
return "Chdir(%r)" \
% (self.dir)
class Pipeline(object):
def __init__(self):
self.current_command = None
self.pipeline = []
def _commit_command(self):
assert self.current_command is not None
self.pipeline.append(self.current_command)
self.current_command = None
def get_abbreviated_command(self):
l = []
for node in self.pipeline:
if isinstance(node, Command):
l.append(node.name)
if isinstance(node, Chdir):
l.append('cd %s' % node.dir)
elif isinstance(node, Pipe):
l.append('|')
elif isinstance(node, And):
l.append('&&')
elif isinstance(node, And):
l.append('||')
return ' '.join(l)
def parse(self, command):
self.current_command = None
self.pipeline = []
if isinstance(command, list):
tokens = list(command)
else:
tokens = shlex.split(command)
debug("command: shlex: %r" % (tokens,))
BEGIN, COMMAND, CHDIR, STDERR, STDOUT, STDIN = range(6)
state = BEGIN
self.current_command = None
env_vars = dict()
while tokens:
token = tokens.pop(0)
if state == BEGIN:
env_var_match = env_var_rx.match(token)
if env_var_match is not None:
env_vars[env_var_match.group(1)] = env_var_match.group(2)
else:
assert self.current_command is None
if token == 'cd':
self.current_command = Chdir()
assert not env_vars
state = CHDIR
else:
self.current_command = Command(token)
if env_vars:
self.current_command.env_vars = env_vars
env_vars = dict()
state = COMMAND
elif state == COMMAND:
if token == '>':
state = STDOUT
elif token == '2>':
state = STDERR
elif token == '2>&1':
assert self.current_command.stderr is None
self.current_command.stderr = Command.STDOUT
elif token == '<':
state = STDIN
elif token == '|':
assert self.current_command.stdout is None
self.current_command.stdout = Command.PIPE
self._commit_command()
self.pipeline.append(Pipe())
state = BEGIN
elif token == '&&':
self._commit_command()
self.pipeline.append(And())
state = BEGIN
elif token == '||':
self._commit_command()
self.pipeline.append(Or())
state = BEGIN
else:
self.current_command.argv.append(token)
elif state == CHDIR:
if token == '&&':
self._commit_command()
self.pipeline.append(And())
state = BEGIN
else:
assert self.current_command.dir is None
self.current_command.dir = token
elif state == STDOUT:
assert self.current_command.stdout is None
self.current_command.stdout = token
state = COMMAND
elif state == STDERR:
assert self.current_command.stderr is None
self.current_command.stderr = token
state = COMMAND
elif state == STDIN:
assert self.current_command.stdin is None
self.current_command.stdin = token
state = COMMAND
self._commit_command()
return self.pipeline
def _exec_piped_commands(self, commands):
retvals = []
for cmd in commands:
retvals.append(cmd.wait())
retval = 0
for r in retvals:
if r:
retval = retvals[-1]
break
return retval
def run(self, verbose=False):
pipeline = list(self.pipeline)
files_to_close = []
piped_commands = []
piped_commands_display = []
BEGIN, PIPE = range(2)
state = BEGIN
cwd = '.'
while pipeline:
node = pipeline.pop(0)
if isinstance(node, Chdir):
next_op = pipeline.pop(0)
assert isinstance(next_op, And)
cwd = os.path.join(cwd, node.dir)
if verbose:
piped_commands_display.append("cd %s &&" % node.dir)
continue
assert isinstance(node, (Command, Chdir))
cmd = node
if verbose:
if cmd.env_vars:
env_vars_str = ' '.join(['%s=%s' % (key, val) for key, val in cmd.env_vars.iteritems()])
piped_commands_display.append("%s %s" % (env_vars_str, ' '.join(cmd.argv)))
else:
piped_commands_display.append(' '.join(cmd.argv))
if state == PIPE:
stdin = piped_commands[-1].stdout
elif cmd.stdin is not None:
stdin = open(cmd.stdin, "r")
if verbose:
piped_commands_display.append('< %s' % cmd.stdin)
files_to_close.append(stdin)
else:
stdin = None
if cmd.stdout is None:
stdout = None
elif cmd.stdout is Command.PIPE:
stdout = subprocess.PIPE
else:
stdout = _open_out_file(cmd.stdout)
files_to_close.append(stdout)
if verbose:
piped_commands_display.append('> %s' % cmd.stdout)
if cmd.stderr is None:
stderr = None
elif cmd.stderr is Command.PIPE:
stderr = subprocess.PIPE
elif cmd.stderr is Command.STDOUT:
stderr = subprocess.STDOUT
if verbose:
piped_commands_display.append('2>&1')
else:
stderr = _open_out_file(cmd.stderr)
files_to_close.append(stderr)
if verbose:
piped_commands_display.append('2> %s' % cmd.stderr)
if cmd.env_vars:
env = dict(os.environ)
env.update(cmd.env_vars)
else:
env = None
if cwd == '.':
proc_cwd = None
else:
proc_cwd = cwd
debug("command: subprocess.Popen(argv=%r, stdin=%r, stdout=%r, stderr=%r, env_vars=%r, cwd=%r)"
% (cmd.argv, stdin, stdout, stderr, cmd.env_vars, proc_cwd))
proc = subprocess.Popen(cmd.argv, stdin=stdin, stdout=stdout, stderr=stderr, env=env, cwd=proc_cwd)
del stdin, stdout, stderr
piped_commands.append(proc)
try:
next_node = pipeline.pop(0)
except IndexError:
try:
retval = self._exec_piped_commands(piped_commands)
if verbose:
print "%s: exit code %i" % (' '.join(piped_commands_display), retval)
finally:
for f in files_to_close:
if f is not dev_null:
f.close()
files_to_close = []
return retval
else:
if isinstance(next_node, Pipe):
state = PIPE
piped_commands_display.append('|')
elif isinstance(next_node, Or):
try:
this_retval = self._exec_piped_commands(piped_commands)
finally:
for f in files_to_close:
if f is not dev_null:
f.close()
files_to_close = []
if this_retval == 0:
if verbose:
print "%s: exit code %i (|| is short-circuited)" % (' '.join(piped_commands_display), retval)
return this_retval
if verbose:
print "%s: exit code %i (|| proceeds)" % (' '.join(piped_commands_display), retval)
state = BEGIN
piped_commands = []
piped_commands_display = []
elif isinstance(next_node, And):
try:
this_retval = self._exec_piped_commands(piped_commands)
finally:
for f in files_to_close:
if f is not dev_null:
f.close()
files_to_close = []
if this_retval != 0:
if verbose:
print "%s: exit code %i (&& is short-circuited)" % (' '.join(piped_commands_display), retval)
return this_retval
if verbose:
print "%s: exit code %i (&& proceeds)" % (' '.join(piped_commands_display), retval)
state = BEGIN
piped_commands = []
piped_commands_display = []
def _main():
pipeline = Pipeline()
pipeline.parse('./foo.py 2>&1 < xxx | cat && ls')
print pipeline.run()
if __name__ == '__main__':
_main()
| zy901002-gpsr | waf-tools/shellcmd.py | Python | gpl2 | 12,146 |
#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2010 (ita)
"""
This tool is totally deprecated
Try using:
.pc.in files for .pc files
the feature intltool_in - see demos/intltool
make-like rules
"""
import shutil, re, os
from waflib import TaskGen, Node, Task, Utils, Build, Errors
from waflib.TaskGen import feature, after_method, before_method
from waflib.Logs import debug
def copy_attrs(orig, dest, names, only_if_set=False):
"""
copy class attributes from an object to another
"""
for a in Utils.to_list(names):
u = getattr(orig, a, ())
if u or not only_if_set:
setattr(dest, a, u)
def copy_func(tsk):
"Make a file copy. This might be used to make other kinds of file processing (even calling a compiler is possible)"
env = tsk.env
infile = tsk.inputs[0].abspath()
outfile = tsk.outputs[0].abspath()
try:
shutil.copy2(infile, outfile)
except (OSError, IOError):
return 1
else:
if tsk.chmod: os.chmod(outfile, tsk.chmod)
return 0
def action_process_file_func(tsk):
"Ask the function attached to the task to process it"
if not tsk.fun: raise Errors.WafError('task must have a function attached to it for copy_func to work!')
return tsk.fun(tsk)
@feature('cmd')
def apply_cmd(self):
"call a command everytime"
if not self.fun: raise Errors.WafError('cmdobj needs a function!')
tsk = Task.TaskBase()
tsk.fun = self.fun
tsk.env = self.env
self.tasks.append(tsk)
tsk.install_path = self.install_path
@feature('copy')
@before_method('process_source')
def apply_copy(self):
Utils.def_attrs(self, fun=copy_func)
self.default_install_path = 0
lst = self.to_list(self.source)
self.meths.remove('process_source')
for filename in lst:
node = self.path.find_resource(filename)
if not node: raise Errors.WafError('cannot find input file %s for processing' % filename)
target = self.target
if not target or len(lst)>1: target = node.name
# TODO the file path may be incorrect
newnode = self.path.find_or_declare(target)
tsk = self.create_task('copy', node, newnode)
tsk.fun = self.fun
tsk.chmod = getattr(self, 'chmod', Utils.O644)
if not tsk.env:
tsk.debug()
raise Errors.WafError('task without an environment')
def subst_func(tsk):
"Substitutes variables in a .in file"
m4_re = re.compile('@(\w+)@', re.M)
code = tsk.inputs[0].read() #Utils.readf(infile)
# replace all % by %% to prevent errors by % signs in the input file while string formatting
code = code.replace('%', '%%')
s = m4_re.sub(r'%(\1)s', code)
env = tsk.env
di = getattr(tsk, 'dict', {}) or getattr(tsk.generator, 'dict', {})
if not di:
names = m4_re.findall(code)
for i in names:
di[i] = env.get_flat(i) or env.get_flat(i.upper())
tsk.outputs[0].write(s % di)
@feature('subst')
@before_method('process_source')
def apply_subst(self):
Utils.def_attrs(self, fun=subst_func)
lst = self.to_list(self.source)
self.meths.remove('process_source')
self.dict = getattr(self, 'dict', {})
for filename in lst:
node = self.path.find_resource(filename)
if not node: raise Errors.WafError('cannot find input file %s for processing' % filename)
if self.target:
newnode = self.path.find_or_declare(self.target)
else:
newnode = node.change_ext('')
try:
self.dict = self.dict.get_merged_dict()
except AttributeError:
pass
if self.dict and not self.env['DICT_HASH']:
self.env = self.env.derive()
keys = list(self.dict.keys())
keys.sort()
lst = [self.dict[x] for x in keys]
self.env['DICT_HASH'] = str(Utils.h_list(lst))
tsk = self.create_task('copy', node, newnode)
tsk.fun = self.fun
tsk.dict = self.dict
tsk.dep_vars = ['DICT_HASH']
tsk.chmod = getattr(self, 'chmod', Utils.O644)
if not tsk.env:
tsk.debug()
raise Errors.WafError('task without an environment')
####################
## command-output ####
####################
class cmd_arg(object):
"""command-output arguments for representing files or folders"""
def __init__(self, name, template='%s'):
self.name = name
self.template = template
self.node = None
class input_file(cmd_arg):
def find_node(self, base_path):
assert isinstance(base_path, Node.Node)
self.node = base_path.find_resource(self.name)
if self.node is None:
raise Errors.WafError("Input file %s not found in " % (self.name, base_path))
def get_path(self, env, absolute):
if absolute:
return self.template % self.node.abspath()
else:
return self.template % self.node.srcpath()
class output_file(cmd_arg):
def find_node(self, base_path):
assert isinstance(base_path, Node.Node)
self.node = base_path.find_or_declare(self.name)
if self.node is None:
raise Errors.WafError("Output file %s not found in " % (self.name, base_path))
def get_path(self, env, absolute):
if absolute:
return self.template % self.node.abspath()
else:
return self.template % self.node.bldpath()
class cmd_dir_arg(cmd_arg):
def find_node(self, base_path):
assert isinstance(base_path, Node.Node)
self.node = base_path.find_dir(self.name)
if self.node is None:
raise Errors.WafError("Directory %s not found in " % (self.name, base_path))
class input_dir(cmd_dir_arg):
def get_path(self, dummy_env, dummy_absolute):
return self.template % self.node.abspath()
class output_dir(cmd_dir_arg):
def get_path(self, env, dummy_absolute):
return self.template % self.node.abspath()
class command_output(Task.Task):
color = "BLUE"
def __init__(self, env, command, command_node, command_args, stdin, stdout, cwd, os_env, stderr):
Task.Task.__init__(self, env=env)
assert isinstance(command, (str, Node.Node))
self.command = command
self.command_args = command_args
self.stdin = stdin
self.stdout = stdout
self.cwd = cwd
self.os_env = os_env
self.stderr = stderr
if command_node is not None: self.dep_nodes = [command_node]
self.dep_vars = [] # additional environment variables to look
def run(self):
task = self
#assert len(task.inputs) > 0
def input_path(node, template):
if task.cwd is None:
return template % node.bldpath()
else:
return template % node.abspath()
def output_path(node, template):
fun = node.abspath
if task.cwd is None: fun = node.bldpath
return template % fun()
if isinstance(task.command, Node.Node):
argv = [input_path(task.command, '%s')]
else:
argv = [task.command]
for arg in task.command_args:
if isinstance(arg, str):
argv.append(arg)
else:
assert isinstance(arg, cmd_arg)
argv.append(arg.get_path(task.env, (task.cwd is not None)))
if task.stdin:
stdin = open(input_path(task.stdin, '%s'))
else:
stdin = None
if task.stdout:
stdout = open(output_path(task.stdout, '%s'), "w")
else:
stdout = None
if task.stderr:
stderr = open(output_path(task.stderr, '%s'), "w")
else:
stderr = None
if task.cwd is None:
cwd = ('None (actually %r)' % os.getcwd())
else:
cwd = repr(task.cwd)
debug("command-output: cwd=%s, stdin=%r, stdout=%r, argv=%r" %
(cwd, stdin, stdout, argv))
if task.os_env is None:
os_env = os.environ
else:
os_env = task.os_env
command = Utils.subprocess.Popen(argv, stdin=stdin, stdout=stdout, stderr=stderr, cwd=task.cwd, env=os_env)
return command.wait()
@feature('command-output')
def init_cmd_output(self):
Utils.def_attrs(self,
stdin = None,
stdout = None,
stderr = None,
# the command to execute
command = None,
# whether it is an external command; otherwise it is assumed
# to be an executable binary or script that lives in the
# source or build tree.
command_is_external = False,
# extra parameters (argv) to pass to the command (excluding
# the command itself)
argv = [],
# dependencies to other objects -> this is probably not what you want (ita)
# values must be 'task_gen' instances (not names!)
dependencies = [],
# dependencies on env variable contents
dep_vars = [],
# input files that are implicit, i.e. they are not
# stdin, nor are they mentioned explicitly in argv
hidden_inputs = [],
# output files that are implicit, i.e. they are not
# stdout, nor are they mentioned explicitly in argv
hidden_outputs = [],
# change the subprocess to this cwd (must use obj.input_dir() or output_dir() here)
cwd = None,
# OS environment variables to pass to the subprocess
# if None, use the default environment variables unchanged
os_env = None)
@feature('command-output')
@after_method('init_cmd_output')
def apply_cmd_output(self):
if self.command is None:
raise Errors.WafError("command-output missing command")
if self.command_is_external:
cmd = self.command
cmd_node = None
else:
cmd_node = self.path.find_resource(self.command)
assert cmd_node is not None, ('''Could not find command '%s' in source tree.
Hint: if this is an external command,
use command_is_external=True''') % (self.command,)
cmd = cmd_node
if self.cwd is None:
cwd = None
else:
assert isinstance(cwd, CmdDirArg)
self.cwd.find_node(self.path)
args = []
inputs = []
outputs = []
for arg in self.argv:
if isinstance(arg, cmd_arg):
arg.find_node(self.path)
if isinstance(arg, input_file):
inputs.append(arg.node)
if isinstance(arg, output_file):
outputs.append(arg.node)
if self.stdout is None:
stdout = None
else:
assert isinstance(self.stdout, str)
stdout = self.path.find_or_declare(self.stdout)
if stdout is None:
raise Errors.WafError("File %s not found" % (self.stdout,))
outputs.append(stdout)
if self.stderr is None:
stderr = None
else:
assert isinstance(self.stderr, str)
stderr = self.path.find_or_declare(self.stderr)
if stderr is None:
raise Errors.WafError("File %s not found" % (self.stderr,))
outputs.append(stderr)
if self.stdin is None:
stdin = None
else:
assert isinstance(self.stdin, str)
stdin = self.path.find_resource(self.stdin)
if stdin is None:
raise Errors.WafError("File %s not found" % (self.stdin,))
inputs.append(stdin)
for hidden_input in self.to_list(self.hidden_inputs):
node = self.path.find_resource(hidden_input)
if node is None:
raise Errors.WafError("File %s not found in dir %s" % (hidden_input, self.path))
inputs.append(node)
for hidden_output in self.to_list(self.hidden_outputs):
node = self.path.find_or_declare(hidden_output)
if node is None:
raise Errors.WafError("File %s not found in dir %s" % (hidden_output, self.path))
outputs.append(node)
if not (inputs or getattr(self, 'no_inputs', None)):
raise Errors.WafError('command-output objects must have at least one input file or give self.no_inputs')
if not (outputs or getattr(self, 'no_outputs', None)):
raise Errors.WafError('command-output objects must have at least one output file or give self.no_outputs')
cwd = self.bld.variant_dir
task = command_output(self.env, cmd, cmd_node, self.argv, stdin, stdout, cwd, self.os_env, stderr)
task.generator = self
copy_attrs(self, task, 'before after ext_in ext_out', only_if_set=True)
self.tasks.append(task)
task.inputs = inputs
task.outputs = outputs
task.dep_vars = self.to_list(self.dep_vars)
for dep in self.dependencies:
assert dep is not self
dep.post()
for dep_task in dep.tasks:
task.set_run_after(dep_task)
if not task.inputs:
# the case for svnversion, always run, and update the output nodes
task.runnable_status = type(Task.TaskBase.run)(runnable_status, task, task.__class__) # always run
task.post_run = type(Task.TaskBase.run)(post_run, task, task.__class__)
# TODO the case with no outputs?
def post_run(self):
for x in self.outputs:
x.sig = Utils.h_file(x.abspath())
def runnable_status(self):
return self.RUN_ME
Task.task_factory('copy', vars=[], func=action_process_file_func)
| zy901002-gpsr | waf-tools/misc.py | Python | gpl2 | 11,741 |
import TaskGen# import feature, taskgen_method, before_method, task_gen
import Node, Task, Utils, Build
import subprocess
import Options
import shellcmd
#shellcmd.subprocess = pproc # the WAF version of the subprocess module is supposedly less buggy
from Logs import debug, error
shellcmd.debug = debug
import Task
import re
arg_rx = re.compile(r"(?P<dollar>\$\$)|(?P<subst>\$\{(?P<var>\w+)(?P<code>.*?)\})", re.M)
class command_task(Task.Task):
color = "BLUE"
def __init__(self, env, generator):
Task.Task.__init__(self, env=env, normal=1, generator=generator)
def __str__(self):
"string to display to the user"
env = self.env
src_str = ' '.join([a.nice_path(env) for a in self.inputs])
tgt_str = ' '.join([a.nice_path(env) for a in self.outputs])
if self.outputs:
sep = ' -> '
else:
sep = ''
pipeline = shellcmd.Pipeline()
pipeline.parse(self.generator.command)
cmd = pipeline.get_abbreviated_command()
return 'command (%s): %s%s%s\n' % (cmd, src_str, sep, tgt_str)
def _subst_arg(self, arg, direction, namespace):
"""
@param arg: the command argument (or stdin/stdout/stderr) to substitute
@param direction: direction of the argument: 'in', 'out', or None
"""
def repl(match):
if match.group('dollar'):
return "$"
elif match.group('subst'):
var = match.group('var')
code = match.group('code')
result = eval(var+code, namespace)
if isinstance(result, Node.Node):
if var == 'TGT':
return result.get_bld().abspath()
elif var == 'SRC':
return result.srcpath()
else:
raise ValueError("Bad subst variable %r" % var)
elif result is self.inputs:
if len(self.inputs) == 1:
return result[0].srcpath()
else:
raise ValueError("${SRC} requested but have multiple sources; which one?")
elif result is self.outputs:
if len(self.outputs) == 1:
return result[0].get_bld().abspath()
else:
raise ValueError("${TGT} requested but have multiple targets; which one?")
elif isinstance(result, list):
assert len(result) == 1
return result[0]
else:
return result
return None
return arg_rx.sub(repl, arg)
def run(self):
pipeline = shellcmd.Pipeline()
pipeline.parse(self.generator.command)
namespace = self.env.get_merged_dict()
if self.generator.variables is not None:
namespace.update(self.generator.variables)
namespace.update(env=self.env, SRC=self.inputs, TGT=self.outputs)
for cmd in pipeline.pipeline:
if isinstance(cmd, shellcmd.Command):
if isinstance(cmd.stdin, basestring):
cmd.stdin = self._subst_arg(cmd.stdin, 'in', namespace)
if isinstance(cmd.stdout, basestring):
cmd.stdout = self._subst_arg(cmd.stdout, 'out', namespace)
if isinstance(cmd.stderr, basestring):
cmd.stderr = self._subst_arg(cmd.stderr, 'out', namespace)
for argI in xrange(len(cmd.argv)):
cmd.argv[argI] = self._subst_arg(cmd.argv[argI], None, namespace)
if cmd.env_vars is not None:
env_vars = dict()
for name, value in cmd.env_vars.iteritems():
env_vars[name] = self._subst_arg(value, None, namespace)
cmd.env_vars = env_vars
elif isinstance(cmd, shellcmd.Chdir):
cmd.dir = self._subst_arg(cmd.dir, None, namespace)
return pipeline.run(verbose=(Options.options.verbose > 0))
@TaskGen.taskgen_method
@TaskGen.feature('command')
def init_command(self):
Utils.def_attrs(self,
# other variables that can be used in the command: ${VARIABLE}
variables = None,
rule='')
@TaskGen.feature('command')
@TaskGen.after_method('process_rule')
def apply_command(self):
#self.meths.remove('apply_core')
# create the task
task = self.create_task('command')
setattr(task, "dep_vars", getattr(self, "dep_vars", None))
# process the sources
inputs = []
for node in self.source:
inputs.append(node)
task.set_inputs(inputs)
task.set_outputs([self.path.find_or_declare(tgt) for tgt in self.to_list(self.target)])
self.source = ''
#Task.file_deps = Task.extract_deps
# class command_taskgen(task_gen):
# def __init__(self, *k, **kw):
# task_gen.__init__(self, *k, **kw)
# self.features.append('command')
| zy901002-gpsr | waf-tools/command.py | Python | gpl2 | 4,165 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
#
# Copyright (c) 2009 University of Washington
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import os
import sys
import time
import optparse
import subprocess
import threading
import Queue
import signal
import xml.dom.minidom
import shutil
import re
from utils import get_list_from_file
#
# XXX This should really be part of a waf command to list the configuration
# items relative to optional ns-3 pieces.
#
# A list of interesting configuration items in the waf configuration
# cache which we may be interested in when deciding on which examples
# to run and how to run them. These are set by waf during the
# configuration phase and the corresponding assignments are usually
# found in the associated subdirectory wscript files.
#
interesting_config_items = [
"NS3_ENABLED_MODULES",
"NS3_MODULE_PATH",
"NSC_ENABLED",
"ENABLE_REAL_TIME",
"ENABLE_THREADING",
"ENABLE_EXAMPLES",
"ENABLE_TESTS",
"EXAMPLE_DIRECTORIES",
"ENABLE_PYTHON_BINDINGS",
"ENABLE_CLICK",
"ENABLE_OPENFLOW",
]
NSC_ENABLED = False
ENABLE_REAL_TIME = False
ENABLE_THREADING = False
ENABLE_EXAMPLES = True
ENABLE_TESTS = True
ENABLE_CLICK = False
ENABLE_OPENFLOW = False
EXAMPLE_DIRECTORIES = []
#
# If the user has constrained us to run certain kinds of tests, we can tell waf
# to only build
#
core_kinds = ["bvt", "core", "system", "unit"]
#
# There are some special cases for test suites that kill valgrind. This is
# because NSC causes illegal instruction crashes when run under valgrind.
#
core_valgrind_skip_tests = [
"ns3-tcp-cwnd",
"nsc-tcp-loss",
"ns3-tcp-interoperability",
"routing-click",
]
#
# There are some special cases for test suites that fail when NSC is
# missing.
#
core_nsc_missing_skip_tests = [
"ns3-tcp-cwnd",
"nsc-tcp-loss",
"ns3-tcp-interoperability",
]
#
# Parse the examples-to-run file if it exists.
#
# This function adds any C++ examples or Python examples that are to be run
# to the lists in example_tests and python_tests, respectively.
#
def parse_examples_to_run_file(
examples_to_run_path,
cpp_executable_dir,
python_script_dir,
example_tests,
python_tests):
# Look for the examples-to-run file exists.
if os.path.exists(examples_to_run_path):
# Each tuple in the C++ list of examples to run contains
#
# (example_name, do_run, do_valgrind_run)
#
# where example_name is the executable to be run, do_run is a
# condition under which to run the example, and do_valgrind_run is
# a condition under which to run the example under valgrind. This
# is needed because NSC causes illegal instruction crashes with
# some tests when they are run under valgrind.
#
# Note that the two conditions are Python statements that
# can depend on waf configuration variables. For example,
#
# ("tcp-nsc-lfn", "NSC_ENABLED == True", "NSC_ENABLED == False"),
#
cpp_examples = get_list_from_file(examples_to_run_path, "cpp_examples")
for example_name, do_run, do_valgrind_run in cpp_examples:
example_path = os.path.join(cpp_executable_dir, example_name)
# Add all of the C++ examples that were built, i.e. found
# in the directory, to the list of C++ examples to run.
if os.path.exists(example_path):
example_tests.append((example_path, do_run, do_valgrind_run))
# Each tuple in the Python list of examples to run contains
#
# (example_name, do_run)
#
# where example_name is the Python script to be run and
# do_run is a condition under which to run the example.
#
# Note that the condition is a Python statement that can
# depend on waf configuration variables. For example,
#
# ("realtime-udp-echo.py", "ENABLE_REAL_TIME == True"),
#
python_examples = get_list_from_file(examples_to_run_path, "python_examples")
for example_name, do_run in python_examples:
example_path = os.path.join(python_script_dir, example_name)
# Add all of the Python examples that were found to the
# list of Python examples to run.
if os.path.exists(example_path):
python_tests.append((example_path, do_run))
#
# The test suites are going to want to output status. They are running
# concurrently. This means that unless we are careful, the output of
# the test suites will be interleaved. Rather than introducing a lock
# file that could unintentionally start serializing execution, we ask
# the tests to write their output to a temporary directory and then
# put together the final output file when we "join" the test tasks back
# to the main thread. In addition to this issue, the example programs
# often write lots and lots of trace files which we will just ignore.
# We put all of them into the temp directory as well, so they can be
# easily deleted.
#
TMP_OUTPUT_DIR = "testpy-output"
def read_test(test):
result = test.find('Result').text
name = test.find('Name').text
if not test.find('Time') is None:
time_real = test.find('Time').get('real')
else:
time_real = ''
return (result, name, time_real)
#
# A simple example of writing a text file with a test result summary. It is
# expected that this output will be fine for developers looking for problems.
#
def node_to_text (test, f):
(result, name, time_real) = read_test(test)
output = "%s: Test Suite \"%s\" (%s)\n" % (result, name, time_real)
f.write(output)
for details in test.findall('FailureDetails'):
f.write(" Details:\n")
f.write(" Message: %s\n" % details.find('Message').text)
f.write(" Condition: %s\n" % details.find('Condition').text)
f.write(" Actual: %s\n" % details.find('Actual').text)
f.write(" Limit: %s\n" % details.find('Limit').text)
f.write(" File: %s\n" % details.find('File').text)
f.write(" Line: %s\n" % details.find('Line').text)
for child in test.findall('Test'):
node_to_text(child, f)
def translate_to_text(results_file, text_file):
f = open(text_file, 'w')
import xml.etree.ElementTree as ET
et = ET.parse (results_file)
for test in et.findall('Test'):
node_to_text (test, f)
for example in et.findall('Example'):
result = example.find('Result').text
name = example.find('Name').text
if not example.find('Time') is None:
time_real = example.find('Time').get('real')
else:
time_real = ''
output = "%s: Example \"%s\" (%s)\n" % (result, name, time_real)
f.write(output)
f.close()
#
# A simple example of writing an HTML file with a test result summary. It is
# expected that this will eventually be made prettier as time progresses and
# we have time to tweak it. This may end up being moved to a separate module
# since it will probably grow over time.
#
def translate_to_html(results_file, html_file):
f = open(html_file, 'w')
f.write("<html>\n")
f.write("<body>\n")
f.write("<center><h1>ns-3 Test Results</h1></center>\n")
#
# Read and parse the whole results file.
#
import xml.etree.ElementTree as ET
et = ET.parse(results_file)
#
# Iterate through the test suites
#
f.write("<h2>Test Suites</h2>\n")
for suite in et.findall('Test'):
#
# For each test suite, get its name, result and execution time info
#
(result, name, time) = read_test (suite)
#
# Print a level three header with the result, name and time. If the
# test suite passed, the header is printed in green. If the suite was
# skipped, print it in orange, otherwise assume something bad happened
# and print in red.
#
if result == "PASS":
f.write("<h3 style=\"color:green\">%s: %s (%s)</h3>\n" % (result, name, time))
elif result == "SKIP":
f.write("<h3 style=\"color:#ff6600\">%s: %s (%s)</h3>\n" % (result, name, time))
else:
f.write("<h3 style=\"color:red\">%s: %s (%s)</h3>\n" % (result, name, time))
#
# The test case information goes in a table.
#
f.write("<table border=\"1\">\n")
#
# The first column of the table has the heading Result
#
f.write("<th> Result </th>\n")
#
# If the suite crashed or is skipped, there is no further information, so just
# delare a new table row with the result (CRASH or SKIP) in it. Looks like:
#
# +--------+
# | Result |
# +--------+
# | CRASH |
# +--------+
#
# Then go on to the next test suite. Valgrind and skipped errors look the same.
#
if result in ["CRASH", "SKIP", "VALGR"]:
f.write("<tr>\n")
if result == "SKIP":
f.write("<td style=\"color:#ff6600\">%s</td>\n" % result)
else:
f.write("<td style=\"color:red\">%s</td>\n" % result)
f.write("</tr>\n")
f.write("</table>\n")
continue
#
# If the suite didn't crash, we expect more information, so fill out
# the table heading row. Like,
#
# +--------+----------------+------+
# | Result | Test Case Name | Time |
# +--------+----------------+------+
#
f.write("<th>Test Case Name</th>\n")
f.write("<th> Time </th>\n")
#
# If the test case failed, we need to print out some failure details
# so extend the heading row again. Like,
#
# +--------+----------------+------+-----------------+
# | Result | Test Case Name | Time | Failure Details |
# +--------+----------------+------+-----------------+
#
if result == "FAIL":
f.write("<th>Failure Details</th>\n")
#
# Now iterate through all of the test cases.
#
for case in suite.findall('Test'):
#
# Get the name, result and timing information from xml to use in
# printing table below.
#
(result, name, time) = read_test(case)
#
# If the test case failed, we iterate through possibly multiple
# failure details
#
if result == "FAIL":
#
# There can be multiple failures for each test case. The first
# row always gets the result, name and timing information along
# with the failure details. Remaining failures don't duplicate
# this information but just get blanks for readability. Like,
#
# +--------+----------------+------+-----------------+
# | Result | Test Case Name | Time | Failure Details |
# +--------+----------------+------+-----------------+
# | FAIL | The name | time | It's busted |
# +--------+----------------+------+-----------------+
# | | | | Really broken |
# +--------+----------------+------+-----------------+
# | | | | Busted bad |
# +--------+----------------+------+-----------------+
#
first_row = True
for details in case.findall('FailureDetails'):
#
# Start a new row in the table for each possible Failure Detail
#
f.write("<tr>\n")
if first_row:
first_row = False
f.write("<td style=\"color:red\">%s</td>\n" % result)
f.write("<td>%s</td>\n" % name)
f.write("<td>%s</td>\n" % time)
else:
f.write("<td></td>\n")
f.write("<td></td>\n")
f.write("<td></td>\n")
f.write("<td>")
f.write("<b>Message: </b>%s, " % details.find('Message').text)
f.write("<b>Condition: </b>%s, " % details.find('Condition').text)
f.write("<b>Actual: </b>%s, " % details.find('Actual').text)
f.write("<b>Limit: </b>%s, " % details.find('Limit').text)
f.write("<b>File: </b>%s, " % details.find('File').text)
f.write("<b>Line: </b>%s" % details.find('Line').text)
f.write("</td>\n")
#
# End the table row
#
f.write("</td>\n")
else:
#
# If this particular test case passed, then we just print the PASS
# result in green, followed by the test case name and its execution
# time information. These go off in <td> ... </td> table data.
# The details table entry is left blank.
#
# +--------+----------------+------+---------+
# | Result | Test Case Name | Time | Details |
# +--------+----------------+------+---------+
# | PASS | The name | time | |
# +--------+----------------+------+---------+
#
f.write("<tr>\n")
f.write("<td style=\"color:green\">%s</td>\n" % result)
f.write("<td>%s</td>\n" % name)
f.write("<td>%s</td>\n" % time)
f.write("<td></td>\n")
f.write("</tr>\n")
#
# All of the rows are written, so we need to end the table.
#
f.write("</table>\n")
#
# That's it for all of the test suites. Now we have to do something about
# our examples.
#
f.write("<h2>Examples</h2>\n")
#
# Example status is rendered in a table just like the suites.
#
f.write("<table border=\"1\">\n")
#
# The table headings look like,
#
# +--------+--------------+--------------+
# | Result | Example Name | Elapsed Time |
# +--------+--------------+--------------+
#
f.write("<th> Result </th>\n")
f.write("<th>Example Name</th>\n")
f.write("<th>Elapsed Time</th>\n")
#
# Now iterate through all of the examples
#
for example in et.findall("Example"):
#
# Start a new row for each example
#
f.write("<tr>\n")
#
# Get the result and name of the example in question
#
(result, name, time) = read_test(example)
#
# If the example either failed or crashed, print its result status
# in red; otherwise green. This goes in a <td> ... </td> table data
#
if result == "PASS":
f.write("<td style=\"color:green\">%s</td>\n" % result)
elif result == "SKIP":
f.write("<td style=\"color:#ff6600\">%s</fd>\n" % result)
else:
f.write("<td style=\"color:red\">%s</td>\n" % result)
#
# Write the example name as a new tag data.
#
f.write("<td>%s</td>\n" % name)
#
# Write the elapsed time as a new tag data.
#
f.write("<td>%s</td>\n" % time)
#
# That's it for the current example, so terminate the row.
#
f.write("</tr>\n")
#
# That's it for the table of examples, so terminate the table.
#
f.write("</table>\n")
#
# And that's it for the report, so finish up.
#
f.write("</body>\n")
f.write("</html>\n")
f.close()
#
# Python Control-C handling is broken in the presence of multiple threads.
# Signals get delivered to the runnable/running thread by default and if
# it is blocked, the signal is simply ignored. So we hook sigint and set
# a global variable telling the system to shut down gracefully.
#
thread_exit = False
def sigint_hook(signal, frame):
global thread_exit
thread_exit = True
return 0
#
# In general, the build process itself naturally takes care of figuring out
# which tests are built into the test runner. For example, if waf configure
# determines that ENABLE_EMU is false due to some missing dependency,
# the tests for the emu net device simply will not be built and will
# therefore not be included in the built test runner.
#
# Examples, however, are a different story. In that case, we are just given
# a list of examples that could be run. Instead of just failing, for example,
# nsc-tcp-zoo if NSC is not present, we look into the waf saved configuration
# for relevant configuration items.
#
# XXX This function pokes around in the waf internal state file. To be a
# little less hacky, we should add a commmand to waf to return this info
# and use that result.
#
def read_waf_config():
for line in open(".lock-wafbuild", "rt"):
if line.startswith("out_dir ="):
key, val = line.split('=')
out_dir = eval(val.strip())
global NS3_BUILDDIR
NS3_BUILDDIR = out_dir
for line in open("%s/c4che/_cache.py" % out_dir).readlines():
for item in interesting_config_items:
if line.startswith(item):
exec(line, globals())
if options.verbose:
for item in interesting_config_items:
print "%s ==" % item, eval(item)
#
# It seems pointless to fork a process to run waf to fork a process to run
# the test runner, so we just run the test runner directly. The main thing
# that waf would do for us would be to sort out the shared library path but
# we can deal with that easily and do here.
#
# There can be many different ns-3 repositories on a system, and each has
# its own shared libraries, so ns-3 doesn't hardcode a shared library search
# path -- it is cooked up dynamically, so we do that too.
#
def make_paths():
have_DYLD_LIBRARY_PATH = False
have_LD_LIBRARY_PATH = False
have_PATH = False
have_PYTHONPATH = False
keys = os.environ.keys()
for key in keys:
if key == "DYLD_LIBRARY_PATH":
have_DYLD_LIBRARY_PATH = True
if key == "LD_LIBRARY_PATH":
have_LD_LIBRARY_PATH = True
if key == "PATH":
have_PATH = True
if key == "PYTHONPATH":
have_PYTHONPATH = True
pypath = os.environ["PYTHONPATH"] = os.path.join (NS3_BUILDDIR, "bindings", "python")
if not have_PYTHONPATH:
os.environ["PYTHONPATH"] = pypath
else:
os.environ["PYTHONPATH"] += ":" + pypath
if options.verbose:
print "os.environ[\"PYTHONPATH\"] == %s" % os.environ["PYTHONPATH"]
if sys.platform == "darwin":
if not have_DYLD_LIBRARY_PATH:
os.environ["DYLD_LIBRARY_PATH"] = ""
for path in NS3_MODULE_PATH:
os.environ["DYLD_LIBRARY_PATH"] += ":" + path
if options.verbose:
print "os.environ[\"DYLD_LIBRARY_PATH\"] == %s" % os.environ["DYLD_LIBRARY_PATH"]
elif sys.platform == "win32":
if not have_PATH:
os.environ["PATH"] = ""
for path in NS3_MODULE_PATH:
os.environ["PATH"] += ';' + path
if options.verbose:
print "os.environ[\"PATH\"] == %s" % os.environ["PATH"]
elif sys.platform == "cygwin":
if not have_PATH:
os.environ["PATH"] = ""
for path in NS3_MODULE_PATH:
os.environ["PATH"] += ":" + path
if options.verbose:
print "os.environ[\"PATH\"] == %s" % os.environ["PATH"]
else:
if not have_LD_LIBRARY_PATH:
os.environ["LD_LIBRARY_PATH"] = ""
for path in NS3_MODULE_PATH:
os.environ["LD_LIBRARY_PATH"] += ":" + path
if options.verbose:
print "os.environ[\"LD_LIBRARY_PATH\"] == %s" % os.environ["LD_LIBRARY_PATH"]
#
# Short note on generating suppressions:
#
# See the valgrind documentation for a description of suppressions. The easiest
# way to generate a suppression expression is by using the valgrind
# --gen-suppressions option. To do that you have to figure out how to run the
# test in question.
#
# If you do "test.py -v -g -s <suitename> then test.py will output most of what
# you need. For example, if you are getting a valgrind error in the
# devices-mesh-dot11s-regression test suite, you can run:
#
# ./test.py -v -g -s devices-mesh-dot11s-regression
#
# You should see in the verbose output something that looks like:
#
# Synchronously execute valgrind --suppressions=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/testpy.supp
# --leak-check=full --error-exitcode=2 /home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/build/debug/utils/test-runner
# --suite=devices-mesh-dot11s-regression --basedir=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev
# --tempdir=testpy-output/2010-01-12-22-47-50-CUT
# --out=testpy-output/2010-01-12-22-47-50-CUT/devices-mesh-dot11s-regression.xml
#
# You need to pull out the useful pieces, and so could run the following to
# reproduce your error:
#
# valgrind --suppressions=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/testpy.supp
# --leak-check=full --error-exitcode=2 /home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/build/debug/utils/test-runner
# --suite=devices-mesh-dot11s-regression --basedir=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev
# --tempdir=testpy-output
#
# Hint: Use the first part of the command as is, and point the "tempdir" to
# somewhere real. You don't need to specify an "out" file.
#
# When you run the above command you should see your valgrind error. The
# suppression expression(s) can be generated by adding the --gen-suppressions=yes
# option to valgrind. Use something like:
#
# valgrind --gen-suppressions=yes --suppressions=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/testpy.supp
# --leak-check=full --error-exitcode=2 /home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/build/debug/utils/test-runner
# --suite=devices-mesh-dot11s-regression --basedir=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev
# --tempdir=testpy-output
#
# Now when valgrind detects an error it will ask:
#
# ==27235== ---- Print suppression ? --- [Return/N/n/Y/y/C/c] ----
#
# to which you just enter 'y'<ret>.
#
# You will be provided with a suppression expression that looks something like
# the following:
# {
# <insert_a_suppression_name_here>
# Memcheck:Addr8
# fun:_ZN3ns36dot11s15HwmpProtocolMac8SendPreqESt6vectorINS0_6IePreqESaIS3_EE
# fun:_ZN3ns36dot11s15HwmpProtocolMac10SendMyPreqEv
# fun:_ZN3ns36dot11s15HwmpProtocolMac18RequestDestinationENS_12Mac48AddressEjj
# ...
# the rest of the stack frame
# ...
# }
#
# You need to add a supression name which will only be printed out by valgrind in
# verbose mode (but it needs to be there in any case). The entire stack frame is
# shown to completely characterize the error, but in most cases you won't need
# all of that info. For example, if you want to turn off all errors that happen
# when the function (fun:) is called, you can just delete the rest of the stack
# frame. You can also use wildcards to make the mangled signatures more readable.
#
# I added the following to the testpy.supp file for this particular error:
#
# {
# Supress invalid read size errors in SendPreq() when using HwmpProtocolMac
# Memcheck:Addr8
# fun:*HwmpProtocolMac*SendPreq*
# }
#
# Now, when you run valgrind the error will be suppressed.
#
VALGRIND_SUPPRESSIONS_FILE = "testpy.supp"
def run_job_synchronously(shell_command, directory, valgrind, is_python, build_path=""):
(base, build) = os.path.split (NS3_BUILDDIR)
suppressions_path = os.path.join (base, VALGRIND_SUPPRESSIONS_FILE)
if is_python:
path_cmd = "python " + os.path.join (base, shell_command)
else:
if len(build_path):
path_cmd = os.path.join (build_path, shell_command)
else:
path_cmd = os.path.join (NS3_BUILDDIR, shell_command)
if valgrind:
cmd = "valgrind --suppressions=%s --leak-check=full --show-reachable=yes --error-exitcode=2 %s" % (suppressions_path,
path_cmd)
else:
cmd = path_cmd
if options.verbose:
print "Synchronously execute %s" % cmd
start_time = time.time()
proc = subprocess.Popen(cmd, shell = True, cwd = directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout_results, stderr_results = proc.communicate()
elapsed_time = time.time() - start_time
retval = proc.returncode
#
# valgrind sometimes has its own idea about what kind of memory management
# errors are important. We want to detect *any* leaks, so the way to do
# that is to look for the presence of a valgrind leak summary section.
#
# If another error has occurred (like a test suite has failed), we don't
# want to trump that error, so only do the valgrind output scan if the
# test has otherwise passed (return code was zero).
#
if valgrind and retval == 0 and "== LEAK SUMMARY:" in stderr_results:
retval = 2
if options.verbose:
print "Return code = ", retval
print "stderr = ", stderr_results
return (retval, stdout_results, stderr_results, elapsed_time)
#
# This class defines a unit of testing work. It will typically refer to
# a test suite to run using the test-runner, or an example to run directly.
#
class Job:
def __init__(self):
self.is_break = False
self.is_skip = False
self.is_example = False
self.is_pyexample = False
self.shell_command = ""
self.display_name = ""
self.basedir = ""
self.tempdir = ""
self.cwd = ""
self.tmp_file_name = ""
self.returncode = False
self.elapsed_time = 0
self.build_path = ""
#
# A job is either a standard job or a special job indicating that a worker
# thread should exist. This special job is indicated by setting is_break
# to true.
#
def set_is_break(self, is_break):
self.is_break = is_break
#
# If a job is to be skipped, we actually run it through the worker threads
# to keep the PASS, FAIL, CRASH and SKIP processing all in one place.
#
def set_is_skip(self, is_skip):
self.is_skip = is_skip
#
# Examples are treated differently than standard test suites. This is
# mostly because they are completely unaware that they are being run as
# tests. So we have to do some special case processing to make them look
# like tests.
#
def set_is_example(self, is_example):
self.is_example = is_example
#
# Examples are treated differently than standard test suites. This is
# mostly because they are completely unaware that they are being run as
# tests. So we have to do some special case processing to make them look
# like tests.
#
def set_is_pyexample(self, is_pyexample):
self.is_pyexample = is_pyexample
#
# This is the shell command that will be executed in the job. For example,
#
# "utils/test-runner --test-name=some-test-suite"
#
def set_shell_command(self, shell_command):
self.shell_command = shell_command
#
# This is the build path where ns-3 was built. For example,
#
# "/home/craigdo/repos/ns-3-allinone-test/ns-3-dev/build/debug"
#
def set_build_path(self, build_path):
self.build_path = build_path
#
# This is the dispaly name of the job, typically the test suite or example
# name. For example,
#
# "some-test-suite" or "udp-echo"
#
def set_display_name(self, display_name):
self.display_name = display_name
#
# This is the base directory of the repository out of which the tests are
# being run. It will be used deep down in the testing framework to determine
# where the source directory of the test was, and therefore where to find
# provided test vectors. For example,
#
# "/home/user/repos/ns-3-dev"
#
def set_basedir(self, basedir):
self.basedir = basedir
#
# This is the directory to which a running test suite should write any
# temporary files.
#
def set_tempdir(self, tempdir):
self.tempdir = tempdir
#
# This is the current working directory that will be given to an executing
# test as it is being run. It will be used for examples to tell them where
# to write all of the pcap files that we will be carefully ignoring. For
# example,
#
# "/tmp/unchecked-traces"
#
def set_cwd(self, cwd):
self.cwd = cwd
#
# This is the temporary results file name that will be given to an executing
# test as it is being run. We will be running all of our tests in parallel
# so there must be multiple temporary output files. These will be collected
# into a single XML file at the end and then be deleted.
#
def set_tmp_file_name(self, tmp_file_name):
self.tmp_file_name = tmp_file_name
#
# The return code received when the job process is executed.
#
def set_returncode(self, returncode):
self.returncode = returncode
#
# The elapsed real time for the job execution.
#
def set_elapsed_time(self, elapsed_time):
self.elapsed_time = elapsed_time
#
# The worker thread class that handles the actual running of a given test.
# Once spawned, it receives requests for work through its input_queue and
# ships the results back through the output_queue.
#
class worker_thread(threading.Thread):
def __init__(self, input_queue, output_queue):
threading.Thread.__init__(self)
self.input_queue = input_queue
self.output_queue = output_queue
def run(self):
while True:
job = self.input_queue.get()
#
# Worker threads continue running until explicitly told to stop with
# a special job.
#
if job.is_break:
return
#
# If the global interrupt handler sets the thread_exit variable,
# we stop doing real work and just report back a "break" in the
# normal command processing has happened.
#
if thread_exit == True:
job.set_is_break(True)
self.output_queue.put(job)
continue
#
# If we are actually supposed to skip this job, do so. Note that
# if is_skip is true, returncode is undefined.
#
if job.is_skip:
if options.verbose:
print "Skip %s" % job.shell_command
self.output_queue.put(job)
continue
#
# Otherwise go about the business of running tests as normal.
#
else:
if options.verbose:
print "Launch %s" % job.shell_command
if job.is_example or job.is_pyexample:
#
# If we have an example, the shell command is all we need to
# know. It will be something like "examples/udp-echo" or
# "examples/mixed-wireless.py"
#
(job.returncode, standard_out, standard_err, et) = run_job_synchronously(job.shell_command,
job.cwd, options.valgrind, job.is_pyexample, job.build_path)
else:
#
# If we're a test suite, we need to provide a little more info
# to the test runner, specifically the base directory and temp
# file name
#
if options.update_data:
update_data = '--update-data'
else:
update_data = ''
(job.returncode, standard_out, standard_err, et) = run_job_synchronously(job.shell_command +
" --xml --tempdir=%s --out=%s %s" % (job.tempdir, job.tmp_file_name, update_data),
job.cwd, options.valgrind, False)
job.set_elapsed_time(et)
if options.verbose:
print "returncode = %d" % job.returncode
print "---------- begin standard out ----------"
print standard_out
print "---------- begin standard err ----------"
print standard_err
print "---------- end standard err ----------"
self.output_queue.put(job)
#
# This is the main function that does the work of interacting with the test-runner
# itself.
#
def run_tests():
#
# Run waf to make sure that everything is built, configured and ready to go
# unless we are explicitly told not to. We want to be careful about causing
# our users pain while waiting for extraneous stuff to compile and link, so
# we allow users that know what they''re doing to not invoke waf at all.
#
if not options.nowaf:
#
# If the user is running the "kinds" or "list" options, there is an
# implied dependency on the test-runner since we call that program
# if those options are selected. We will exit after processing those
# options, so if we see them, we can safely only build the test-runner.
#
# If the user has constrained us to running only a particular type of
# file, we can only ask waf to build what we know will be necessary.
# For example, if the user only wants to run BVT tests, we only have
# to build the test-runner and can ignore all of the examples.
#
# If the user only wants to run a single example, then we can just build
# that example.
#
# If there is no constraint, then we have to build everything since the
# user wants to run everything.
#
if options.kinds or options.list or (len(options.constrain) and options.constrain in core_kinds):
if sys.platform == "win32":
waf_cmd = "waf --target=test-runner"
else:
waf_cmd = "./waf --target=test-runner"
elif len(options.example):
if sys.platform == "win32":
waf_cmd = "waf --target=%s" % os.path.basename(options.example)
else:
waf_cmd = "./waf --target=%s" % os.path.basename(options.example)
else:
if sys.platform == "win32":
waf_cmd = "waf"
else:
waf_cmd = "./waf"
if options.verbose:
print "Building: %s" % waf_cmd
proc = subprocess.Popen(waf_cmd, shell = True)
proc.communicate()
if proc.returncode:
print >> sys.stderr, "Waf died. Not running tests"
return proc.returncode
#
# Pull some interesting configuration information out of waf, primarily
# so we can know where executables can be found, but also to tell us what
# pieces of the system have been built. This will tell us what examples
# are runnable.
#
read_waf_config()
make_paths()
# Get the information from the build status file.
build_status_file = os.path.join (NS3_BUILDDIR, 'build-status.py')
if os.path.exists(build_status_file):
ns3_runnable_programs = get_list_from_file(build_status_file, "ns3_runnable_programs")
ns3_runnable_scripts = get_list_from_file(build_status_file, "ns3_runnable_scripts")
else:
print >> sys.stderr, 'The build status file was not found. You must do waf build before running test.py.'
sys.exit(2)
# Generate the lists of examples to run as smoke tests in order to
# ensure that they remain buildable and runnable over time.
#
example_tests = []
python_tests = []
for directory in EXAMPLE_DIRECTORIES:
# Set the directories and paths for this example.
example_directory = os.path.join("examples", directory)
examples_to_run_path = os.path.join(example_directory, "examples-to-run.py")
cpp_executable_dir = os.path.join(NS3_BUILDDIR, example_directory)
python_script_dir = os.path.join(example_directory)
# Parse this example directory's file.
parse_examples_to_run_file(
examples_to_run_path,
cpp_executable_dir,
python_script_dir,
example_tests,
python_tests)
for module in NS3_ENABLED_MODULES:
# Remove the "ns3-" from the module name.
module = module[len("ns3-"):]
# Set the directories and paths for this example.
module_directory = os.path.join("src", module)
example_directory = os.path.join(module_directory, "examples")
examples_to_run_path = os.path.join(module_directory, "test", "examples-to-run.py")
cpp_executable_dir = os.path.join(NS3_BUILDDIR, example_directory)
python_script_dir = os.path.join(example_directory)
# Parse this module's file.
parse_examples_to_run_file(
examples_to_run_path,
cpp_executable_dir,
python_script_dir,
example_tests,
python_tests)
#
# If lots of logging is enabled, we can crash Python when it tries to
# save all of the text. We just don't allow logging to be turned on when
# test.py runs. If you want to see logging output from your tests, you
# have to run them using the test-runner directly.
#
os.environ["NS_LOG"] = ""
#
# There are a couple of options that imply we can to exit before starting
# up a bunch of threads and running tests. Let's detect these cases and
# handle them without doing all of the hard work.
#
if options.kinds:
path_cmd = os.path.join("utils", "test-runner --print-test-type-list")
(rc, standard_out, standard_err, et) = run_job_synchronously(path_cmd, os.getcwd(), False, False)
print standard_out
if options.list:
path_cmd = os.path.join("utils", "test-runner --print-test-name-list")
(rc, standard_out, standard_err, et) = run_job_synchronously(path_cmd, os.getcwd(), False, False)
print standard_out
if options.kinds or options.list:
return
#
# We communicate results in two ways. First, a simple message relating
# PASS, FAIL, CRASH or SKIP is always written to the standard output. It
# is expected that this will be one of the main use cases. A developer can
# just run test.py with no options and see that all of the tests still
# pass.
#
# The second main use case is when detailed status is requested (with the
# --text or --html options). Typicall this will be text if a developer
# finds a problem, or HTML for nightly builds. In these cases, an
# XML file is written containing the status messages from the test suites.
# This file is then read and translated into text or HTML. It is expected
# that nobody will really be interested in the XML, so we write it somewhere
# with a unique name (time) to avoid collisions. In case an error happens, we
# provide a runtime option to retain the temporary files.
#
# When we run examples as smoke tests, they are going to want to create
# lots and lots of trace files. We aren't really interested in the contents
# of the trace files, so we also just stash them off in the temporary dir.
# The retain option also causes these unchecked trace files to be kept.
#
date_and_time = time.strftime("%Y-%m-%d-%H-%M-%S-CUT", time.gmtime())
if not os.path.exists(TMP_OUTPUT_DIR):
os.makedirs(TMP_OUTPUT_DIR)
testpy_output_dir = os.path.join(TMP_OUTPUT_DIR, date_and_time);
if not os.path.exists(testpy_output_dir):
os.makedirs(testpy_output_dir)
#
# Create the main output file and start filling it with XML. We need to
# do this since the tests will just append individual results to this file.
#
xml_results_file = os.path.join(testpy_output_dir, "results.xml")
f = open(xml_results_file, 'w')
f.write('<?xml version="1.0"?>\n')
f.write('<Results>\n')
f.close()
#
# We need to figure out what test suites to execute. We are either given one
# suite or example explicitly via the --suite or --example/--pyexample option,
# or we need to call into the test runner and ask it to list all of the available
# test suites. Further, we need to provide the constraint information if it
# has been given to us.
#
# This translates into allowing the following options with respect to the
# suites
#
# ./test,py: run all of the suites and examples
# ./test.py --constrain=core: run all of the suites of all kinds
# ./test.py --constrain=unit: run all unit suites
# ./test,py --suite=some-test-suite: run a single suite
# ./test,py --example=udp/udp-echo: run no test suites
# ./test,py --pyexample=wireless/mixed-wireless.py: run no test suites
# ./test,py --suite=some-suite --example=some-example: run the single suite
#
# We can also use the --constrain option to provide an ordering of test
# execution quite easily.
#
if len(options.suite):
# See if this is a valid test suite.
path_cmd = os.path.join("utils", "test-runner --print-test-name-list")
(rc, suites, standard_err, et) = run_job_synchronously(path_cmd, os.getcwd(), False, False)
if options.suite in suites:
suites = options.suite + "\n"
else:
print >> sys.stderr, 'The test suite was not run because an unknown test suite name was requested.'
sys.exit(2)
elif len(options.example) == 0 and len(options.pyexample) == 0:
if len(options.constrain):
path_cmd = os.path.join("utils", "test-runner --print-test-name-list --test-type=%s" % options.constrain)
(rc, suites, standard_err, et) = run_job_synchronously(path_cmd, os.getcwd(), False, False)
else:
path_cmd = os.path.join("utils", "test-runner --print-test-name-list")
(rc, suites, standard_err, et) = run_job_synchronously(path_cmd, os.getcwd(), False, False)
else:
suites = ""
#
# suite_list will either a single test suite name that the user has
# indicated she wants to run or a list of test suites provided by
# the test-runner possibly according to user provided constraints.
# We go through the trouble of setting up the parallel execution
# even in the case of a single suite to avoid having two process the
# results in two different places.
#
suite_list = suites.split('\n')
#
# We now have a possibly large number of test suites to run, so we want to
# run them in parallel. We're going to spin up a number of worker threads
# that will run our test jobs for us.
#
input_queue = Queue.Queue(0)
output_queue = Queue.Queue(0)
jobs = 0
threads=[]
#
# In Python 2.6 you can just use multiprocessing module, but we don't want
# to introduce that dependency yet; so we jump through a few hoops.
#
processors = 1
if sys.platform != "win32":
if 'SC_NPROCESSORS_ONLN'in os.sysconf_names:
processors = os.sysconf('SC_NPROCESSORS_ONLN')
else:
proc = subprocess.Popen("sysctl -n hw.ncpu", shell = True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout_results, stderr_results = proc.communicate()
if len(stderr_results) == 0:
processors = int(stdout_results)
#
# Now, spin up one thread per processor which will eventually mean one test
# per processor running concurrently.
#
for i in range(processors):
thread = worker_thread(input_queue, output_queue)
threads.append(thread)
thread.start()
#
# Keep track of some summary statistics
#
total_tests = 0
skipped_tests = 0
#
# We now have worker threads spun up, and a list of work to do. So, run
# through the list of test suites and dispatch a job to run each one.
#
# Dispatching will run with unlimited speed and the worker threads will
# execute as fast as possible from the queue.
#
# Note that we actually dispatch tests to be skipped, so all of the
# PASS, FAIL, CRASH and SKIP processing is done in the same place.
#
for test in suite_list:
test = test.strip()
if len(test):
job = Job()
job.set_is_example(False)
job.set_is_pyexample(False)
job.set_display_name(test)
job.set_tmp_file_name(os.path.join(testpy_output_dir, "%s.xml" % test))
job.set_cwd(os.getcwd())
job.set_basedir(os.getcwd())
job.set_tempdir(testpy_output_dir)
if (options.multiple):
multiple = ""
else:
multiple = " --stop-on-failure"
path_cmd = os.path.join("utils", "test-runner --test-name=%s%s" % (test, multiple))
job.set_shell_command(path_cmd)
if options.valgrind and test in core_valgrind_skip_tests:
job.set_is_skip(True)
# Skip tests that will fail if NSC is missing.
if not NSC_ENABLED and test in core_nsc_missing_skip_tests:
job.set_is_skip(True)
if options.verbose:
print "Queue %s" % test
input_queue.put(job)
jobs = jobs + 1
total_tests = total_tests + 1
#
# We've taken care of the discovered or specified test suites. Now we
# have to deal with examples run as smoke tests. We have a list of all of
# the example programs it makes sense to try and run. Each example will
# have a condition associated with it that must evaluate to true for us
# to try and execute it. This is used to determine if the example has
# a dependency that is not satisfied. For example, if an example depends
# on NSC being configured by waf, that example should have a condition
# that evaluates to true if NSC is enabled. For example,
#
# ("tcp-nsc-zoo", "NSC_ENABLED == True"),
#
# In this case, the example "tcp-nsc-zoo" will only be run if we find the
# waf configuration variable "NSC_ENABLED" to be True.
#
# We don't care at all how the trace files come out, so we just write them
# to a single temporary directory.
#
# XXX As it stands, all of the trace files have unique names, and so file
# collisions can only happen if two instances of an example are running in
# two versions of the test.py process concurrently. We may want to create
# uniquely named temporary traces directories to avoid this problem.
#
# We need to figure out what examples to execute. We are either given one
# suite or example explicitly via the --suite or --example option, or we
# need to walk the list of examples looking for available example
# conditions.
#
# This translates into allowing the following options with respect to the
# suites
#
# ./test,py: run all of the examples
# ./test.py --constrain=unit run no examples
# ./test.py --constrain=example run all of the examples
# ./test.py --suite=some-test-suite: run no examples
# ./test.py --example=some-example: run the single example
# ./test.py --suite=some-suite --example=some-example: run the single example
#
# XXX could use constrain to separate out examples used for performance
# testing
#
if len(options.suite) == 0 and len(options.example) == 0 and len(options.pyexample) == 0:
if len(options.constrain) == 0 or options.constrain == "example":
if ENABLE_EXAMPLES:
for test, do_run, do_valgrind_run in example_tests:
# Don't try to run this example if it isn't runnable.
if os.path.basename(test) in ns3_runnable_programs:
if eval(do_run):
job = Job()
job.set_is_example(True)
job.set_is_pyexample(False)
job.set_display_name(test)
job.set_tmp_file_name("")
job.set_cwd(testpy_output_dir)
job.set_basedir(os.getcwd())
job.set_tempdir(testpy_output_dir)
job.set_shell_command(test)
job.set_build_path("")
if options.valgrind and not eval(do_valgrind_run):
job.set_is_skip (True)
if options.verbose:
print "Queue %s" % test
input_queue.put(job)
jobs = jobs + 1
total_tests = total_tests + 1
elif len(options.example):
# Don't try to run this example if it isn't runnable.
example_name = os.path.basename(options.example)
if example_name not in ns3_runnable_programs:
print "Example %s is not runnable." % example_name
else:
#
# If you tell me to run an example, I will try and run the example
# irrespective of any condition.
#
job = Job()
job.set_is_example(True)
job.set_is_pyexample(False)
job.set_display_name(options.example)
job.set_tmp_file_name("")
job.set_cwd(testpy_output_dir)
job.set_basedir(os.getcwd())
job.set_tempdir(testpy_output_dir)
job.set_shell_command(options.example)
job.set_build_path(options.buildpath)
if options.verbose:
print "Queue %s" % options.example
input_queue.put(job)
jobs = jobs + 1
total_tests = total_tests + 1
#
# Run some Python examples as smoke tests. We have a list of all of
# the example programs it makes sense to try and run. Each example will
# have a condition associated with it that must evaluate to true for us
# to try and execute it. This is used to determine if the example has
# a dependency that is not satisfied.
#
# We don't care at all how the trace files come out, so we just write them
# to a single temporary directory.
#
# We need to figure out what python examples to execute. We are either
# given one pyexample explicitly via the --pyexample option, or we
# need to walk the list of python examples
#
# This translates into allowing the following options with respect to the
# suites
#
# ./test.py --constrain=pyexample run all of the python examples
# ./test.py --pyexample=some-example.py: run the single python example
#
if len(options.suite) == 0 and len(options.example) == 0 and len(options.pyexample) == 0:
if len(options.constrain) == 0 or options.constrain == "pyexample":
if ENABLE_EXAMPLES:
for test, do_run in python_tests:
# Don't try to run this example if it isn't runnable.
if os.path.basename(test) in ns3_runnable_scripts:
if eval(do_run):
job = Job()
job.set_is_example(False)
job.set_is_pyexample(True)
job.set_display_name(test)
job.set_tmp_file_name("")
job.set_cwd(testpy_output_dir)
job.set_basedir(os.getcwd())
job.set_tempdir(testpy_output_dir)
job.set_shell_command(test)
job.set_build_path("")
#
# Python programs and valgrind do not work and play
# well together, so we skip them under valgrind.
# We go through the trouble of doing all of this
# work to report the skipped tests in a consistent
# way throught the output formatter.
#
if options.valgrind:
job.set_is_skip (True)
#
# The user can disable python bindings, so we need
# to pay attention to that and give some feedback
# that we're not testing them
#
if not ENABLE_PYTHON_BINDINGS:
job.set_is_skip (True)
if options.verbose:
print "Queue %s" % test
input_queue.put(job)
jobs = jobs + 1
total_tests = total_tests + 1
elif len(options.pyexample):
# Don't try to run this example if it isn't runnable.
example_name = os.path.basename(options.pyexample)
if example_name not in ns3_runnable_scripts:
print "Example %s is not runnable." % example_name
else:
#
# If you tell me to run a python example, I will try and run the example
# irrespective of any condition.
#
job = Job()
job.set_is_pyexample(True)
job.set_display_name(options.pyexample)
job.set_tmp_file_name("")
job.set_cwd(testpy_output_dir)
job.set_basedir(os.getcwd())
job.set_tempdir(testpy_output_dir)
job.set_shell_command(options.pyexample)
job.set_build_path("")
if options.verbose:
print "Queue %s" % options.pyexample
input_queue.put(job)
jobs = jobs + 1
total_tests = total_tests + 1
#
# Tell the worker threads to pack up and go home for the day. Each one
# will exit when they see their is_break task.
#
for i in range(processors):
job = Job()
job.set_is_break(True)
input_queue.put(job)
#
# Now all of the tests have been dispatched, so all we have to do here
# in the main thread is to wait for them to complete. Keyboard interrupt
# handling is broken as mentioned above. We use a signal handler to catch
# sigint and set a global variable. When the worker threads sense this
# they stop doing real work and will just start throwing jobs back at us
# with is_break set to True. In this case, there are no real results so we
# ignore them. If there are real results, we always print PASS or FAIL to
# standard out as a quick indication of what happened.
#
passed_tests = 0
failed_tests = 0
crashed_tests = 0
valgrind_errors = 0
for i in range(jobs):
job = output_queue.get()
if job.is_break:
continue
if job.is_example or job.is_pyexample:
kind = "Example"
else:
kind = "TestSuite"
if job.is_skip:
status = "SKIP"
skipped_tests = skipped_tests + 1
else:
if job.returncode == 0:
status = "PASS"
passed_tests = passed_tests + 1
elif job.returncode == 1:
failed_tests = failed_tests + 1
status = "FAIL"
elif job.returncode == 2:
valgrind_errors = valgrind_errors + 1
status = "VALGR"
else:
crashed_tests = crashed_tests + 1
status = "CRASH"
print "%s: %s %s" % (status, kind, job.display_name)
if job.is_example or job.is_pyexample:
#
# Examples are the odd man out here. They are written without any
# knowledge that they are going to be run as a test, so we need to
# cook up some kind of output for them. We're writing an xml file,
# so we do some simple XML that says we ran the example.
#
# XXX We could add some timing information to the examples, i.e. run
# them through time and print the results here.
#
f = open(xml_results_file, 'a')
f.write('<Example>\n')
example_name = " <Name>%s</Name>\n" % job.display_name
f.write(example_name)
if status == "PASS":
f.write(' <Result>PASS</Result>\n')
elif status == "FAIL":
f.write(' <Result>FAIL</Result>\n')
elif status == "VALGR":
f.write(' <Result>VALGR</Result>\n')
elif status == "SKIP":
f.write(' <Result>SKIP</Result>\n')
else:
f.write(' <Result>CRASH</Result>\n')
f.write(' <Time real="%.3f"/>\n' % job.elapsed_time)
f.write('</Example>\n')
f.close()
else:
#
# If we're not running an example, we're running a test suite.
# These puppies are running concurrently and generating output
# that was written to a temporary file to avoid collisions.
#
# Now that we are executing sequentially in the main thread, we can
# concatenate the contents of the associated temp file to the main
# results file and remove that temp file.
#
# One thing to consider is that a test suite can crash just as
# well as any other program, so we need to deal with that
# possibility as well. If it ran correctly it will return 0
# if it passed, or 1 if it failed. In this case, we can count
# on the results file it saved being complete. If it crashed, it
# will return some other code, and the file should be considered
# corrupt and useless. If the suite didn't create any XML, then
# we're going to have to do it ourselves.
#
# Another issue is how to deal with a valgrind error. If we run
# a test suite under valgrind and it passes, we will get a return
# code of 0 and there will be a valid xml results file since the code
# ran to completion. If we get a return code of 1 under valgrind,
# the test case failed, but valgrind did not find any problems so the
# test case return code was passed through. We will have a valid xml
# results file here as well since the test suite ran. If we see a
# return code of 2, this means that valgrind found an error (we asked
# it to return 2 if it found a problem in run_job_synchronously) but
# the suite ran to completion so there is a valid xml results file.
# If the suite crashes under valgrind we will see some other error
# return code (like 139). If valgrind finds an illegal instruction or
# some other strange problem, it will die with its own strange return
# code (like 132). However, if the test crashes by itself, not under
# valgrind we will also see some other return code.
#
# If the return code is 0, 1, or 2, we have a valid xml file. If we
# get another return code, we have no xml and we can't really say what
# happened -- maybe the TestSuite crashed, maybe valgrind crashed due
# to an illegal instruction. If we get something beside 0-2, we assume
# a crash and fake up an xml entry. After this is all done, we still
# need to indicate a valgrind error somehow, so we fake up an xml entry
# with a VALGR result. Thus, in the case of a working TestSuite that
# fails valgrind, we'll see the PASS entry for the working TestSuite
# followed by a VALGR failing test suite of the same name.
#
if job.is_skip:
f = open(xml_results_file, 'a')
f.write("<Test>\n")
f.write(" <Name>%s</Name>\n" % job.display_name)
f.write(' <Result>SKIP</Result>\n')
f.write("</Test>\n")
f.close()
else:
if job.returncode == 0 or job.returncode == 1 or job.returncode == 2:
f_to = open(xml_results_file, 'a')
f_from = open(job.tmp_file_name)
f_to.write(f_from.read())
f_to.close()
f_from.close()
else:
f = open(xml_results_file, 'a')
f.write("<Test>\n")
f.write(" <Name>%s</Name>\n" % job.display_name)
f.write(' <Result>CRASH</Suite>\n')
f.write("</Test>\n")
f.close()
if job.returncode == 2:
f = open(xml_results_file, 'a')
f.write("<Test>\n")
f.write(" <Name>%s</Name>\n" % job.display_name)
f.write(' <Result>VALGR</Result>\n')
f.write("</Test>\n")
f.close()
#
# We have all of the tests run and the results written out. One final
# bit of housekeeping is to wait for all of the threads to close down
# so we can exit gracefully.
#
for thread in threads:
thread.join()
#
# Back at the beginning of time, we started the body of an XML document
# since the test suites and examples were going to just write their
# individual pieces. So, we need to finish off and close out the XML
# document
#
f = open(xml_results_file, 'a')
f.write('</Results>\n')
f.close()
#
# Print a quick summary of events
#
print "%d of %d tests passed (%d passed, %d skipped, %d failed, %d crashed, %d valgrind errors)" % (passed_tests,
total_tests, passed_tests, skipped_tests, failed_tests, crashed_tests, valgrind_errors)
#
# The last things to do are to translate the XML results file to "human
# readable form" if the user asked for it (or make an XML file somewhere)
#
if len(options.html):
translate_to_html(xml_results_file, options.html)
if len(options.text):
translate_to_text(xml_results_file, options.text)
if len(options.xml):
shutil.copyfile(xml_results_file, options.xml)
#
# Let the user know if they need to turn on tests or examples.
#
if not ENABLE_TESTS or not ENABLE_EXAMPLES:
print
if not ENABLE_TESTS:
print '*** Note: ns-3 tests are currently disabled. Enable them by adding'
print '*** "--enable-tests" to ./waf configure or modifying your .ns3rc file.'
print
if not ENABLE_EXAMPLES:
print '*** Note: ns-3 examples are currently disabled. Enable them by adding'
print '*** "--enable-examples" to ./waf configure or modifying your .ns3rc file.'
print
#
# If we have been asked to retain all of the little temporary files, we
# don't delete tm. If we do delete the temporary files, delete only the
# directory we just created. We don't want to happily delete any retained
# directories, which will probably surprise the user.
#
if not options.retain:
shutil.rmtree(testpy_output_dir)
if passed_tests + skipped_tests == total_tests:
return 0 # success
else:
return 1 # catchall for general errors
def main(argv):
parser = optparse.OptionParser()
parser.add_option("-b", "--buildpath", action="store", type="string", dest="buildpath", default="",
metavar="BUILDPATH",
help="specify the path where ns-3 was built (defaults to the build directory for the current variant)")
parser.add_option("-c", "--constrain", action="store", type="string", dest="constrain", default="",
metavar="KIND",
help="constrain the test-runner by kind of test")
parser.add_option("-e", "--example", action="store", type="string", dest="example", default="",
metavar="EXAMPLE",
help="specify a single example to run (with relative path)")
parser.add_option("-u", "--update-data", action="store_true", dest="update_data", default=False,
help="If examples use reference data files, get them to re-generate them")
parser.add_option("-g", "--grind", action="store_true", dest="valgrind", default=False,
help="run the test suites and examples using valgrind")
parser.add_option("-k", "--kinds", action="store_true", dest="kinds", default=False,
help="print the kinds of tests available")
parser.add_option("-l", "--list", action="store_true", dest="list", default=False,
help="print the list of known tests")
parser.add_option("-m", "--multiple", action="store_true", dest="multiple", default=False,
help="report multiple failures from test suites and test cases")
parser.add_option("-n", "--nowaf", action="store_true", dest="nowaf", default=False,
help="do not run waf before starting testing")
parser.add_option("-p", "--pyexample", action="store", type="string", dest="pyexample", default="",
metavar="PYEXAMPLE",
help="specify a single python example to run (with relative path)")
parser.add_option("-r", "--retain", action="store_true", dest="retain", default=False,
help="retain all temporary files (which are normally deleted)")
parser.add_option("-s", "--suite", action="store", type="string", dest="suite", default="",
metavar="TEST-SUITE",
help="specify a single test suite to run")
parser.add_option("-t", "--text", action="store", type="string", dest="text", default="",
metavar="TEXT-FILE",
help="write detailed test results into TEXT-FILE.txt")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
help="print progress and informational messages")
parser.add_option("-w", "--web", "--html", action="store", type="string", dest="html", default="",
metavar="HTML-FILE",
help="write detailed test results into HTML-FILE.html")
parser.add_option("-x", "--xml", action="store", type="string", dest="xml", default="",
metavar="XML-FILE",
help="write detailed test results into XML-FILE.xml")
global options
options = parser.parse_args()[0]
signal.signal(signal.SIGINT, sigint_hook)
return run_tests()
if __name__ == '__main__':
sys.exit(main(sys.argv))
| zy901002-gpsr | test.py | Python | gpl2 | 69,157 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* Test program for multi-interface host, static routing
Destination host (10.20.1.2)
|
| 10.20.1.0/24
DSTRTR
10.10.1.0/24 / \ 10.10.2.0/24
/ \
Rtr1 Rtr2
10.1.1.0/24 | | 10.1.2.0/24
| /
\ /
Source
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-list-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SocketBoundRoutingExample");
void SendStuff (Ptr<Socket> sock, Ipv4Address dstaddr, uint16_t port);
void BindSock (Ptr<Socket> sock, Ptr<NetDevice> netdev);
void srcSocketRecv (Ptr<Socket> socket);
void dstSocketRecv (Ptr<Socket> socket);
int
main (int argc, char *argv[])
{
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);
Ptr<Node> nSrc = CreateObject<Node> ();
Ptr<Node> nDst = CreateObject<Node> ();
Ptr<Node> nRtr1 = CreateObject<Node> ();
Ptr<Node> nRtr2 = CreateObject<Node> ();
Ptr<Node> nDstRtr = CreateObject<Node> ();
NodeContainer c = NodeContainer (nSrc, nDst, nRtr1, nRtr2, nDstRtr);
InternetStackHelper internet;
internet.Install (c);
// Point-to-point links
NodeContainer nSrcnRtr1 = NodeContainer (nSrc, nRtr1);
NodeContainer nSrcnRtr2 = NodeContainer (nSrc, nRtr2);
NodeContainer nRtr1nDstRtr = NodeContainer (nRtr1, nDstRtr);
NodeContainer nRtr2nDstRtr = NodeContainer (nRtr2, nDstRtr);
NodeContainer nDstRtrnDst = NodeContainer (nDstRtr, nDst);
// We create the channels first without any IP addressing information
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer dSrcdRtr1 = p2p.Install (nSrcnRtr1);
NetDeviceContainer dSrcdRtr2 = p2p.Install (nSrcnRtr2);
NetDeviceContainer dRtr1dDstRtr = p2p.Install (nRtr1nDstRtr);
NetDeviceContainer dRtr2dDstRtr = p2p.Install (nRtr2nDstRtr);
NetDeviceContainer dDstRtrdDst = p2p.Install (nDstRtrnDst);
Ptr<NetDevice> SrcToRtr1=dSrcdRtr1.Get (0);
Ptr<NetDevice> SrcToRtr2=dSrcdRtr2.Get (0);
// Later, we add IP addresses.
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer iSrciRtr1 = ipv4.Assign (dSrcdRtr1);
ipv4.SetBase ("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer iSrciRtr2 = ipv4.Assign (dSrcdRtr2);
ipv4.SetBase ("10.10.1.0", "255.255.255.0");
Ipv4InterfaceContainer iRtr1iDstRtr = ipv4.Assign (dRtr1dDstRtr);
ipv4.SetBase ("10.10.2.0", "255.255.255.0");
Ipv4InterfaceContainer iRtr2iDstRtr = ipv4.Assign (dRtr2dDstRtr);
ipv4.SetBase ("10.20.1.0", "255.255.255.0");
Ipv4InterfaceContainer iDstRtrDst = ipv4.Assign (dDstRtrdDst);
Ptr<Ipv4> ipv4Src = nSrc->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4Rtr1 = nRtr1->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4Rtr2 = nRtr2->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4DstRtr = nDstRtr->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4Dst = nDst->GetObject<Ipv4> ();
Ipv4StaticRoutingHelper ipv4RoutingHelper;
Ptr<Ipv4StaticRouting> staticRoutingSrc = ipv4RoutingHelper.GetStaticRouting (ipv4Src);
Ptr<Ipv4StaticRouting> staticRoutingRtr1 = ipv4RoutingHelper.GetStaticRouting (ipv4Rtr1);
Ptr<Ipv4StaticRouting> staticRoutingRtr2 = ipv4RoutingHelper.GetStaticRouting (ipv4Rtr2);
Ptr<Ipv4StaticRouting> staticRoutingDstRtr = ipv4RoutingHelper.GetStaticRouting (ipv4DstRtr);
Ptr<Ipv4StaticRouting> staticRoutingDst = ipv4RoutingHelper.GetStaticRouting (ipv4Dst);
// Create static routes from Src to Dst
staticRoutingRtr1->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address ("10.10.1.2"), 2);
staticRoutingRtr2->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address ("10.10.2.2"), 2);
// Two routes to same destination - setting separate metrics.
// You can switch these to see how traffic gets diverted via different routes
staticRoutingSrc->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address ("10.1.1.2"), 1,5);
staticRoutingSrc->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address ("10.1.2.2"), 2,10);
// Creating static routes from DST to Source pointing to Rtr1 VIA Rtr2(!)
staticRoutingDst->AddHostRouteTo (Ipv4Address ("10.1.1.1"), Ipv4Address ("10.20.1.1"), 1);
staticRoutingDstRtr->AddHostRouteTo (Ipv4Address ("10.1.1.1"), Ipv4Address ("10.10.2.1"), 2);
staticRoutingRtr2->AddHostRouteTo (Ipv4Address ("10.1.1.1"), Ipv4Address ("10.1.2.1"), 1);
// There are no apps that can utilize the Socket Option so doing the work directly..
// Taken from tcp-large-transfer example
Ptr<Socket> srcSocket = Socket::CreateSocket (nSrc, TypeId::LookupByName ("ns3::UdpSocketFactory"));
srcSocket->Bind ();
srcSocket->SetRecvCallback (MakeCallback (&srcSocketRecv));
Ptr<Socket> dstSocket = Socket::CreateSocket (nDst, TypeId::LookupByName ("ns3::UdpSocketFactory"));
uint16_t dstport = 12345;
Ipv4Address dstaddr ("10.20.1.2");
InetSocketAddress dst = InetSocketAddress (dstaddr, dstport);
dstSocket->Bind (dst);
dstSocket->SetRecvCallback (MakeCallback (&dstSocketRecv));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("socket-bound-static-routing.tr"));
p2p.EnablePcapAll ("socket-bound-static-routing");
LogComponentEnableAll (LOG_PREFIX_TIME);
LogComponentEnable ("SocketBoundRoutingExample", LOG_LEVEL_INFO);
// First packet as normal (goes via Rtr1)
Simulator::Schedule (Seconds (0.1),&SendStuff, srcSocket, dstaddr, dstport);
// Second via Rtr1 explicitly
Simulator::Schedule (Seconds (1.0),&BindSock, srcSocket, SrcToRtr1);
Simulator::Schedule (Seconds ( 1.1),&SendStuff, srcSocket, dstaddr, dstport);
// Third via Rtr2 explicitly
Simulator::Schedule (Seconds (2.0),&BindSock, srcSocket, SrcToRtr2);
Simulator::Schedule (Seconds (2.1),&SendStuff, srcSocket, dstaddr, dstport);
// Fourth again as normal (goes via Rtr1)
Simulator::Schedule (Seconds (3.0),&BindSock, srcSocket, Ptr<NetDevice>(0));
Simulator::Schedule (Seconds (3.1),&SendStuff, srcSocket, dstaddr, dstport);
// If you uncomment what's below, it results in ASSERT failing since you can't
// bind to a socket not existing on a node
// Simulator::Schedule(Seconds(4.0),&BindSock, srcSocket, dDstRtrdDst.Get(0));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
void SendStuff (Ptr<Socket> sock, Ipv4Address dstaddr, uint16_t port)
{
Ptr<Packet> p = Create<Packet> ();
p->AddPaddingAtEnd (100);
sock->SendTo (p, 0, InetSocketAddress (dstaddr,port));
return;
}
void BindSock (Ptr<Socket> sock, Ptr<NetDevice> netdev)
{
sock->BindToNetDevice (netdev);
return;
}
void
srcSocketRecv (Ptr<Socket> socket)
{
Address from;
Ptr<Packet> packet = socket->RecvFrom (from);
packet->RemoveAllPacketTags ();
packet->RemoveAllByteTags ();
NS_LOG_INFO ("Source Received " << packet->GetSize () << " bytes from " << InetSocketAddress::ConvertFrom (from).GetIpv4 ());
if (socket->GetBoundNetDevice ())
{
NS_LOG_INFO ("Socket was bound");
}
else
{
NS_LOG_INFO ("Socket was not bound");
}
}
void
dstSocketRecv (Ptr<Socket> socket)
{
Address from;
Ptr<Packet> packet = socket->RecvFrom (from);
packet->RemoveAllPacketTags ();
packet->RemoveAllByteTags ();
InetSocketAddress address = InetSocketAddress::ConvertFrom (from);
NS_LOG_INFO ("Destination Received " << packet->GetSize () << " bytes from " << address.GetIpv4 ());
NS_LOG_INFO ("Triggering packet back to source node's interface 1");
SendStuff (socket, Ipv4Address ("10.1.1.1"), address.GetPort ());
}
| zy901002-gpsr | examples/socket/socket-bound-static-routing.cc | C++ | gpl2 | 8,596 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
obj = bld.create_ns3_program('socket-bound-static-routing', ['network', 'csma', 'point-to-point', 'internet'])
obj.source = 'socket-bound-static-routing.cc'
obj = bld.create_ns3_program('socket-bound-tcp-static-routing', ['network', 'csma', 'point-to-point', 'internet'])
obj.source = 'socket-bound-tcp-static-routing.cc'
| zy901002-gpsr | examples/socket/wscript | Python | gpl2 | 440 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* Test program for multi-interface host, static routing
Destination host (10.20.1.2)
|
| 10.20.1.0/24
DSTRTR
10.10.1.0/24 / \ 10.10.2.0/24
/ \
Rtr1 Rtr2
10.1.1.0/24 | | 10.1.2.0/24
| /
\ /
Source
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-list-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SocketBoundTcpRoutingExample");
static const uint32_t totalTxBytes = 20000;
static uint32_t currentTxBytes = 0;
static const uint32_t writeSize = 1040;
uint8_t data[writeSize];
void StartFlow (Ptr<Socket>, Ipv4Address, uint16_t);
void WriteUntilBufferFull (Ptr<Socket>, uint32_t);
void SendStuff (Ptr<Socket> sock, Ipv4Address dstaddr, uint16_t port);
void BindSock (Ptr<Socket> sock, Ptr<NetDevice> netdev);
void srcSocketRecv (Ptr<Socket> socket);
void dstSocketRecv (Ptr<Socket> socket);
int
main (int argc, char *argv[])
{
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);
Ptr<Node> nSrc = CreateObject<Node> ();
Ptr<Node> nDst = CreateObject<Node> ();
Ptr<Node> nRtr1 = CreateObject<Node> ();
Ptr<Node> nRtr2 = CreateObject<Node> ();
Ptr<Node> nDstRtr = CreateObject<Node> ();
NodeContainer c = NodeContainer (nSrc, nDst, nRtr1, nRtr2, nDstRtr);
InternetStackHelper internet;
internet.Install (c);
// Point-to-point links
NodeContainer nSrcnRtr1 = NodeContainer (nSrc, nRtr1);
NodeContainer nSrcnRtr2 = NodeContainer (nSrc, nRtr2);
NodeContainer nRtr1nDstRtr = NodeContainer (nRtr1, nDstRtr);
NodeContainer nRtr2nDstRtr = NodeContainer (nRtr2, nDstRtr);
NodeContainer nDstRtrnDst = NodeContainer (nDstRtr, nDst);
// We create the channels first without any IP addressing information
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer dSrcdRtr1 = p2p.Install (nSrcnRtr1);
NetDeviceContainer dSrcdRtr2 = p2p.Install (nSrcnRtr2);
NetDeviceContainer dRtr1dDstRtr = p2p.Install (nRtr1nDstRtr);
NetDeviceContainer dRtr2dDstRtr = p2p.Install (nRtr2nDstRtr);
NetDeviceContainer dDstRtrdDst = p2p.Install (nDstRtrnDst);
Ptr<NetDevice> SrcToRtr1=dSrcdRtr1.Get (0);
Ptr<NetDevice> SrcToRtr2=dSrcdRtr2.Get (0);
// Later, we add IP addresses.
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer iSrciRtr1 = ipv4.Assign (dSrcdRtr1);
ipv4.SetBase ("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer iSrciRtr2 = ipv4.Assign (dSrcdRtr2);
ipv4.SetBase ("10.10.1.0", "255.255.255.0");
Ipv4InterfaceContainer iRtr1iDstRtr = ipv4.Assign (dRtr1dDstRtr);
ipv4.SetBase ("10.10.2.0", "255.255.255.0");
Ipv4InterfaceContainer iRtr2iDstRtr = ipv4.Assign (dRtr2dDstRtr);
ipv4.SetBase ("10.20.1.0", "255.255.255.0");
Ipv4InterfaceContainer iDstRtrDst = ipv4.Assign (dDstRtrdDst);
Ptr<Ipv4> ipv4Src = nSrc->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4Rtr1 = nRtr1->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4Rtr2 = nRtr2->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4DstRtr = nDstRtr->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4Dst = nDst->GetObject<Ipv4> ();
Ipv4StaticRoutingHelper ipv4RoutingHelper;
Ptr<Ipv4StaticRouting> staticRoutingSrc = ipv4RoutingHelper.GetStaticRouting (ipv4Src);
Ptr<Ipv4StaticRouting> staticRoutingRtr1 = ipv4RoutingHelper.GetStaticRouting (ipv4Rtr1);
Ptr<Ipv4StaticRouting> staticRoutingRtr2 = ipv4RoutingHelper.GetStaticRouting (ipv4Rtr2);
Ptr<Ipv4StaticRouting> staticRoutingDstRtr = ipv4RoutingHelper.GetStaticRouting (ipv4DstRtr);
Ptr<Ipv4StaticRouting> staticRoutingDst = ipv4RoutingHelper.GetStaticRouting (ipv4Dst);
// Create static routes from Src to Dst
staticRoutingRtr1->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address ("10.10.1.2"), 2);
staticRoutingRtr2->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address ("10.10.2.2"), 2);
// Two routes to same destination - setting separate metrics.
// You can switch these to see how traffic gets diverted via different routes
staticRoutingSrc->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address ("10.1.1.2"), 1,5);
staticRoutingSrc->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address ("10.1.2.2"), 2,10);
// Creating static routes from DST to Source pointing to Rtr1 VIA Rtr2(!)
staticRoutingDst->AddHostRouteTo (Ipv4Address ("10.1.1.1"), Ipv4Address ("10.20.1.1"), 1);
staticRoutingDstRtr->AddHostRouteTo (Ipv4Address ("10.1.1.1"), Ipv4Address ("10.10.2.1"), 2);
staticRoutingRtr2->AddHostRouteTo (Ipv4Address ("10.1.1.1"), Ipv4Address ("10.1.2.1"), 1);
staticRoutingDst->AddHostRouteTo (Ipv4Address ("10.1.2.1"), Ipv4Address ("10.20.1.1"), 1);
staticRoutingDstRtr->AddHostRouteTo (Ipv4Address ("10.1.2.1"), Ipv4Address ("10.10.2.1"), 2);
staticRoutingRtr2->AddHostRouteTo (Ipv4Address ("10.1.2.1"), Ipv4Address ("10.1.2.1"), 1);
// There are no apps that can utilize the Socket Option so doing the work directly..
// Taken from tcp-large-transfer example
Ptr<Socket> srcSocket1 = Socket::CreateSocket (nSrc, TypeId::LookupByName ("ns3::TcpSocketFactory"));
Ptr<Socket> srcSocket2 = Socket::CreateSocket (nSrc, TypeId::LookupByName ("ns3::TcpSocketFactory"));
Ptr<Socket> srcSocket3 = Socket::CreateSocket (nSrc, TypeId::LookupByName ("ns3::TcpSocketFactory"));
Ptr<Socket> srcSocket4 = Socket::CreateSocket (nSrc, TypeId::LookupByName ("ns3::TcpSocketFactory"));
uint16_t dstport = 12345;
Ipv4Address dstaddr ("10.20.1.2");
PacketSinkHelper sink ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), dstport));
ApplicationContainer apps = sink.Install (nDst);
apps.Start (Seconds (0.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("socket-bound-tcp-static-routing.tr"));
p2p.EnablePcapAll ("socket-bound-tcp-static-routing");
LogComponentEnableAll (LOG_PREFIX_TIME);
LogComponentEnable ("SocketBoundTcpRoutingExample", LOG_LEVEL_INFO);
// First packet as normal (goes via Rtr1)
Simulator::Schedule (Seconds (0.1),&StartFlow, srcSocket1, dstaddr, dstport);
// Second via Rtr1 explicitly
Simulator::Schedule (Seconds (1.0),&BindSock, srcSocket2, SrcToRtr1);
Simulator::Schedule (Seconds (1.1),&StartFlow, srcSocket2, dstaddr, dstport);
// Third via Rtr2 explicitly
Simulator::Schedule (Seconds (2.0),&BindSock, srcSocket3, SrcToRtr2);
Simulator::Schedule (Seconds (2.1),&StartFlow, srcSocket3, dstaddr, dstport);
// Fourth again as normal (goes via Rtr1)
Simulator::Schedule (Seconds (3.0),&BindSock, srcSocket4, Ptr<NetDevice>(0));
Simulator::Schedule (Seconds (3.1),&StartFlow, srcSocket4, dstaddr, dstport);
// If you uncomment what's below, it results in ASSERT failing since you can't
// bind to a socket not existing on a node
// Simulator::Schedule(Seconds(4.0),&BindSock, srcSocket, dDstRtrdDst.Get(0));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
void BindSock (Ptr<Socket> sock, Ptr<NetDevice> netdev)
{
sock->BindToNetDevice (netdev);
return;
}
void StartFlow (Ptr<Socket> localSocket,
Ipv4Address servAddress,
uint16_t servPort)
{
NS_LOG_INFO ("Starting flow at time " << Simulator::Now ().GetSeconds ());
currentTxBytes = 0;
localSocket->Bind ();
localSocket->Connect (InetSocketAddress (servAddress, servPort)); //connect
// tell the tcp implementation to call WriteUntilBufferFull again
// if we blocked and new tx buffer space becomes available
localSocket->SetSendCallback (MakeCallback (&WriteUntilBufferFull));
WriteUntilBufferFull (localSocket, localSocket->GetTxAvailable ());
}
void WriteUntilBufferFull (Ptr<Socket> localSocket, uint32_t txSpace)
{
while (currentTxBytes < totalTxBytes && localSocket->GetTxAvailable () > 0)
{
uint32_t left = totalTxBytes - currentTxBytes;
uint32_t dataOffset = currentTxBytes % writeSize;
uint32_t toWrite = writeSize - dataOffset;
toWrite = std::min (toWrite, left);
toWrite = std::min (toWrite, localSocket->GetTxAvailable ());
int amountSent = localSocket->Send (&data[dataOffset], toWrite, 0);
if(amountSent < 0)
{
// we will be called again when new tx space becomes available.
return;
}
currentTxBytes += amountSent;
}
localSocket->Close ();
}
| zy901002-gpsr | examples/socket/socket-bound-tcp-static-routing.cc | C++ | gpl2 | 9,532 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// Network topology
//
// n0
// \ 5 Mb/s, 2ms
// \ 1.5Mb/s, 10ms
// n2 -------------------------n3
// /
// / 5 Mb/s, 2ms
// n1
//
// - all links are point-to-point links with indicated one-way BW/delay
// - CBR/UDP flows from n0 to n3, and from n3 to n1
// - FTP/TCP flow from n0 to n3, starting at time 1.2 to time 1.35 sec.
// - UDP packet size of 210 bytes, with per-packet interval 0.00375 sec.
// (i.e., DataRate of 448,000 bps)
// - DropTail queues
// - Tracing of queues and packet receptions to file
// "simple-error-model.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SimpleErrorModelExample");
int
main (int argc, char *argv[])
{
// Users may find it convenient to turn on explicit debugging
// for selected modules; the below lines suggest how to do this
#if 0
LogComponentEnable ("SimplePointToPointExample", LOG_LEVEL_INFO);
#endif
// Set a few attributes
Config::SetDefault ("ns3::RateErrorModel::ErrorRate", DoubleValue (0.01));
Config::SetDefault ("ns3::RateErrorModel::ErrorUnit", StringValue ("EU_PKT"));
Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (210));
Config::SetDefault ("ns3::OnOffApplication::DataRate", DataRateValue (DataRate ("448kb/s")));
// Allow the user to override any of the defaults and the above
// Bind()s at run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);
// Here, we will explicitly create four nodes. In more sophisticated
// topologies, we could configure a node factory.
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (4);
NodeContainer n0n2 = NodeContainer (c.Get (0), c.Get (2));
NodeContainer n1n2 = NodeContainer (c.Get (1), c.Get (2));
NodeContainer n3n2 = NodeContainer (c.Get (3), c.Get (2));
InternetStackHelper internet;
internet.Install (c);
// We create the channels first without any IP addressing information
NS_LOG_INFO ("Create channels.");
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", DataRateValue (DataRate (5000000)));
p2p.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer d0d2 = p2p.Install (n0n2);
NetDeviceContainer d1d2 = p2p.Install (n1n2);
p2p.SetDeviceAttribute ("DataRate", DataRateValue (DataRate (1500000)));
p2p.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (10)));
NetDeviceContainer d3d2 = p2p.Install (n3n2);
// Later, we add IP addresses.
NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
ipv4.Assign (d0d2);
ipv4.SetBase ("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer i1i2 = ipv4.Assign (d1d2);
ipv4.SetBase ("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer i3i2 = ipv4.Assign (d3d2);
NS_LOG_INFO ("Use global routing.");
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Create the OnOff application to send UDP datagrams of size
// 210 bytes at a rate of 448 Kb/s
NS_LOG_INFO ("Create Applications.");
uint16_t port = 9; // Discard port (RFC 863)
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (i3i2.GetAddress (1), port)));
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
ApplicationContainer apps = onoff.Install (c.Get (0));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
// Create an optional packet sink to receive these packets
PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (c.Get (2));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
// Create a similar flow from n3 to n1, starting at time 1.1 seconds
onoff.SetAttribute ("Remote",
AddressValue (InetSocketAddress (i1i2.GetAddress (0), port)));
apps = onoff.Install (c.Get (3));
apps.Start (Seconds (1.1));
apps.Stop (Seconds (10.0));
// Create a packet sink to receive these packets
sink.SetAttribute ("Local",
AddressValue (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (c.Get (1));
apps.Start (Seconds (1.1));
apps.Stop (Seconds (10.0));
//
// Error model
//
// Create an ErrorModel based on the implementation (constructor)
// specified by the default classId
Ptr<RateErrorModel> em = CreateObjectWithAttributes<RateErrorModel> ("RanVar", RandomVariableValue (UniformVariable (0.0, 1.0)),
"ErrorRate", DoubleValue (0.001));
d3d2.Get (0)->SetAttribute ("ReceiveErrorModel", PointerValue (em));
// Now, let's use the ListErrorModel and explicitly force a loss
// of the packets with pkt-uids = 11 and 17 on node 2, device 0
std::list<uint32_t> sampleList;
sampleList.push_back (11);
sampleList.push_back (17);
// This time, we'll explicitly create the error model we want
Ptr<ListErrorModel> pem = CreateObject<ListErrorModel> ();
pem->SetList (sampleList);
d0d2.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (pem));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("simple-error-model.tr"));
p2p.EnablePcapAll ("simple-error-model");
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/error-model/simple-error-model.cc | C++ | gpl2 | 6,431 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("simple-error-model", "True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
| zy901002-gpsr | examples/error-model/examples-to-run.py | Python | gpl2 | 613 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
obj = bld.create_ns3_program('simple-error-model', ['point-to-point', 'internet', 'applications'])
obj.source = 'simple-error-model.cc'
| zy901002-gpsr | examples/error-model/wscript | Python | gpl2 | 245 |
#
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License version 2 as
# * published by the Free Software Foundation;
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Network topology
#
# n0 n1 n2 n3
# | | | |
# =================
# LAN
#
# - UDP flows from n0 to n1 and back
# - DropTail queues
# - Tracing of queues and packet receptions to file "udp-echo.tr"
import ns.applications
import ns.core
import ns.csma
import ns.internet
import ns.network
def main(argv):
#
# Allow the user to override any of the defaults and the above Bind() at
# run-time, via command-line arguments
#
cmd = ns.core.CommandLine()
cmd.Parse(argv)
#
# But since this is a realtime script, don't allow the user to mess with
# that.
#
ns.core.GlobalValue.Bind("SimulatorImplementationType", ns.core.StringValue("ns3::RealtimeSimulatorImpl"))
#
# Explicitly create the nodes required by the topology (shown above).
#
print "Create nodes."
n = ns.network.NodeContainer()
n.Create(4)
internet = ns.internet.InternetStackHelper()
internet.Install(n)
#
# Explicitly create the channels required by the topology (shown above).
#
print ("Create channels.")
csma = ns.csma.CsmaHelper()
csma.SetChannelAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.MilliSeconds(2)));
csma.SetDeviceAttribute("Mtu", ns.core.UintegerValue(1400))
d = csma.Install(n)
#
# We've got the "hardware" in place. Now we need to add IP addresses.
#
print ("Assign IP Addresses.")
ipv4 = ns.internet.Ipv4AddressHelper()
ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"), ns.network.Ipv4Mask("255.255.255.0"))
i = ipv4.Assign(d)
print ("Create Applications.")
#
# Create a UdpEchoServer application on node one.
#
port = 9 # well-known echo port number
server = ns.applications.UdpEchoServerHelper(port)
apps = server.Install(n.Get(1))
apps.Start(ns.core.Seconds(1.0))
apps.Stop(ns.core.Seconds(10.0))
#
# Create a UdpEchoClient application to send UDP datagrams from node zero to
# node one.
#
packetSize = 1024
maxPacketCount = 500
interPacketInterval = ns.core.Seconds(0.01)
client = ns.applications.UdpEchoClientHelper(i.GetAddress (1), port)
client.SetAttribute("MaxPackets", ns.core.UintegerValue(maxPacketCount))
client.SetAttribute("Interval", ns.core.TimeValue(interPacketInterval))
client.SetAttribute("PacketSize", ns.core.UintegerValue(packetSize))
apps = client.Install(n.Get(0))
apps.Start(ns.core.Seconds(2.0))
apps.Stop(ns.core.Seconds(10.0))
ascii = ns.network.AsciiTraceHelper()
csma.EnableAsciiAll(ascii.CreateFileStream("realtime-udp-echo.tr"))
csma.EnablePcapAll("realtime-udp-echo", False)
#
# Now, do the actual simulation.
#
print ("Run Simulation.")
ns.core.Simulator.Run()
ns.core.Simulator.Destroy()
print ("Done.")
if __name__ == '__main__':
import sys
main(sys.argv)
| zy901002-gpsr | examples/realtime/realtime-udp-echo.py | Python | gpl2 | 3,526 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Network topology
//
// n0 n1 n2 n3
// | | | |
// =================
// LAN
//
// - UDP flows from n0 to n1 and back
// - DropTail queues
// - Tracing of queues and packet receptions to file "udp-echo.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("RealtimeUdpEchoExample");
int
main (int argc, char *argv[])
{
//
// Allow the user to override any of the defaults and the above Bind() at
// run-time, via command-line arguments
//
CommandLine cmd;
cmd.Parse (argc, argv);
//
// But since this is a realtime script, don't allow the user to mess with
// that.
//
GlobalValue::Bind ("SimulatorImplementationType",
StringValue ("ns3::RealtimeSimulatorImpl"));
//
// Explicitly create the nodes required by the topology (shown above).
//
NS_LOG_INFO ("Create nodes.");
NodeContainer n;
n.Create (4);
InternetStackHelper internet;
internet.Install (n);
//
// Explicitly create the channels required by the topology (shown above).
//
NS_LOG_INFO ("Create channels.");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (DataRate (5000000)));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
csma.SetDeviceAttribute ("Mtu", UintegerValue (1400));
NetDeviceContainer d = csma.Install (n);
//
// We've got the "hardware" in place. Now we need to add IP addresses.
//
NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer i = ipv4.Assign (d);
NS_LOG_INFO ("Create Applications.");
//
// Create a UdpEchoServer application on node one.
//
uint16_t port = 9; // well-known echo port number
UdpEchoServerHelper server (port);
ApplicationContainer apps = server.Install (n.Get (1));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
//
// Create a UdpEchoClient application to send UDP datagrams from node zero to
// node one.
//
uint32_t packetSize = 1024;
uint32_t maxPacketCount = 500;
Time interPacketInterval = Seconds (0.01);
UdpEchoClientHelper client (i.GetAddress (1), port);
client.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
client.SetAttribute ("Interval", TimeValue (interPacketInterval));
client.SetAttribute ("PacketSize", UintegerValue (packetSize));
apps = client.Install (n.Get (0));
apps.Start (Seconds (2.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("realtime-udp-echo.tr"));
csma.EnablePcapAll ("realtime-udp-echo", false);
//
// Now, do the actual simulation.
//
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/realtime/realtime-udp-echo.cc | C++ | gpl2 | 3,657 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("realtime-udp-echo", "ENABLE_REAL_TIME == True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
| zy901002-gpsr | examples/realtime/examples-to-run.py | Python | gpl2 | 632 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
obj = bld.create_ns3_program('realtime-udp-echo', ['csma', 'internet'])
obj.source = 'realtime-udp-echo.cc'
bld.register_ns3_script('realtime-udp-echo.py', ['csma', 'internet', 'applications'])
| zy901002-gpsr | examples/realtime/wscript | Python | gpl2 | 308 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008-2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr>
*/
// Network topology
//
// n0 n1
// | |
// =================
// LAN
//
// - ICMPv6 echo request flows from n0 to n1 and back with ICMPv6 echo reply
// - DropTail queues
// - Tracing of queues and packet receptions to file "ping6.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("Ping6Example");
int main (int argc, char **argv)
{
#if 0
LogComponentEnable ("Ping6Example", LOG_LEVEL_INFO);
LogComponentEnable ("Ipv6EndPointDemux", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6L3Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6StaticRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6ListRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Interface", LOG_LEVEL_ALL);
LogComponentEnable ("Icmpv6L4Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ping6Application", LOG_LEVEL_ALL);
LogComponentEnable ("NdiscCache", LOG_LEVEL_ALL);
#endif
CommandLine cmd;
cmd.Parse (argc, argv);
NS_LOG_INFO ("Create nodes.");
NodeContainer n;
n.Create (4);
/* Install IPv4/IPv6 stack */
InternetStackHelper internetv6;
internetv6.SetIpv4StackInstall (false);
internetv6.Install (n);
NS_LOG_INFO ("Create channels.");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer d = csma.Install (n);
Ipv6AddressHelper ipv6;
NS_LOG_INFO ("Assign IPv6 Addresses.");
Ipv6InterfaceContainer i = ipv6.Assign (d);
NS_LOG_INFO ("Create Applications.");
/* Create a Ping6 application to send ICMPv6 echo request from node zero to
* all-nodes (ff02::1).
*/
uint32_t packetSize = 1024;
uint32_t maxPacketCount = 5;
Time interPacketInterval = Seconds (1.);
Ping6Helper ping6;
/*
ping6.SetLocal (i.GetAddress (0, 1));
ping6.SetRemote (i.GetAddress (1, 1));
*/
ping6.SetIfIndex (i.GetInterfaceIndex (0));
ping6.SetRemote (Ipv6Address::GetAllNodesMulticast ());
ping6.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
ping6.SetAttribute ("Interval", TimeValue (interPacketInterval));
ping6.SetAttribute ("PacketSize", UintegerValue (packetSize));
ApplicationContainer apps = ping6.Install (n.Get (0));
apps.Start (Seconds (2.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("ping6.tr"));
csma.EnablePcapAll (std::string ("ping6"), true);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/ipv6/ping6.cc | C++ | gpl2 | 3,535 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: David Gross <gdavid.devel@gmail.com>
*/
// Network topology
//
// STA2
// |
// |
// R1 R2
// | |
// | |
// ------------
// |
// |
// STA 1
//
// - Initial configuration :
// - STA1 default route : R1
// - R1 static route to STA2 : R2
// - STA2 default route : R2
// - STA1 send Echo Request to STA2 using its default route to R1
// - R1 receive Echo Request from STA1, and forward it to R2
// - R1 send an ICMPv6 Redirection to STA1 with Target STA2 and Destination R2
// - Next Echo Request from STA1 to STA2 are directly sent to R2
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv6-static-routing-helper.h"
#include "ns3/ipv6-routing-table-entry.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("Icmpv6RedirectExample");
/**
* \class StackHelper
* \brief Helper to set or get some IPv6 information about nodes.
*/
class StackHelper
{
public:
/**
* \brief Print the routing table.
* \param n the node
*/
inline void PrintRoutingTable (Ptr<Node>& n)
{
Ptr<Ipv6StaticRouting> routing = 0;
Ipv6StaticRoutingHelper routingHelper;
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
uint32_t nbRoutes = 0;
Ipv6RoutingTableEntry route;
routing = routingHelper.GetStaticRouting (ipv6);
std::cout << "Routing table of " << n << " : " << std::endl;
std::cout << "Destination\t\t\t\t" << "Gateway\t\t\t\t\t" << "Interface\t" << "Prefix to use" << std::endl;
nbRoutes = routing->GetNRoutes ();
for(uint32_t i = 0; i < nbRoutes; i++)
{
route = routing->GetRoute (i);
std::cout << route.GetDest () << "\t"
<< route.GetGateway () << "\t"
<< route.GetInterface () << "\t"
<< route.GetPrefixToUse () << "\t"
<< std::endl;
}
}
/**
* \brief Add an host route.
* \param n node
* \param dst destination address
* \param nextHop next hop for destination
* \param interface output interface
*/
inline void AddHostRouteTo (Ptr<Node>& n, Ipv6Address dst, Ipv6Address nextHop, uint32_t interface)
{
Ptr<Ipv6StaticRouting> routing = 0;
Ipv6StaticRoutingHelper routingHelper;
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
routing = routingHelper.GetStaticRouting (ipv6);
routing->AddHostRouteTo (dst, nextHop, interface);
}
};
int main (int argc, char **argv)
{
#if 0
LogComponentEnable ("Icmpv6RedirectExample", LOG_LEVEL_INFO);
LogComponentEnable ("Icmpv6L4Protocol", LOG_LEVEL_INFO);
LogComponentEnable ("Ipv6L3Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6StaticRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Interface", LOG_LEVEL_ALL);
LogComponentEnable ("Icmpv6L4Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("NdiscCache", LOG_LEVEL_ALL);
#endif
CommandLine cmd;
cmd.Parse (argc, argv);
NS_LOG_INFO ("Create nodes.");
Ptr<Node> sta1 = CreateObject<Node> ();
Ptr<Node> r1 = CreateObject<Node> ();
Ptr<Node> r2 = CreateObject<Node> ();
Ptr<Node> sta2 = CreateObject<Node> ();
NodeContainer net1 (sta1, r1, r2);
NodeContainer net2 (r2, sta2);
NodeContainer all (sta1, r1, r2, sta2);
StackHelper stackHelper;
InternetStackHelper internetv6;
internetv6.Install (all);
NS_LOG_INFO ("Create channels.");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer ndc1 = csma.Install (net1);
NetDeviceContainer ndc2 = csma.Install (net2);
NS_LOG_INFO ("Assign IPv6 Addresses.");
Ipv6AddressHelper ipv6;
ipv6.NewNetwork (Ipv6Address ("2001:1::"), 64);
Ipv6InterfaceContainer iic1 = ipv6.Assign (ndc1);
iic1.SetRouter (2, true);
iic1.SetRouter (1, true);
ipv6.NewNetwork (Ipv6Address ("2001:2::"), 64);
Ipv6InterfaceContainer iic2 = ipv6.Assign (ndc2);
iic2.SetRouter (0, true);
stackHelper.AddHostRouteTo (r1, iic2.GetAddress (1, 1), iic1.GetAddress (2, 1), iic1.GetInterfaceIndex (1));
Simulator::Schedule (Seconds (0.0), &StackHelper::PrintRoutingTable, &stackHelper, r1);
Simulator::Schedule (Seconds (3.0), &StackHelper::PrintRoutingTable, &stackHelper, sta1);
NS_LOG_INFO ("Create Applications.");
uint32_t packetSize = 1024;
uint32_t maxPacketCount = 5;
Time interPacketInterval = Seconds (1.);
Ping6Helper ping6;
ping6.SetLocal (iic1.GetAddress (0, 1));
ping6.SetRemote (iic2.GetAddress (1, 1));
ping6.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
ping6.SetAttribute ("Interval", TimeValue (interPacketInterval));
ping6.SetAttribute ("PacketSize", UintegerValue (packetSize));
ApplicationContainer apps = ping6.Install (sta1);
apps.Start (Seconds (2.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("icmpv6-redirect.tr"));
csma.EnablePcapAll ("icmpv6-redirect", true);
/* Now, do the actual simulation. */
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/ipv6/icmpv6-redirect.cc | C++ | gpl2 | 6,030 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: David Gross <gdavid.devel@gmail.com>
* Sebastien Vincent <vincent@clarinet.u-strasbg.fr>
*/
// Network topology
// //
// // n0 R n1
// // | _ |
// // ====|_|====
// // router
// // - R sends RA to n0's subnet (2001:1::/64);
// // - R sends RA to n1's subnet (2001:2::/64);
// // - n0 ping6 n1.
// //
// // - Tracing of queues and packet receptions to file "radvd.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/radvd.h"
#include "ns3/radvd-interface.h"
#include "ns3/radvd-prefix.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("RadvdExample");
int main (int argc, char** argv)
{
#if 0
LogComponentEnable ("Ipv6L3Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6RawSocketImpl", LOG_LEVEL_ALL);
LogComponentEnable ("Icmpv6L4Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6StaticRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Interface", LOG_LEVEL_ALL);
LogComponentEnable ("RadvdApplication", LOG_LEVEL_ALL);
LogComponentEnable ("Ping6Application", LOG_LEVEL_ALL);
#endif
CommandLine cmd;
cmd.Parse (argc, argv);
NS_LOG_INFO ("Create nodes.");
Ptr<Node> n0 = CreateObject<Node> ();
Ptr<Node> r = CreateObject<Node> ();
Ptr<Node> n1 = CreateObject<Node> ();
NodeContainer net1 (n0, r);
NodeContainer net2 (r, n1);
NodeContainer all (n0, r, n1);
NS_LOG_INFO ("Create IPv6 Internet Stack");
InternetStackHelper internetv6;
internetv6.Install (all);
NS_LOG_INFO ("Create channels.");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer d1 = csma.Install (net1); /* n0 - R */
NetDeviceContainer d2 = csma.Install (net2); /* R - n1 */
NS_LOG_INFO ("Create networks and assign IPv6 Addresses.");
Ipv6AddressHelper ipv6;
/* first subnet */
ipv6.NewNetwork (Ipv6Address ("2001:1::"), 64);
NetDeviceContainer tmp;
tmp.Add (d1.Get (0)); /* n0 */
Ipv6InterfaceContainer iic1 = ipv6.AssignWithoutAddress (tmp); /* n0 interface */
NetDeviceContainer tmp2;
tmp2.Add (d1.Get (1)); /* R */
Ipv6InterfaceContainer iicr1 = ipv6.Assign (tmp2); /* R interface to the first subnet is just statically assigned */
iicr1.SetRouter (0, true);
iic1.Add (iicr1);
/* second subnet R - n1 */
ipv6.NewNetwork (Ipv6Address ("2001:2::"), 64);
NetDeviceContainer tmp3;
tmp3.Add (d2.Get (0)); /* R */
Ipv6InterfaceContainer iicr2 = ipv6.Assign (tmp3); /* R interface */
iicr2.SetRouter (0, true);
NetDeviceContainer tmp4;
tmp4.Add (d2.Get (1)); /* n1 */
Ipv6InterfaceContainer iic2 = ipv6.AssignWithoutAddress (tmp4);
iic2.Add (iicr2);
/* radvd configuration */
Ipv6Address prefix ("2001:1::0"); /* create the prefix */
Ipv6Address prefix2 ("2001:2::0"); /* create the prefix */
uint32_t indexRouter = iic1.GetInterfaceIndex (1); /* R interface (n0 - R) */
uint32_t indexRouter2 = iic2.GetInterfaceIndex (1); /* R interface (R - n1) */
Ptr<Radvd> radvd = CreateObject<Radvd> ();
Ptr<RadvdInterface> routerInterface = Create<RadvdInterface> (indexRouter, 5000, 1000);
Ptr<RadvdPrefix> routerPrefix = Create<RadvdPrefix> (prefix, 64, 3, 5);
Ptr<RadvdInterface> routerInterface2 = Create<RadvdInterface> (indexRouter2, 5000, 1000);
Ptr<RadvdPrefix> routerPrefix2 = Create<RadvdPrefix> (prefix2, 64, 3, 5);
routerInterface->AddPrefix (routerPrefix);
routerInterface2->AddPrefix (routerPrefix2);
radvd->AddConfiguration (routerInterface);
radvd->AddConfiguration (routerInterface2);
r->AddApplication (radvd);
radvd->SetStartTime (Seconds (1.0));
radvd->SetStopTime (Seconds (10.0));
/* Create a Ping6 application to send ICMPv6 echo request from n0 to n1 via R */
uint32_t packetSize = 1024;
uint32_t maxPacketCount = 5;
Time interPacketInterval = Seconds (1.);
Ping6Helper ping6;
/* ping6.SetLocal (iic1.GetAddress (0, 1)); */
ping6.SetRemote (Ipv6Address ("2001:2::200:ff:fe00:4")); /* should be n1 address after autoconfiguration */
ping6.SetIfIndex (iic1.GetInterfaceIndex (0));
ping6.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
ping6.SetAttribute ("Interval", TimeValue (interPacketInterval));
ping6.SetAttribute ("PacketSize", UintegerValue (packetSize));
ApplicationContainer apps = ping6.Install (net1.Get (0));
apps.Start (Seconds (2.0));
apps.Stop (Seconds (7.0));
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("radvd.tr"));
csma.EnablePcapAll (std::string ("radvd"), true);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/ipv6/radvd.cc | C++ | gpl2 | 5,578 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008-2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: David Gross <gdavid.devel@gmail.com>
* Sebastien Vincent <vincent@clarinet.u-strasbg.fr>
*/
// Network topology
// //
// // n0 r n1
// // | _ |
// // ====|_|====
// // router
// //
// // - Tracing of queues and packet receptions to file "fragmentation-ipv6.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv6-static-routing-helper.h"
#include "ns3/ipv6-routing-table-entry.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("FragmentationIpv6Example");
/**
* \class StackHelper
* \brief Helper to set or get some IPv6 information about nodes.
*/
class StackHelper
{
public:
/**
* \brief Add an address to a IPv6 node.
* \param n node
* \param interface interface index
* \param address IPv6 address to add
*/
inline void AddAddress (Ptr<Node>& n, uint32_t interface, Ipv6Address address)
{
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
ipv6->AddAddress (interface, address);
}
/**
* \brief Print the routing table.
* \param n the node
*/
inline void PrintRoutingTable (Ptr<Node>& n)
{
Ptr<Ipv6StaticRouting> routing = 0;
Ipv6StaticRoutingHelper routingHelper;
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
uint32_t nbRoutes = 0;
Ipv6RoutingTableEntry route;
routing = routingHelper.GetStaticRouting (ipv6);
std::cout << "Routing table of " << n << " : " << std::endl;
std::cout << "Destination\t\t\t\t" << "Gateway\t\t\t\t\t" << "Interface\t" << "Prefix to use" << std::endl;
nbRoutes = routing->GetNRoutes ();
for (uint32_t i = 0; i < nbRoutes; i++)
{
route = routing->GetRoute (i);
std::cout << route.GetDest () << "\t"
<< route.GetGateway () << "\t"
<< route.GetInterface () << "\t"
<< route.GetPrefixToUse () << "\t"
<< std::endl;
}
}
};
int main (int argc, char** argv)
{
#if 0
LogComponentEnable ("Ipv6L3Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Icmpv6L4Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6StaticRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Interface", LOG_LEVEL_ALL);
LogComponentEnable ("Ping6Application", LOG_LEVEL_ALL);
#endif
CommandLine cmd;
cmd.Parse (argc, argv);
StackHelper stackHelper;
NS_LOG_INFO ("Create nodes.");
Ptr<Node> n0 = CreateObject<Node> ();
Ptr<Node> r = CreateObject<Node> ();
Ptr<Node> n1 = CreateObject<Node> ();
NodeContainer net1 (n0, r);
NodeContainer net2 (r, n1);
NodeContainer all (n0, r, n1);
NS_LOG_INFO ("Create IPv6 Internet Stack");
InternetStackHelper internetv6;
internetv6.Install (all);
NS_LOG_INFO ("Create channels.");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer d1 = csma.Install (net1);
NetDeviceContainer d2 = csma.Install (net2);
NS_LOG_INFO ("Create networks and assign IPv6 Addresses.");
Ipv6AddressHelper ipv6;
ipv6.NewNetwork (Ipv6Address ("2001:1::"), 64);
Ipv6InterfaceContainer i1 = ipv6.Assign (d1);
i1.SetRouter (1, true);
ipv6.NewNetwork (Ipv6Address ("2001:2::"), 64);
Ipv6InterfaceContainer i2 = ipv6.Assign (d2);
i2.SetRouter (0, true);
stackHelper.PrintRoutingTable (n0);
/* Create a Ping6 application to send ICMPv6 echo request from n0 to n1 via r */
uint32_t packetSize = 4096;
uint32_t maxPacketCount = 5;
Time interPacketInterval = Seconds (1.0);
Ping6Helper ping6;
ping6.SetLocal (i1.GetAddress (0, 1));
ping6.SetRemote (i2.GetAddress (1, 1));
ping6.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
ping6.SetAttribute ("Interval", TimeValue (interPacketInterval));
ping6.SetAttribute ("PacketSize", UintegerValue (packetSize));
ApplicationContainer apps = ping6.Install (net1.Get (0));
apps.Start (Seconds (2.0));
apps.Stop (Seconds (20.0));
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("fragmentation-ipv6.tr"));
csma.EnablePcapAll (std::string ("fragmentation-ipv6"), true);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/ipv6/fragmentation-ipv6.cc | C++ | gpl2 | 5,127 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: David Gross <gdavid.devel@gmail.com>
* Sebastien Vincent <vincent@clarinet.u-strasbg.fr>
*/
// Network topology
// //
// // n0 R n1
// // | _ |
// // ====|_|====
// // router
// // - R sends RA to n0's subnet (2001:1::/64 and 2001:ABCD::/64);
// // - R interface to n0 has two addresses with following prefixes 2001:1::/64 and 2001:ABCD::/64;
// // - R sends RA to n1's subnet (2001:2::/64);
// // - n0 ping6 n1.
// //
// // - Tracing of queues and packet receptions to file "radvd-two-prefix.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv6-routing-table-entry.h"
#include "ns3/radvd.h"
#include "ns3/radvd-interface.h"
#include "ns3/radvd-prefix.h"
#include "ns3/ipv6-static-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("RadvdTwoPrefixExample");
/**
* \class StackHelper
* \brief Helper to set or get some IPv6 information about nodes.
*/
class StackHelper
{
public:
/**
* \brief Add an address to a IPv6 node.
* \param n node
* \param interface interface index
* \param address IPv6 address to add
*/
inline void AddAddress (Ptr<Node>& n, uint32_t interface, Ipv6Address address)
{
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
ipv6->AddAddress (interface, address);
}
/**
* \brief Print the routing table.
* \param n the node
*/
inline void PrintRoutingTable (Ptr<Node>& n)
{
Ptr<Ipv6StaticRouting> routing = 0;
Ipv6StaticRoutingHelper routingHelper;
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
uint32_t nbRoutes = 0;
Ipv6RoutingTableEntry route;
routing = routingHelper.GetStaticRouting (ipv6);
std::cout << "Routing table of " << n << " : " << std::endl;
std::cout << "Destination\t\t\t\t" << "Gateway\t\t\t\t\t" << "Interface\t" << "Prefix to use" << std::endl;
nbRoutes = routing->GetNRoutes ();
for (uint32_t i = 0; i < nbRoutes; i++)
{
route = routing->GetRoute (i);
std::cout << route.GetDest () << "\t"
<< route.GetGateway () << "\t"
<< route.GetInterface () << "\t"
<< route.GetPrefixToUse () << "\t"
<< std::endl;
}
}
};
int main (int argc, char** argv)
{
#if 0
LogComponentEnable ("Ipv6L3Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6RawSocketImpl", LOG_LEVEL_ALL);
LogComponentEnable ("Icmpv6L4Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6StaticRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Interface", LOG_LEVEL_ALL);
LogComponentEnable ("RadvdApplication", LOG_LEVEL_ALL);
LogComponentEnable ("Ping6Application", LOG_LEVEL_ALL);
#endif
CommandLine cmd;
cmd.Parse (argc, argv);
NS_LOG_INFO ("Create nodes.");
Ptr<Node> n0 = CreateObject<Node> ();
Ptr<Node> r = CreateObject<Node> ();
Ptr<Node> n1 = CreateObject<Node> ();
NodeContainer net1 (n0, r);
NodeContainer net2 (r, n1);
NodeContainer all (n0, r, n1);
StackHelper stackHelper;
NS_LOG_INFO ("Create IPv6 Internet Stack");
InternetStackHelper internetv6;
internetv6.Install (all);
NS_LOG_INFO ("Create channels.");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer d1 = csma.Install (net1); /* n0 - R */
NetDeviceContainer d2 = csma.Install (net2); /* R - n1 */
NS_LOG_INFO ("Create networks and assign IPv6 Addresses.");
Ipv6AddressHelper ipv6;
/* first subnet */
ipv6.NewNetwork (Ipv6Address ("2001:1::"), 64);
NetDeviceContainer tmp;
tmp.Add (d1.Get (0)); /* n0 */
Ipv6InterfaceContainer iic1 = ipv6.AssignWithoutAddress (tmp); /* n0 interface */
NetDeviceContainer tmp2;
tmp2.Add (d1.Get (1)); /* R */
Ipv6InterfaceContainer iicr1 = ipv6.Assign (tmp2); /* R interface to the first subnet is just statically assigned */
iicr1.SetRouter (0, true);
iic1.Add (iicr1);
/* add another IPv6 address for second prefix advertised on first subnet */
stackHelper.AddAddress (r, iic1.GetInterfaceIndex (1), Ipv6Address ("2001:ABCD::2"));
/* second subnet R - n1 */
ipv6.NewNetwork (Ipv6Address ("2001:2::"), 64);
NetDeviceContainer tmp3;
tmp3.Add (d2.Get (0)); /* R */
Ipv6InterfaceContainer iicr2 = ipv6.Assign (tmp3); /* R interface */
iicr2.SetRouter (0, true);
NetDeviceContainer tmp4;
tmp4.Add (d2.Get (1)); /* n1 */
Ipv6InterfaceContainer iic2 = ipv6.AssignWithoutAddress (tmp4);
iic2.Add (iicr2);
/* radvd configuration */
Ipv6Address prefix ("2001:ABCD::0"); /* create the prefix */
Ipv6Address prefixBis ("2001:1::0"); /* create the prefix */
Ipv6Address prefix2 ("2001:2::0"); /* create the prefix */
uint32_t indexRouter = iic1.GetInterfaceIndex (1); /* R interface (n0 - R) */
uint32_t indexRouter2 = iic2.GetInterfaceIndex (1); /* R interface (R - n1) */
Ptr<Radvd> radvd = CreateObject<Radvd> ();
Ptr<RadvdInterface> routerInterface = Create<RadvdInterface> (indexRouter, 2000, 1000);
Ptr<RadvdPrefix> routerPrefix = Create<RadvdPrefix> (prefix, 64, 3, 5);
Ptr<RadvdPrefix> routerPrefixBis = Create<RadvdPrefix> (prefixBis, 64, 3, 5);
Ptr<RadvdInterface> routerInterface2 = Create<RadvdInterface> (indexRouter2, 2000, 1000);
Ptr<RadvdPrefix> routerPrefix2 = Create<RadvdPrefix> (prefix2, 64, 3, 5);
/* first interface advertise two prefixes (2001:1::/64 and 2001:ABCD::/64) */
/* prefix is added in the inverse order in packet */
routerInterface->AddPrefix (routerPrefix);
routerInterface->AddPrefix (routerPrefixBis);
routerInterface2->AddPrefix (routerPrefix2);
radvd->AddConfiguration (routerInterface);
radvd->AddConfiguration (routerInterface2);
r->AddApplication (radvd);
radvd->SetStartTime (Seconds (1.0));
radvd->SetStopTime (Seconds (2.0));
/* Create a Ping6 application to send ICMPv6 echo request from n0 to n1 via R */
uint32_t packetSize = 1024;
uint32_t maxPacketCount = 8;
Time interPacketInterval = Seconds (1.);
Ping6Helper ping6;
/* ping6.SetLocal (iic1.GetAddress (0, 1)); */
ping6.SetRemote (Ipv6Address ("2001:2::200:ff:fe00:4")); /* should be n1 address after autoconfiguration */
ping6.SetIfIndex (iic1.GetInterfaceIndex (0));
ping6.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
ping6.SetAttribute ("Interval", TimeValue (interPacketInterval));
ping6.SetAttribute ("PacketSize", UintegerValue (packetSize));
ApplicationContainer apps = ping6.Install (net1.Get (0));
apps.Start (Seconds (2.0));
apps.Stop (Seconds (9.0));
/* RA should be received, two prefixes + routes + default route should be present */
Simulator::Schedule (Seconds (2.0), &StackHelper::PrintRoutingTable, &stackHelper, n0);
/* at the end, RA addresses and routes should be cleared */
Simulator::Schedule (Seconds (10.0), &StackHelper::PrintRoutingTable, &stackHelper, n0);
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("radvd-two-prefix.tr"));
csma.EnablePcapAll (std::string ("radvd-two-prefix"), true);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/ipv6/radvd-two-prefix.cc | C++ | gpl2 | 8,053 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("icmpv6-redirect", "True", "True"),
("ping6", "True", "True"),
("radvd", "True", "True"),
("radvd-two-prefix", "True", "True"),
("test-ipv6", "True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
| zy901002-gpsr | examples/ipv6/examples-to-run.py | Python | gpl2 | 753 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
obj = bld.create_ns3_program('icmpv6-redirect', ['csma', 'internet'])
obj.source = 'icmpv6-redirect.cc'
obj = bld.create_ns3_program('ping6', ['csma', 'internet'])
obj.source = 'ping6.cc'
obj = bld.create_ns3_program('radvd', ['csma', 'internet'])
obj.source = 'radvd.cc'
obj = bld.create_ns3_program('radvd-two-prefix', ['csma', 'internet', 'applications'])
obj.source = 'radvd-two-prefix.cc'
obj = bld.create_ns3_program('test-ipv6', ['point-to-point', 'internet'])
obj.source = 'test-ipv6.cc'
obj = bld.create_ns3_program('fragmentation-ipv6', ['csma', 'internet'])
obj.source = 'fragmentation-ipv6.cc'
obj = bld.create_ns3_program('loose-routing-ipv6', ['csma', 'internet'])
obj.source = 'loose-routing-ipv6.cc'
| zy901002-gpsr | examples/ipv6/wscript | Python | gpl2 | 888 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: David Gross <gdavid.devel@gmail.com>
*/
// Network topology
// //
// //
// // +------------+
// // +------------+ |---| Router 1 |---|
// // | Host 0 |--| | [------------] |
// // [------------] | | |
// // | +------------+ |
// // +--| | +------------+
// // | Router 0 | | Router 2 |
// // +--| | [------------]
// // | [------------] |
// // +------------+ | | |
// // | Host 1 |--| | +------------+ |
// // [------------] |---| Router 3 |---|
// // [------------]
// //
// //
// // - Tracing of queues and packet receptions to file "loose-routing-ipv6.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv6-header.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("LooseRoutingIpv6Example");
int main (int argc, char **argv)
{
#if 0
LogComponentEnable ("Ipv6ExtensionLooseRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Extension", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6L3Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6StaticRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Interface", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Interface", LOG_LEVEL_ALL);
LogComponentEnable ("NdiscCache", LOG_LEVEL_ALL);
#endif
CommandLine cmd;
cmd.Parse (argc, argv);
NS_LOG_INFO ("Create nodes.");
Ptr<Node> h0 = CreateObject<Node> ();
Ptr<Node> h1 = CreateObject<Node> ();
Ptr<Node> r0 = CreateObject<Node> ();
Ptr<Node> r1 = CreateObject<Node> ();
Ptr<Node> r2 = CreateObject<Node> ();
Ptr<Node> r3 = CreateObject<Node> ();
NodeContainer net1 (h0, r0);
NodeContainer net2 (h1, r0);
NodeContainer net3 (r0, r1);
NodeContainer net4 (r1, r2);
NodeContainer net5 (r2, r3);
NodeContainer net6 (r3, r0);
NodeContainer all;
all.Add (h0);
all.Add (h1);
all.Add (r0);
all.Add (r1);
all.Add (r2);
all.Add (r3);
NS_LOG_INFO ("Create IPv6 Internet Stack");
InternetStackHelper internetv6;
internetv6.Install (all);
NS_LOG_INFO ("Create channels.");
CsmaHelper csma;
csma.SetDeviceAttribute ("Mtu", UintegerValue (1500));
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer d1 = csma.Install (net1);
NetDeviceContainer d2 = csma.Install (net2);
NetDeviceContainer d3 = csma.Install (net3);
NetDeviceContainer d4 = csma.Install (net4);
NetDeviceContainer d5 = csma.Install (net5);
NetDeviceContainer d6 = csma.Install (net6);
NS_LOG_INFO ("Create networks and assign IPv6 Addresses.");
Ipv6AddressHelper ipv6;
ipv6.NewNetwork (Ipv6Address ("2001:1::"), 64);
Ipv6InterfaceContainer i1 = ipv6.Assign (d1);
i1.SetRouter (1, true);
ipv6.NewNetwork (Ipv6Address ("2001:2::"), 64);
Ipv6InterfaceContainer i2 = ipv6.Assign (d2);
i2.SetRouter (1, true);
ipv6.NewNetwork (Ipv6Address ("2001:3::"), 64);
Ipv6InterfaceContainer i3 = ipv6.Assign (d3);
i3.SetRouter (0, true);
i3.SetRouter (1, true);
ipv6.NewNetwork (Ipv6Address ("2001:4::"), 64);
Ipv6InterfaceContainer i4 = ipv6.Assign (d4);
i4.SetRouter (0, true);
i4.SetRouter (1, true);
ipv6.NewNetwork (Ipv6Address ("2001:5::"), 64);
Ipv6InterfaceContainer i5 = ipv6.Assign (d5);
i5.SetRouter (0, true);
i5.SetRouter (1, true);
ipv6.NewNetwork (Ipv6Address ("2001:6::"), 64);
Ipv6InterfaceContainer i6 = ipv6.Assign (d6);
i6.SetRouter (0, true);
i6.SetRouter (1, true);
NS_LOG_INFO ("Create Applications.");
/**
* ICMPv6 Echo from h0 to h1 port 7
*/
uint32_t packetSize = 1024;
uint32_t maxPacketCount = 1;
Time interPacketInterval = Seconds (1.0);
std::vector<Ipv6Address> routersAddress;
routersAddress.push_back (i3.GetAddress (1, 1));
routersAddress.push_back (i4.GetAddress (1, 1));
routersAddress.push_back (i5.GetAddress (1, 1));
routersAddress.push_back (i6.GetAddress (1, 1));
routersAddress.push_back (i2.GetAddress (0, 1));
Ping6Helper client;
/* remote address is first routers in RH0 => source routing */
client.SetRemote (i1.GetAddress (1, 1));
client.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
client.SetAttribute ("Interval", TimeValue (interPacketInterval));
client.SetAttribute ("PacketSize", UintegerValue (packetSize));
client.SetRoutersAddress (routersAddress);
ApplicationContainer apps = client.Install (h0);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("loose-routing-ipv6.tr"));
csma.EnablePcapAll ("loose-routing-ipv6", true);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/ipv6/loose-routing-ipv6.cc | C++ | gpl2 | 5,831 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008 Louis Pasteur University / Telecom Bretagne
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Angelos Chatzipapas <Angelos.CHATZIPAPAS@enst-bretagne.fr> /
* <chatzipa@ceid.upatras.gr>
*/
#include "ns3/log.h"
#include "ns3/ipv6-address.h"
#include "ns3/node.h"
#include "ns3/mac48-address.h"
NS_LOG_COMPONENT_DEFINE ("TestIpv6");
using namespace ns3;
int
main (int argc, char *argv[])
{
LogComponentEnable ("TestIpv6", LOG_LEVEL_ALL);
NS_LOG_INFO ("Test Ipv6");
Mac48Address m_addresses[10];
m_addresses[0] = ("00:00:00:00:00:01");
m_addresses[1] = ("00:00:00:00:00:02");
m_addresses[2] = ("00:00:00:00:00:03");
m_addresses[3] = ("00:00:00:00:00:04");
m_addresses[4] = ("00:00:00:00:00:05");
m_addresses[5] = ("00:00:00:00:00:06");
m_addresses[6] = ("00:00:00:00:00:07");
m_addresses[7] = ("00:00:00:00:00:08");
m_addresses[8] = ("00:00:00:00:00:09");
m_addresses[9] = ("00:00:00:00:00:10");
Ipv6Address prefix1 ("2001:1::");
NS_LOG_INFO ("prefix = " << prefix1);
for (uint32_t i = 0; i < 10; ++i)
{
NS_LOG_INFO ("address = " << m_addresses[i]);
Ipv6Address ipv6address = Ipv6Address::MakeAutoconfiguredAddress (m_addresses[i], prefix1);
NS_LOG_INFO ("address = " << ipv6address);
}
Ipv6Address prefix2 ("2002:1:1::");
NS_LOG_INFO ("prefix = " << prefix2);
for (uint32_t i = 0; i < 10; ++i)
{
Ipv6Address ipv6address = Ipv6Address::MakeAutoconfiguredAddress (m_addresses[i], prefix2);
NS_LOG_INFO ("address = " << ipv6address);
}
}
| zy901002-gpsr | examples/ipv6/test-ipv6.cc | C++ | gpl2 | 2,238 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Joe Kopena <tjkopena@cs.drexel.edu>
*
* These applications are used in the WiFi Distance Test experiment,
* described and implemented in test02.cc. That file should be in the
* same place as this file. The applications have two very simple
* jobs, they just generate and receive packets. We could use the
* standard Application classes included in the NS-3 distribution.
* These have been written just to change the behavior a little, and
* provide more examples.
*
*/
#include <ostream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/stats-module.h"
#include "wifi-example-apps.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("WiFiDistanceApps");
TypeId
Sender::GetTypeId (void)
{
static TypeId tid = TypeId ("Sender")
.SetParent<Application> ()
.AddConstructor<Sender> ()
.AddAttribute ("PacketSize", "The size of packets transmitted.",
UintegerValue (64),
MakeUintegerAccessor (&Sender::m_pktSize),
MakeUintegerChecker<uint32_t>(1))
.AddAttribute ("Destination", "Target host address.",
Ipv4AddressValue ("255.255.255.255"),
MakeIpv4AddressAccessor (&Sender::m_destAddr),
MakeIpv4AddressChecker ())
.AddAttribute ("Port", "Destination app port.",
UintegerValue (1603),
MakeUintegerAccessor (&Sender::m_destPort),
MakeUintegerChecker<uint32_t>())
.AddAttribute ("NumPackets", "Total number of packets to send.",
UintegerValue (30),
MakeUintegerAccessor (&Sender::m_numPkts),
MakeUintegerChecker<uint32_t>(1))
.AddAttribute ("Interval", "Delay between transmissions.",
RandomVariableValue (ConstantVariable (0.5)),
MakeRandomVariableAccessor (&Sender::m_interval),
MakeRandomVariableChecker ())
.AddTraceSource ("Tx", "A new packet is created and is sent",
MakeTraceSourceAccessor (&Sender::m_txTrace))
;
return tid;
}
Sender::Sender()
{
NS_LOG_FUNCTION_NOARGS ();
m_socket = 0;
}
Sender::~Sender()
{
NS_LOG_FUNCTION_NOARGS ();
}
void
Sender::DoDispose (void)
{
NS_LOG_FUNCTION_NOARGS ();
m_socket = 0;
// chain up
Application::DoDispose ();
}
void Sender::StartApplication ()
{
NS_LOG_FUNCTION_NOARGS ();
if (m_socket == 0) {
Ptr<SocketFactory> socketFactory = GetNode ()->GetObject<SocketFactory>
(UdpSocketFactory::GetTypeId ());
m_socket = socketFactory->CreateSocket ();
m_socket->Bind ();
}
m_count = 0;
Simulator::Cancel (m_sendEvent);
m_sendEvent = Simulator::ScheduleNow (&Sender::SendPacket, this);
// end Sender::StartApplication
}
void Sender::StopApplication ()
{
NS_LOG_FUNCTION_NOARGS ();
Simulator::Cancel (m_sendEvent);
// end Sender::StopApplication
}
void Sender::SendPacket ()
{
// NS_LOG_FUNCTION_NOARGS ();
NS_LOG_INFO ("Sending packet at " << Simulator::Now () << " to " <<
m_destAddr);
Ptr<Packet> packet = Create<Packet>(m_pktSize);
TimestampTag timestamp;
timestamp.SetTimestamp (Simulator::Now ());
packet->AddByteTag (timestamp);
// Could connect the socket since the address never changes; using SendTo
// here simply because all of the standard apps do not.
m_socket->SendTo (packet, 0, InetSocketAddress (m_destAddr, m_destPort));
// Report the event to the trace.
m_txTrace (packet);
if (++m_count < m_numPkts) {
m_sendEvent = Simulator::Schedule (Seconds (m_interval.GetValue ()),
&Sender::SendPacket, this);
}
// end Sender::SendPacket
}
//----------------------------------------------------------------------
//-- Receiver
//------------------------------------------------------
TypeId
Receiver::GetTypeId (void)
{
static TypeId tid = TypeId ("Receiver")
.SetParent<Application> ()
.AddConstructor<Receiver> ()
.AddAttribute ("Port", "Listening port.",
UintegerValue (1603),
MakeUintegerAccessor (&Receiver::m_port),
MakeUintegerChecker<uint32_t>())
;
return tid;
}
Receiver::Receiver() :
m_calc (0),
m_delay (0)
{
NS_LOG_FUNCTION_NOARGS ();
m_socket = 0;
}
Receiver::~Receiver()
{
NS_LOG_FUNCTION_NOARGS ();
}
void
Receiver::DoDispose (void)
{
NS_LOG_FUNCTION_NOARGS ();
m_socket = 0;
// chain up
Application::DoDispose ();
}
void
Receiver::StartApplication ()
{
NS_LOG_FUNCTION_NOARGS ();
if (m_socket == 0) {
Ptr<SocketFactory> socketFactory = GetNode ()->GetObject<SocketFactory>
(UdpSocketFactory::GetTypeId ());
m_socket = socketFactory->CreateSocket ();
InetSocketAddress local =
InetSocketAddress (Ipv4Address::GetAny (), m_port);
m_socket->Bind (local);
}
m_socket->SetRecvCallback (MakeCallback (&Receiver::Receive, this));
// end Receiver::StartApplication
}
void
Receiver::StopApplication ()
{
NS_LOG_FUNCTION_NOARGS ();
if (m_socket != 0) {
m_socket->SetRecvCallback (MakeNullCallback<void, Ptr<Socket> > ());
}
// end Receiver::StopApplication
}
void
Receiver::SetCounter (Ptr<CounterCalculator<> > calc)
{
m_calc = calc;
// end Receiver::SetCounter
}
void
Receiver::SetDelayTracker (Ptr<TimeMinMaxAvgTotalCalculator> delay)
{
m_delay = delay;
// end Receiver::SetDelayTracker
}
void
Receiver::Receive (Ptr<Socket> socket)
{
// NS_LOG_FUNCTION (this << socket << packet << from);
Ptr<Packet> packet;
Address from;
while (packet = socket->RecvFrom (from)) {
if (InetSocketAddress::IsMatchingType (from)) {
NS_LOG_INFO ("Received " << packet->GetSize () << " bytes from " <<
InetSocketAddress::ConvertFrom (from).GetIpv4 ());
}
TimestampTag timestamp;
// Should never not be found since the sender is adding it, but
// you never know.
if (packet->FindFirstMatchingByteTag (timestamp)) {
Time tx = timestamp.GetTimestamp ();
if (m_delay != 0) {
m_delay->Update (Simulator::Now () - tx);
}
}
if (m_calc != 0) {
m_calc->Update ();
}
// end receiving packets
}
// end Receiver::Receive
}
//----------------------------------------------------------------------
//-- TimestampTag
//------------------------------------------------------
TypeId
TimestampTag::GetTypeId (void)
{
static TypeId tid = TypeId ("TimestampTag")
.SetParent<Tag> ()
.AddConstructor<TimestampTag> ()
.AddAttribute ("Timestamp",
"Some momentous point in time!",
EmptyAttributeValue (),
MakeTimeAccessor (&TimestampTag::GetTimestamp),
MakeTimeChecker ())
;
return tid;
}
TypeId
TimestampTag::GetInstanceTypeId (void) const
{
return GetTypeId ();
}
uint32_t
TimestampTag::GetSerializedSize (void) const
{
return 8;
}
void
TimestampTag::Serialize (TagBuffer i) const
{
int64_t t = m_timestamp.GetNanoSeconds ();
i.Write ((const uint8_t *)&t, 8);
}
void
TimestampTag::Deserialize (TagBuffer i)
{
int64_t t;
i.Read ((uint8_t *)&t, 8);
m_timestamp = NanoSeconds (t);
}
void
TimestampTag::SetTimestamp (Time time)
{
m_timestamp = time;
}
Time
TimestampTag::GetTimestamp (void) const
{
return m_timestamp;
}
void
TimestampTag::Print (std::ostream &os) const
{
os << "t=" << m_timestamp;
}
| zy901002-gpsr | examples/stats/wifi-example-apps.cc | C++ | gpl2 | 8,321 |
set terminal postscript portrait enhanced lw 2 "Helvetica" 14
set size 1.0, 0.66
#-------------------------------------------------------
set out "wifi-default.eps"
#set title "Packet Loss Over Distance"
set xlabel "Distance (m)"
set xrange [0:200]
set ylabel "% Packet Loss --- average of 5 trials per distance"
set yrange [0:110]
plot "wifi-default.data" with lines title "WiFi Defaults"
| zy901002-gpsr | examples/stats/wifi-example.gnuplot | Gnuplot | gpl2 | 393 |
#!/bin/sh
DISTANCES="25 50 75 100 125 145 147 150 152 155 157 160 162 165 167 170 172 175 177 180"
TRIALS="1 2 3 4 5"
echo WiFi Experiment Example
pCheck=`which sqlite3`
if [ -z "$pCheck" ]
then
echo "ERROR: This script requires sqlite3 (wifi-example-sim does not)."
exit 255
fi
pCheck=`which gnuplot`
if [ -z "$pCheck" ]
then
echo "ERROR: This script requires gnuplot (wifi-example-sim does not)."
exit 255
fi
pCheck=`which sed`
if [ -z "$pCheck" ]
then
echo "ERROR: This script requires sed (wifi-example-sim does not)."
exit 255
fi
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:bin/
if [ -e ../../data.db ]
then
echo "Kill data.db? (y/n)"
read ANS
if [ "$ANS" = "yes" -o "$ANS" = "y" ]
then
echo Deleting database
rm ../../data.db
fi
fi
for trial in $TRIALS
do
for distance in $DISTANCES
do
echo Trial $trial, distance $distance
../../waf --run "wifi-example-sim --format=db --distance=$distance --run=run-$distance-$trial"
done
done
#
#Another SQL command which just collects raw numbers of frames receved.
#
#CMD="select Experiments.input,avg(Singletons.value) \
# from Singletons,Experiments \
# where Singletons.run = Experiments.run AND \
# Singletons.name='wifi-rx-frames' \
# group by Experiments.input \
# order by abs(Experiments.input) ASC;"
mv ../../data.db .
CMD="select exp.input,avg(100-((rx.value*100)/tx.value)) \
from Singletons rx, Singletons tx, Experiments exp \
where rx.run = tx.run AND \
rx.run = exp.run AND \
rx.variable='receiver-rx-packets' AND \
tx.variable='sender-tx-packets' \
group by exp.input \
order by abs(exp.input) ASC;"
sqlite3 -noheader data.db "$CMD" > wifi-default.data
sed -i "s/|/ /" wifi-default.data
gnuplot wifi-example.gnuplot
echo "Done; data in wifi-default.data, plot in wifi-default.eps"
| zy901002-gpsr | examples/stats/wifi-example-db.sh | Shell | gpl2 | 1,863 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Joe Kopena <tjkopena@cs.drexel.edu>
*
* This program conducts a simple experiment: It places two nodes at a
* parameterized distance apart. One node generates packets and the
* other node receives. The stat framework collects data on packet
* loss. Outside of this program, a control script uses that data to
* produce graphs presenting performance at the varying distances.
* This isn't a typical simulation but is a common "experiment"
* performed in real life and serves as an accessible exemplar for the
* stat framework. It also gives some intuition on the behavior and
* basic reasonability of the NS-3 WiFi models.
*
* Applications used by this program are in test02-apps.h and
* test02-apps.cc, which should be in the same place as this file.
*
*/
// #define NS3_LOG_ENABLE // Now defined by Makefile
#include <ctime>
#include <sstream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/mobility-module.h"
#include "ns3/wifi-module.h"
#include "ns3/internet-module.h"
#include "ns3/stats-module.h"
#include "wifi-example-apps.h"
using namespace ns3;
using namespace std;
NS_LOG_COMPONENT_DEFINE ("WiFiDistanceExperiment");
void TxCallback (Ptr<CounterCalculator<uint32_t> > datac,
std::string path, Ptr<const Packet> packet) {
NS_LOG_INFO ("Sent frame counted in " <<
datac->GetKey ());
datac->Update ();
// end TxCallback
}
//----------------------------------------------------------------------
//-- main
//----------------------------------------------
int main (int argc, char *argv[]) {
double distance = 50.0;
string format ("omnet");
string experiment ("wifi-distance-test");
string strategy ("wifi-default");
string input;
string runID;
{
stringstream sstr;
sstr << "run-" << time (NULL);
runID = sstr.str ();
}
// Set up command line parameters used to control the experiment.
CommandLine cmd;
cmd.AddValue ("distance", "Distance apart to place nodes (in meters).",
distance);
cmd.AddValue ("format", "Format to use for data output.",
format);
cmd.AddValue ("experiment", "Identifier for experiment.",
experiment);
cmd.AddValue ("strategy", "Identifier for strategy.",
strategy);
cmd.AddValue ("run", "Identifier for run.",
runID);
cmd.Parse (argc, argv);
if (format != "omnet" && format != "db") {
NS_LOG_ERROR ("Unknown output format '" << format << "'");
return -1;
}
#ifndef STATS_HAS_SQLITE3
if (format == "db") {
NS_LOG_ERROR ("sqlite support not compiled in.");
return -1;
}
#endif
{
stringstream sstr ("");
sstr << distance;
input = sstr.str ();
}
//------------------------------------------------------------
//-- Create nodes and network stacks
//--------------------------------------------
NS_LOG_INFO ("Creating nodes.");
NodeContainer nodes;
nodes.Create (2);
NS_LOG_INFO ("Installing WiFi and Internet stack.");
WifiHelper wifi = WifiHelper::Default ();
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
NetDeviceContainer nodeDevices = wifi.Install (wifiPhy, wifiMac, nodes);
InternetStackHelper internet;
internet.Install (nodes);
Ipv4AddressHelper ipAddrs;
ipAddrs.SetBase ("192.168.0.0", "255.255.255.0");
ipAddrs.Assign (nodeDevices);
//------------------------------------------------------------
//-- Setup physical layout
//--------------------------------------------
NS_LOG_INFO ("Installing static mobility; distance " << distance << " .");
MobilityHelper mobility;
Ptr<ListPositionAllocator> positionAlloc =
CreateObject<ListPositionAllocator>();
positionAlloc->Add (Vector (0.0, 0.0, 0.0));
positionAlloc->Add (Vector (0.0, distance, 0.0));
mobility.SetPositionAllocator (positionAlloc);
mobility.Install (nodes);
//------------------------------------------------------------
//-- Create a custom traffic source and sink
//--------------------------------------------
NS_LOG_INFO ("Create traffic source & sink.");
Ptr<Node> appSource = NodeList::GetNode (0);
Ptr<Sender> sender = CreateObject<Sender>();
appSource->AddApplication (sender);
sender->SetStartTime (Seconds (1));
Ptr<Node> appSink = NodeList::GetNode (1);
Ptr<Receiver> receiver = CreateObject<Receiver>();
appSink->AddApplication (receiver);
receiver->SetStartTime (Seconds (0));
// Config::Set("/NodeList/*/ApplicationList/*/$Sender/Destination",
// Ipv4AddressValue("192.168.0.2"));
//------------------------------------------------------------
//-- Setup stats and data collection
//--------------------------------------------
// Create a DataCollector object to hold information about this run.
DataCollector data;
data.DescribeRun (experiment,
strategy,
input,
runID);
// Add any information we wish to record about this run.
data.AddMetadata ("author", "tjkopena");
// Create a counter to track how many frames are generated. Updates
// are triggered by the trace signal generated by the WiFi MAC model
// object. Here we connect the counter to the signal via the simple
// TxCallback() glue function defined above.
Ptr<CounterCalculator<uint32_t> > totalTx =
CreateObject<CounterCalculator<uint32_t> >();
totalTx->SetKey ("wifi-tx-frames");
totalTx->SetContext ("node[0]");
Config::Connect ("/NodeList/0/DeviceList/*/$ns3::WifiNetDevice/Mac/MacTx",
MakeBoundCallback (&TxCallback, totalTx));
data.AddDataCalculator (totalTx);
// This is similar, but creates a counter to track how many frames
// are received. Instead of our own glue function, this uses a
// method of an adapter class to connect a counter directly to the
// trace signal generated by the WiFi MAC.
Ptr<PacketCounterCalculator> totalRx =
CreateObject<PacketCounterCalculator>();
totalRx->SetKey ("wifi-rx-frames");
totalRx->SetContext ("node[1]");
Config::Connect ("/NodeList/1/DeviceList/*/$ns3::WifiNetDevice/Mac/MacRx",
MakeCallback (&PacketCounterCalculator::PacketUpdate,
totalRx));
data.AddDataCalculator (totalRx);
// This counter tracks how many packets---as opposed to frames---are
// generated. This is connected directly to a trace signal provided
// by our Sender class.
Ptr<PacketCounterCalculator> appTx =
CreateObject<PacketCounterCalculator>();
appTx->SetKey ("sender-tx-packets");
appTx->SetContext ("node[0]");
Config::Connect ("/NodeList/0/ApplicationList/*/$Sender/Tx",
MakeCallback (&PacketCounterCalculator::PacketUpdate,
appTx));
data.AddDataCalculator (appTx);
// Here a counter for received packets is directly manipulated by
// one of the custom objects in our simulation, the Receiver
// Application. The Receiver object is given a pointer to the
// counter and calls its Update() method whenever a packet arrives.
Ptr<CounterCalculator<> > appRx =
CreateObject<CounterCalculator<> >();
appRx->SetKey ("receiver-rx-packets");
appRx->SetContext ("node[1]");
receiver->SetCounter (appRx);
data.AddDataCalculator (appRx);
/**
* Just to show this is here...
Ptr<MinMaxAvgTotalCalculator<uint32_t> > test =
CreateObject<MinMaxAvgTotalCalculator<uint32_t> >();
test->SetKey("test-dc");
data.AddDataCalculator(test);
test->Update(4);
test->Update(8);
test->Update(24);
test->Update(12);
**/
// This DataCalculator connects directly to the transmit trace
// provided by our Sender Application. It records some basic
// statistics about the sizes of the packets received (min, max,
// avg, total # bytes), although in this scenaro they're fixed.
Ptr<PacketSizeMinMaxAvgTotalCalculator> appTxPkts =
CreateObject<PacketSizeMinMaxAvgTotalCalculator>();
appTxPkts->SetKey ("tx-pkt-size");
appTxPkts->SetContext ("node[0]");
Config::Connect ("/NodeList/0/ApplicationList/*/$Sender/Tx",
MakeCallback
(&PacketSizeMinMaxAvgTotalCalculator::PacketUpdate,
appTxPkts));
data.AddDataCalculator (appTxPkts);
// Here we directly manipulate another DataCollector tracking min,
// max, total, and average propagation delays. Check out the Sender
// and Receiver classes to see how packets are tagged with
// timestamps to do this.
Ptr<TimeMinMaxAvgTotalCalculator> delayStat =
CreateObject<TimeMinMaxAvgTotalCalculator>();
delayStat->SetKey ("delay");
delayStat->SetContext (".");
receiver->SetDelayTracker (delayStat);
data.AddDataCalculator (delayStat);
//------------------------------------------------------------
//-- Run the simulation
//--------------------------------------------
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
//------------------------------------------------------------
//-- Generate statistics output.
//--------------------------------------------
// Pick an output writer based in the requested format.
Ptr<DataOutputInterface> output = 0;
if (format == "omnet") {
NS_LOG_INFO ("Creating omnet formatted data output.");
output = CreateObject<OmnetDataOutput>();
} else if (format == "db") {
#ifdef STATS_HAS_SQLITE3
NS_LOG_INFO ("Creating sqlite formatted data output.");
output = CreateObject<SqliteDataOutput>();
#endif
} else {
NS_LOG_ERROR ("Unknown output format " << format);
}
// Finally, have that writer interrogate the DataCollector and save
// the results.
if (output != 0)
output->Output (data);
// Free any memory here at the end of this example.
Simulator::Destroy ();
// end main
}
| zy901002-gpsr | examples/stats/wifi-example-sim.cc | C++ | gpl2 | 10,837 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Joe Kopena <tjkopena@cs.drexel.edu>
*
* These applications are used in the WiFi Distance Test experiment,
* described and implemented in test02.cc. That file should be in the
* same place as this file. The applications have two very simple
* jobs, they just generate and receive packets. We could use the
* standard Application classes included in the NS-3 distribution.
* These have been written just to change the behavior a little, and
* provide more examples.
*
*/
// #define NS3_LOG_ENABLE // Now defined by Makefile
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/application.h"
#include "ns3/stats-module.h"
using namespace ns3;
//----------------------------------------------------------------------
//------------------------------------------------------
class Sender : public Application {
public:
static TypeId GetTypeId (void);
Sender();
virtual ~Sender();
protected:
virtual void DoDispose (void);
private:
virtual void StartApplication (void);
virtual void StopApplication (void);
void SendPacket ();
uint32_t m_pktSize;
Ipv4Address m_destAddr;
uint32_t m_destPort;
RandomVariable m_interval;
uint32_t m_numPkts;
Ptr<Socket> m_socket;
EventId m_sendEvent;
TracedCallback<Ptr<const Packet> > m_txTrace;
uint32_t m_count;
// end class Sender
};
//------------------------------------------------------
class Receiver : public Application {
public:
static TypeId GetTypeId (void);
Receiver();
virtual ~Receiver();
void SetCounter (Ptr<CounterCalculator<> > calc);
void SetDelayTracker (Ptr<TimeMinMaxAvgTotalCalculator> delay);
protected:
virtual void DoDispose (void);
private:
virtual void StartApplication (void);
virtual void StopApplication (void);
void Receive (Ptr<Socket> socket);
Ptr<Socket> m_socket;
uint32_t m_port;
Ptr<CounterCalculator<> > m_calc;
Ptr<TimeMinMaxAvgTotalCalculator> m_delay;
// end class Receiver
};
//------------------------------------------------------
class TimestampTag : public Tag {
public:
static TypeId GetTypeId (void);
virtual TypeId GetInstanceTypeId (void) const;
virtual uint32_t GetSerializedSize (void) const;
virtual void Serialize (TagBuffer i) const;
virtual void Deserialize (TagBuffer i);
// these are our accessors to our tag structure
void SetTimestamp (Time time);
Time GetTimestamp (void) const;
void Print (std::ostream &os) const;
private:
Time m_timestamp;
// end class TimestampTag
};
| zy901002-gpsr | examples/stats/wifi-example-apps.h | C++ | gpl2 | 3,304 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("wifi-example-sim", "True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
| zy901002-gpsr | examples/stats/examples-to-run.py | Python | gpl2 | 611 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
obj = bld.create_ns3_program('wifi-example-sim', ['stats', 'internet', 'mobility', 'wifi'])
obj.source = ['wifi-example-sim.cc',
'wifi-example-apps.cc']
| zy901002-gpsr | examples/stats/wscript | Python | gpl2 | 280 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
//
// Network topology
//
// n0
// \ 5 Mb/s, 2ms
// \ 1.5Mb/s, 10ms
// n2 ------------------------n3
// / /
// / 5 Mb/s, 2ms /
// n1--------------------------
// 1.5 Mb/s, 100ms
//
// this is a modification of simple-global-routing to allow for
// a single hop but higher-cost path between n1 and n3
//
// - Tracing of queues and packet receptions to file "simple-rerouting.tr"
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SimpleAlternateRoutingExample");
int
main (int argc, char *argv[])
{
// Users may find it convenient to turn on explicit debugging
// for selected modules; the below lines suggest how to do this
#if 0
LogComponentEnable ("GlobalRoutingHelper", LOG_LOGIC);
LogComponentEnable ("GlobalRouter", LOG_LOGIC);
#endif
Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (210));
Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("300b/s"));
// The below metric, if set to 3 or higher, will cause packets between
// n1 and n3 to take the 2-hop route through n2
CommandLine cmd;
//
// Additionally, we plumb this metric into the default value / command
// line argument system as well, for exemplary purposes. This means
// that it can be resettable at the command-line to the program,
// rather than recompiling
// e.g. waf --run "simple-alternate-routing --AlternateCost=5"
uint16_t sampleMetric = 1;
cmd.AddValue ("AlternateCost",
"This metric is used in the example script between n3 and n1 ",
sampleMetric);
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
cmd.Parse (argc, argv);
// Here, we will explicitly create four nodes. In more sophisticated
// topologies, we could configure a node factory.
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (4);
NodeContainer n0n2 = NodeContainer (c.Get (0), c.Get (2));
NodeContainer n1n2 = NodeContainer (c.Get (1), c.Get (2));
NodeContainer n3n2 = NodeContainer (c.Get (3), c.Get (2));
NodeContainer n1n3 = NodeContainer (c.Get (1), c.Get (3));
// We create the channels first without any IP addressing information
NS_LOG_INFO ("Create channels.");
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer d0d2 = p2p.Install (n0n2);
NetDeviceContainer d1d2 = p2p.Install (n1n2);
p2p.SetDeviceAttribute ("DataRate", StringValue ("1500kbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("10ms"));
NetDeviceContainer d3d2 = p2p.Install (n3n2);
p2p.SetChannelAttribute ("Delay", StringValue ("100ms"));
NetDeviceContainer d1d3 = p2p.Install (n1n3);
InternetStackHelper internet;
internet.Install (c);
// Later, we add IP addresses. The middle two octets correspond to
// the channel number.
NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.0.0.0", "255.255.255.0");
ipv4.Assign (d0d2);
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer i1i2 = ipv4.Assign (d1d2);
ipv4.SetBase ("10.2.2.0", "255.255.255.0");
ipv4.Assign (d3d2);
ipv4.SetBase ("10.3.3.0", "255.255.255.0");
Ipv4InterfaceContainer i1i3 = ipv4.Assign (d1d3);
i1i3.SetMetric (0, sampleMetric);
i1i3.SetMetric (1, sampleMetric);
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Create the OnOff application to send UDP datagrams
NS_LOG_INFO ("Create Application.");
uint16_t port = 9; // Discard port (RFC 863)
// Create a flow from n3 to n1, starting at time 1.1 seconds
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (i1i2.GetAddress (0), port)));
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
ApplicationContainer apps = onoff.Install (c.Get (3));
apps.Start (Seconds (1.1));
apps.Stop (Seconds (10.0));
// Create a packet sink to receive these packets
PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (c.Get (1));
apps.Start (Seconds (1.1));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("simple-alternate-routing.tr"));
p2p.EnablePcapAll ("simple-alternate-routing");
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
return 0;
}
| zy901002-gpsr | examples/routing/simple-alternate-routing.cc | C++ | gpl2 | 5,833 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008-2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: David Gross <gdavid.devel@gmail.com>
* Sebastien Vincent <vincent@clarinet.u-strasbg.fr>
*/
// Network topology
// //
// // n0 r n1
// // | _ |
// // ====|_|====
// // router
// //
// // - Tracing of queues and packet receptions to file "simple-routing-ping6.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv6-static-routing-helper.h"
#include "ns3/ipv6-routing-table-entry.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SimpleRoutingPing6Example");
/**
* \class StackHelper
* \brief Helper to set or get some IPv6 information about nodes.
*/
class StackHelper
{
public:
/**
* \brief Add an address to a IPv6 node.
* \param n node
* \param interface interface index
* \param address IPv6 address to add
*/
inline void AddAddress (Ptr<Node>& n, uint32_t interface, Ipv6Address address)
{
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
ipv6->AddAddress (interface, address);
}
/**
* \brief Print the routing table.
* \param n the node
*/
inline void PrintRoutingTable (Ptr<Node>& n)
{
Ptr<Ipv6StaticRouting> routing = 0;
Ipv6StaticRoutingHelper routingHelper;
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
uint32_t nbRoutes = 0;
Ipv6RoutingTableEntry route;
routing = routingHelper.GetStaticRouting (ipv6);
std::cout << "Routing table of " << n << " : " << std::endl;
std::cout << "Destination\t\t\t\t" << "Gateway\t\t\t\t\t" << "Interface\t" << "Prefix to use" << std::endl;
nbRoutes = routing->GetNRoutes ();
for (uint32_t i = 0; i < nbRoutes; i++)
{
route = routing->GetRoute (i);
std::cout << route.GetDest () << "\t"
<< route.GetGateway () << "\t"
<< route.GetInterface () << "\t"
<< route.GetPrefixToUse () << "\t"
<< std::endl;
}
}
};
int main (int argc, char** argv)
{
#if 0
LogComponentEnable ("Ipv6L3Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Icmpv6L4Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6StaticRouting", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv6Interface", LOG_LEVEL_ALL);
LogComponentEnable ("Ping6Application", LOG_LEVEL_ALL);
#endif
CommandLine cmd;
cmd.Parse (argc, argv);
StackHelper stackHelper;
NS_LOG_INFO ("Create nodes.");
Ptr<Node> n0 = CreateObject<Node> ();
Ptr<Node> r = CreateObject<Node> ();
Ptr<Node> n1 = CreateObject<Node> ();
NodeContainer net1 (n0, r);
NodeContainer net2 (r, n1);
NodeContainer all (n0, r, n1);
NS_LOG_INFO ("Create IPv6 Internet Stack");
InternetStackHelper internetv6;
internetv6.Install (all);
NS_LOG_INFO ("Create channels.");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer d1 = csma.Install (net1);
NetDeviceContainer d2 = csma.Install (net2);
NS_LOG_INFO ("Create networks and assign IPv6 Addresses.");
Ipv6AddressHelper ipv6;
ipv6.NewNetwork (Ipv6Address ("2001:1::"), 64);
Ipv6InterfaceContainer i1 = ipv6.Assign (d1);
i1.SetRouter (1, true);
ipv6.NewNetwork (Ipv6Address ("2001:2::"), 64);
Ipv6InterfaceContainer i2 = ipv6.Assign (d2);
i2.SetRouter (0, true);
stackHelper.PrintRoutingTable (n0);
/* Create a Ping6 application to send ICMPv6 echo request from n0 to n1 via r */
uint32_t packetSize = 1024;
uint32_t maxPacketCount = 5;
Time interPacketInterval = Seconds (1.);
Ping6Helper ping6;
ping6.SetLocal (i1.GetAddress (0, 1));
ping6.SetRemote (i2.GetAddress (1, 1));
ping6.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
ping6.SetAttribute ("Interval", TimeValue (interPacketInterval));
ping6.SetAttribute ("PacketSize", UintegerValue (packetSize));
ApplicationContainer apps = ping6.Install (net1.Get (0));
apps.Start (Seconds (2.0));
apps.Stop (Seconds (20.0));
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("simple-routing-ping6.tr"));
csma.EnablePcapAll ("simple-routing-ping6", true);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/routing/simple-routing-ping6.cc | C++ | gpl2 | 5,119 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
//
// Network topology
//
// n0
// \ 5 Mb/s, 2ms
// \ 1.5Mb/s, 10ms
// n2 -------------------------n3
// /
// / 5 Mb/s, 2ms
// n1
//
// - all links are point-to-point links with indicated one-way BW/delay
// - CBR/UDP flows from n0 to n3, and from n3 to n1
// - FTP/TCP flow from n0 to n3, starting at time 1.2 to time 1.35 sec.
// - UDP packet size of 210 bytes, with per-packet interval 0.00375 sec.
// (i.e., DataRate of 448,000 bps)
// - DropTail queues
// - Tracing of queues and packet receptions to file "simple-global-routing.tr"
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/flow-monitor-helper.h"
#include "ns3/ipv4-global-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SimpleGlobalRoutingExample");
int
main (int argc, char *argv[])
{
// Users may find it convenient to turn on explicit debugging
// for selected modules; the below lines suggest how to do this
#if 0
LogComponentEnable ("SimpleGlobalRoutingExample", LOG_LEVEL_INFO);
#endif
// Set up some default values for the simulation. Use the
Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (210));
Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("448kb/s"));
//DefaultValue::Bind ("DropTailQueue::m_maxPackets", 30);
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
CommandLine cmd;
bool enableFlowMonitor = false;
cmd.AddValue ("EnableMonitor", "Enable Flow Monitor", enableFlowMonitor);
cmd.Parse (argc, argv);
// Here, we will explicitly create four nodes. In more sophisticated
// topologies, we could configure a node factory.
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (4);
NodeContainer n0n2 = NodeContainer (c.Get (0), c.Get (2));
NodeContainer n1n2 = NodeContainer (c.Get (1), c.Get (2));
NodeContainer n3n2 = NodeContainer (c.Get (3), c.Get (2));
InternetStackHelper internet;
internet.Install (c);
// We create the channels first without any IP addressing information
NS_LOG_INFO ("Create channels.");
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer d0d2 = p2p.Install (n0n2);
NetDeviceContainer d1d2 = p2p.Install (n1n2);
p2p.SetDeviceAttribute ("DataRate", StringValue ("1500kbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("10ms"));
NetDeviceContainer d3d2 = p2p.Install (n3n2);
// Later, we add IP addresses.
NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer i0i2 = ipv4.Assign (d0d2);
ipv4.SetBase ("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer i1i2 = ipv4.Assign (d1d2);
ipv4.SetBase ("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer i3i2 = ipv4.Assign (d3d2);
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Create the OnOff application to send UDP datagrams of size
// 210 bytes at a rate of 448 Kb/s
NS_LOG_INFO ("Create Applications.");
uint16_t port = 9; // Discard port (RFC 863)
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (i3i2.GetAddress (0), port)));
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
ApplicationContainer apps = onoff.Install (c.Get (0));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
// Create a packet sink to receive these packets
PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (c.Get (3));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
// Create a similar flow from n3 to n1, starting at time 1.1 seconds
onoff.SetAttribute ("Remote",
AddressValue (InetSocketAddress (i1i2.GetAddress (0), port)));
apps = onoff.Install (c.Get (3));
apps.Start (Seconds (1.1));
apps.Stop (Seconds (10.0));
// Create a packet sink to receive these packets
apps = sink.Install (c.Get (1));
apps.Start (Seconds (1.1));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("simple-global-routing.tr"));
p2p.EnablePcapAll ("simple-global-routing");
// Flow Monitor
Ptr<FlowMonitor> flowmon;
if (enableFlowMonitor)
{
FlowMonitorHelper flowmonHelper;
flowmon = flowmonHelper.InstallAll ();
}
NS_LOG_INFO ("Run Simulation.");
Simulator::Stop (Seconds (11));
Simulator::Run ();
NS_LOG_INFO ("Done.");
if (enableFlowMonitor)
{
flowmon->SerializeToXmlFile ("simple-global-routing.flowmon", false, false);
}
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/routing/simple-global-routing.cc | C++ | gpl2 | 5,950 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 University of Kansas
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Justin Rohrer <rohrej@ittc.ku.edu>
*
* James P.G. Sterbenz <jpgs@ittc.ku.edu>, director
* ResiliNets Research Group http://wiki.ittc.ku.edu/resilinets
* Information and Telecommunication Technology Center (ITTC)
* and Department of Electrical Engineering and Computer Science
* The University of Kansas Lawrence, KS USA.
*
* Work supported in part by NSF FIND (Future Internet Design) Program
* under grant CNS-0626918 (Postmodern Internet Architecture),
* NSF grant CNS-1050226 (Multilayer Network Resilience Analysis and Experimentation on GENI),
* US Department of Defense (DoD), and ITTC at The University of Kansas.
*/
/*
* This example program allows one to run ns-3 DSDV, AODV, or OLSR under
* a typical random waypoint mobility model.
*
* By default, the simulation runs for 200 simulated seconds, of which
* the first 50 are used for start-up time. The number of nodes is 50.
* Nodes move according to RandomWaypointMobilityModel with a speed of
* 20 m/s and no pause time within a 300x1500 m region. The WiFi is
* in ad hoc mode with a 2 Mb/s rate (802.11b) and a Friis loss model.
* The transmit power is set to 7.5 dBm.
*
* It is possible to change the mobility and density of the network by
* directly modifying the speed and the number of nodes. It is also
* possible to change the characteristics of the network by changing
* the transmit power (as power increases, the impact of mobility
* decreases and the effective density increases).
*
* By default, OLSR is used, but specifying a value of 2 for the protocol
* will cause AODV to be used, and specifying a value of 3 will cause
* DSDV to be used.
*
* By default, there are 10 source/sink data pairs sending UDP data
* at an application rate of 2.048 Kb/s each. This is typically done
* at a rate of 4 64-byte packets per second. Application data is
* started at a random time between 50 and 51 seconds and continues
* to the end of the simulation.
*
* The program outputs a few items:
* - packet receptions are notified to stdout such as:
* <timestamp> <node-id> received one packet from <src-address>
* - each second, the data reception statistics are tabulated and output
* to a comma-separated value (csv) file
* - some tracing and flow monitor configuration that used to work is
* left commented inline in the program
*/
#include <fstream>
#include <iostream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/wifi-module.h"
#include "ns3/aodv-module.h"
#include "ns3/olsr-module.h"
#include "ns3/dsdv-module.h"
#include "ns3/applications-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("manet-routing-compare");
class RoutingExperiment
{
public:
RoutingExperiment ();
void Run (int nSinks, double txp, std::string CSVfileName);
//static void SetMACParam (ns3::NetDeviceContainer & devices,
// int slotDistance);
std::string CommandSetup (int argc, char **argv);
private:
Ptr<Socket> SetupPacketReceive (Ipv4Address addr, Ptr<Node> node);
void ReceivePacket (Ptr<Socket> socket);
void CheckThroughput ();
uint32_t port;
uint32_t bytesTotal;
uint32_t packetsReceived;
std::string m_CSVfileName;
int m_nSinks;
std::string m_protocolName;
double m_txp;
bool m_traceMobility;
uint32_t m_protocol;
};
RoutingExperiment::RoutingExperiment ()
: port (9),
bytesTotal (0),
packetsReceived (0),
m_CSVfileName ("manet-routing.output.csv"),
m_traceMobility (false),
m_protocol (2) // AODV
{
}
void
RoutingExperiment::ReceivePacket (Ptr<Socket> socket)
{
Ptr<Packet> packet;
while (packet = socket->Recv ())
{
bytesTotal += packet->GetSize ();
packetsReceived += 1;
SocketAddressTag tag;
bool found;
found = packet->PeekPacketTag (tag);
if (found)
{
InetSocketAddress addr = InetSocketAddress::ConvertFrom (tag.GetAddress ());
NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << " " << socket->GetNode ()->GetId ()
<< " received one packet from " << addr.GetIpv4 ());
//cast addr to void, to suppress 'addr' set but not used
//compiler warning in optimized builds
(void) addr;
}
else
{
NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << " " << socket->GetNode ()->GetId ()
<< " received one packet!");
}
}
}
void
RoutingExperiment::CheckThroughput ()
{
double kbs = (bytesTotal * 8.0) / 1000;
bytesTotal = 0;
std::ofstream out (m_CSVfileName.c_str (), std::ios::app);
out << (Simulator::Now ()).GetSeconds () << ","
<< kbs << ","
<< packetsReceived << ","
<< m_nSinks << ","
<< m_protocolName << ","
<< m_txp << ""
<< std::endl;
out.close ();
packetsReceived = 0;
Simulator::Schedule (Seconds (1.0), &RoutingExperiment::CheckThroughput, this);
}
Ptr<Socket>
RoutingExperiment::SetupPacketReceive (Ipv4Address addr, Ptr<Node> node)
{
TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
Ptr<Socket> sink = Socket::CreateSocket (node, tid);
InetSocketAddress local = InetSocketAddress (addr, port);
sink->Bind (local);
sink->SetRecvCallback (MakeCallback (&RoutingExperiment::ReceivePacket, this));
return sink;
}
std::string
RoutingExperiment::CommandSetup (int argc, char **argv)
{
CommandLine cmd;
cmd.AddValue ("CSVfileName", "The name of the CSV output file name", m_CSVfileName);
cmd.AddValue ("traceMobility", "Enable mobility tracing", m_traceMobility);
cmd.AddValue ("protocol", "1=OLSR;2=AODV;3=DSDV", m_protocol);
cmd.Parse (argc, argv);
return m_CSVfileName;
}
int
main (int argc, char *argv[])
{
RoutingExperiment experiment;
std::string CSVfileName = experiment.CommandSetup (argc,argv);
//blank out the last output file and write the column headers
std::ofstream out (CSVfileName.c_str ());
out << "SimulationSecond," <<
"ReceiveRate," <<
"PacketsReceived," <<
"NumberOfSinks," <<
"RoutingProtocol," <<
"TransmissionPower" <<
std::endl;
out.close ();
int nSinks = 10;
double txp = 7.5;
experiment.Run (nSinks, txp, CSVfileName);
}
void
RoutingExperiment::Run (int nSinks, double txp, std::string CSVfileName)
{
Packet::EnablePrinting ();
m_nSinks = nSinks;
m_txp = txp;
m_CSVfileName = CSVfileName;
int nWifis = 50;
double TotalTime = 200.0;
std::string rate ("2048bps");
std::string phyMode ("DsssRate11Mbps");
std::string tr_name ("manet-routing-compare");
int nodeSpeed = 20; //in m/s
int nodePause = 0; //in s
m_protocolName = "protocol";
Config::SetDefault ("ns3::OnOffApplication::PacketSize",StringValue ("64"));
Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue (rate));
//Set Non-unicastMode rate to unicast mode
Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",StringValue (phyMode));
NodeContainer adhocNodes;
adhocNodes.Create (nWifis);
// setting up wifi phy and channel using helpers
WifiHelper wifi;
wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel;
wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
wifiPhy.SetChannel (wifiChannel.Create ());
// Add a non-QoS upper mac, and disable rate control
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
"DataMode",StringValue (phyMode),
"ControlMode",StringValue (phyMode));
wifiPhy.Set ("TxPowerStart",DoubleValue (txp));
wifiPhy.Set ("TxPowerEnd", DoubleValue (txp));
wifiMac.SetType ("ns3::AdhocWifiMac");
NetDeviceContainer adhocDevices = wifi.Install (wifiPhy, wifiMac, adhocNodes);
AodvHelper aodv;
OlsrHelper olsr;
DsdvHelper dsdv;
Ipv4ListRoutingHelper list;
switch (m_protocol)
{
case 1:
list.Add (olsr, 100);
m_protocolName = "OLSR";
break;
case 2:
list.Add (aodv, 100);
m_protocolName = "AODV";
break;
case 3:
list.Add (dsdv, 100);
m_protocolName = "DSDV";
break;
default:
NS_FATAL_ERROR ("No such protocol:" << m_protocol);
}
InternetStackHelper internet;
internet.SetRoutingHelper (list);
internet.Install (adhocNodes);
NS_LOG_INFO ("assigning ip address");
Ipv4AddressHelper addressAdhoc;
addressAdhoc.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer adhocInterfaces;
adhocInterfaces = addressAdhoc.Assign (adhocDevices);
MobilityHelper mobilityAdhoc;
ObjectFactory pos;
pos.SetTypeId ("ns3::RandomRectanglePositionAllocator");
pos.Set ("X", RandomVariableValue (UniformVariable (0.0, 300.0)));
pos.Set ("Y", RandomVariableValue (UniformVariable (0.0, 1500.0)));
Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();
mobilityAdhoc.SetMobilityModel ("ns3::RandomWaypointMobilityModel",
"Speed", RandomVariableValue (UniformVariable (0.0, nodeSpeed)),
"Pause", RandomVariableValue (ConstantVariable (nodePause)),
"PositionAllocator", PointerValue (taPositionAlloc));
mobilityAdhoc.SetPositionAllocator (taPositionAlloc);
mobilityAdhoc.Install (adhocNodes);
OnOffHelper onoff1 ("ns3::UdpSocketFactory",Address ());
onoff1.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff1.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
for (int i = 0; i <= nSinks - 1; i++)
{
Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i), adhocNodes.Get (i));
AddressValue remoteAddress (InetSocketAddress (adhocInterfaces.GetAddress (i), port));
onoff1.SetAttribute ("Remote", remoteAddress);
UniformVariable var;
ApplicationContainer temp = onoff1.Install (adhocNodes.Get (i + nSinks));
temp.Start (Seconds (var.GetValue (50.0,51.0)));
temp.Stop (Seconds (TotalTime));
}
std::stringstream ss;
ss << nWifis;
std::string nodes = ss.str ();
std::stringstream ss2;
ss2 << nodeSpeed;
std::string sNodeSpeed = ss2.str ();
std::stringstream ss3;
ss3 << nodePause;
std::string sNodePause = ss3.str ();
std::stringstream ss4;
ss4 << rate;
std::string sRate = ss4.str ();
//NS_LOG_INFO ("Configure Tracing.");
//tr_name = tr_name + "_" + m_protocolName +"_" + nodes + "nodes_" + sNodeSpeed + "speed_" + sNodePause + "pause_" + sRate + "rate";
//AsciiTraceHelper ascii;
//Ptr<OutputStreamWrapper> osw = ascii.CreateFileStream ( (tr_name + ".tr").c_str());
//wifiPhy.EnableAsciiAll (osw);
std::ofstream os;
os.open ((tr_name + ".mob").c_str());
MobilityHelper::EnableAsciiAll (os);
//Ptr<FlowMonitor> flowmon;
//FlowMonitorHelper flowmonHelper;
//flowmon = flowmonHelper.InstallAll ();
NS_LOG_INFO ("Run Simulation.");
CheckThroughput ();
Simulator::Stop (Seconds (TotalTime));
Simulator::Run ();
//flowmon->SerializeToXmlFile ((tr_name + ".flowmon").c_str(), false, false);
Simulator::Destroy ();
}
| zy901002-gpsr | examples/routing/manet-routing-compare.cc | C++ | gpl2 | 12,247 |
#
# Copyright (c) 2008-2009 Strasbourg University
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Author: David Gross <gdavid.devel@gmail.com>
# Sebastien Vincent <vincent@clarinet.u-strasbg.fr>
#
#
# Network topology:
#
# n0 r n1
# | _ |
# ====|_|====
# router
#
import ns.applications
import ns.core
import ns.csma
import ns.internet
import ns.network
def main(argv):
cmd = ns.core.CommandLine();
cmd.Parse(argv);
# Create nodes
print "Create nodes"
n0 = ns.network.Node();
r = ns.network.Node();
n1 = ns.network.Node();
net1 = ns.network.NodeContainer();
net1.Add(n0);
net1.Add(r);
net2 = ns.network.NodeContainer();
net2.Add(r);
net2.Add(n1);
all = ns.network.NodeContainer();
all.Add(n0);
all.Add(r);
all.Add(n1);
# Create IPv6 Internet Stack
internetv6 = ns.internet.InternetStackHelper();
internetv6.Install(all);
# Create channels
csma = ns.csma.CsmaHelper();
csma.SetChannelAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)));
csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.MilliSeconds(2)));
d1 = csma.Install(net1);
d2 = csma.Install(net2);
# Create networks and assign IPv6 Addresses
print "Addressing"
ipv6 = ns.internet.Ipv6AddressHelper();
ipv6.NewNetwork(ns.network.Ipv6Address("2001:1::"), ns.network.Ipv6Prefix(64));
i1 = ipv6.Assign(d1);
i1.SetRouter(1, True);
ipv6.NewNetwork(ns.network.Ipv6Address("2001:2::"), ns.network.Ipv6Prefix(64));
i2 = ipv6.Assign(d2);
i2.SetRouter(0, True);
# Create a Ping6 application to send ICMPv6 echo request from n0 to n1 via r
print "Application"
packetSize = 1024;
maxPacketCount = 5;
interPacketInterval = ns.core.Seconds(1.);
ping6 = ns.applications.Ping6Helper();
ping6.SetLocal(i1.GetAddress(0, 1));
ping6.SetRemote(i2.GetAddress(1, 1));
ping6.SetAttribute("MaxPackets", ns.core.UintegerValue(maxPacketCount));
ping6.SetAttribute("Interval", ns.core.TimeValue(interPacketInterval));
ping6.SetAttribute("PacketSize", ns.core.UintegerValue(packetSize));
apps = ping6.Install(ns.network.NodeContainer(net1.Get(0)));
apps.Start(ns.core.Seconds(2.0));
apps.Stop(ns.core.Seconds(20.0));
print "Tracing"
ascii = ns.network.AsciiTraceHelper()
csma.EnableAsciiAll(ascii.CreateFileStream("simple-routing-ping6.tr"))
csma.EnablePcapAll("simple-routing-ping6", True)
# Run Simulation
ns.core.Simulator.Run()
ns.core.Simulator.Destroy()
if __name__ == '__main__':
import sys
main(sys.argv)
| zy901002-gpsr | examples/routing/simple-routing-ping6.py | Python | gpl2 | 3,298 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// This script exercises global routing code in a mixed point-to-point
// and csma/cd environment
//
// Network topology
//
// n0
// \ p-p
// \ (shared csma/cd)
// n2 -------------------------n3
// / | |
// / p-p n4 n5 ---------- n6
// n1 p-p
//
// - CBR/UDP flows from n0 to n6
// - Tracing of queues and packet receptions to file "mixed-global-routing.tr"
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("MixedGlobalRoutingExample");
int
main (int argc, char *argv[])
{
Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (210));
Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("448kb/s"));
// Allow the user to override any of the defaults and the above
// Bind ()s at run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (7);
NodeContainer n0n2 = NodeContainer (c.Get (0), c.Get (2));
NodeContainer n1n2 = NodeContainer (c.Get (1), c.Get (2));
NodeContainer n5n6 = NodeContainer (c.Get (5), c.Get (6));
NodeContainer n2345 = NodeContainer (c.Get (2), c.Get (3), c.Get (4), c.Get (5));
InternetStackHelper internet;
internet.Install (c);
// We create the channels first without any IP addressing information
NS_LOG_INFO ("Create channels.");
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer d0d2 = p2p.Install (n0n2);
NetDeviceContainer d1d2 = p2p.Install (n1n2);
p2p.SetDeviceAttribute ("DataRate", StringValue ("1500kbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("10ms"));
NetDeviceContainer d5d6 = p2p.Install (n5n6);
// We create the channels first without any IP addressing information
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("5Mbps"));
csma.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer d2345 = csma.Install (n2345);
// Later, we add IP addresses.
NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
ipv4.Assign (d0d2);
ipv4.SetBase ("10.1.2.0", "255.255.255.0");
ipv4.Assign (d1d2);
ipv4.SetBase ("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer i5i6 = ipv4.Assign (d5d6);
ipv4.SetBase ("10.250.1.0", "255.255.255.0");
ipv4.Assign (d2345);
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Create the OnOff application to send UDP datagrams of size
// 210 bytes at a rate of 448 Kb/s
NS_LOG_INFO ("Create Applications.");
uint16_t port = 9; // Discard port (RFC 863)
OnOffHelper onoff ("ns3::UdpSocketFactory",
InetSocketAddress (i5i6.GetAddress (1), port));
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
onoff.SetAttribute ("DataRate", StringValue ("300bps"));
onoff.SetAttribute ("PacketSize", UintegerValue (50));
ApplicationContainer apps = onoff.Install (c.Get (0));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
Ptr<OutputStreamWrapper> stream = ascii.CreateFileStream ("mixed-global-routing.tr");
p2p.EnableAsciiAll (stream);
csma.EnableAsciiAll (stream);
p2p.EnablePcapAll ("mixed-global-routing");
csma.EnablePcapAll ("mixed-global-routing", false);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/routing/mixed-global-routing.cc | C++ | gpl2 | 4,735 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contributed by: Luis Cortes (cortes@gatech.edu)
*/
// This script exercises global routing code in a mixed point-to-point
// and csma/cd environment. We bring up and down interfaces and observe
// the effect on global routing. We explicitly enable the attribute
// to respond to interface events, so that routes are recomputed
// automatically.
//
// Network topology
//
// n0
// \ p-p
// \ (shared csma/cd)
// n2 -------------------------n3
// / | |
// / p-p n4 n5 ---------- n6
// n1 p-p
// | |
// ----------------------------------------
// p-p
//
// - at time 1 CBR/UDP flow from n1 to n6's IP address on the n5/n6 link
// - at time 10, start similar flow from n1 to n6's address on the n1/n6 link
//
// Order of events
// At pre-simulation time, configure global routes. Shortest path from
// n1 to n6 is via the direct point-to-point link
// At time 1s, start CBR traffic flow from n1 to n6
// At time 2s, set the n1 point-to-point interface to down. Packets
// will be diverted to the n1-n2-n5-n6 path
// At time 4s, re-enable the n1/n6 interface to up. n1-n6 route restored.
// At time 6s, set the n6-n1 point-to-point Ipv4 interface to down (note, this
// keeps the point-to-point link "up" from n1's perspective). Traffic will
// flow through the path n1-n2-n5-n6
// At time 8s, bring the interface back up. Path n1-n6 is restored
// At time 10s, stop the first flow.
// At time 11s, start a new flow, but to n6's other IP address (the one
// on the n1/n6 p2p link)
// At time 12s, bring the n1 interface down between n1 and n6. Packets
// will be diverted to the alternate path
// At time 14s, re-enable the n1/n6 interface to up. This will change
// routing back to n1-n6 since the interface up notification will cause
// a new local interface route, at higher priority than global routing
// At time 16s, stop the second flow.
// - Tracing of queues and packet receptions to file "dynamic-global-routing.tr"
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("DynamicGlobalRoutingExample");
int
main (int argc, char *argv[])
{
// The below value configures the default behavior of global routing.
// By default, it is disabled. To respond to interface events, set to true
Config::SetDefault ("ns3::Ipv4GlobalRouting::RespondToInterfaceEvents", BooleanValue (true));
// Allow the user to override any of the defaults and the above
// Bind ()s at run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (7);
NodeContainer n0n2 = NodeContainer (c.Get (0), c.Get (2));
NodeContainer n1n2 = NodeContainer (c.Get (1), c.Get (2));
NodeContainer n5n6 = NodeContainer (c.Get (5), c.Get (6));
NodeContainer n1n6 = NodeContainer (c.Get (1), c.Get (6));
NodeContainer n2345 = NodeContainer (c.Get (2), c.Get (3), c.Get (4), c.Get (5));
InternetStackHelper internet;
internet.Install (c);
// We create the channels first without any IP addressing information
NS_LOG_INFO ("Create channels.");
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer d0d2 = p2p.Install (n0n2);
NetDeviceContainer d1d6 = p2p.Install (n1n6);
NetDeviceContainer d1d2 = p2p.Install (n1n2);
p2p.SetDeviceAttribute ("DataRate", StringValue ("1500kbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("10ms"));
NetDeviceContainer d5d6 = p2p.Install (n5n6);
// We create the channels first without any IP addressing information
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("5Mbps"));
csma.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer d2345 = csma.Install (n2345);
// Later, we add IP addresses.
NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
ipv4.Assign (d0d2);
ipv4.SetBase ("10.1.2.0", "255.255.255.0");
ipv4.Assign (d1d2);
ipv4.SetBase ("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer i5i6 = ipv4.Assign (d5d6);
ipv4.SetBase ("10.250.1.0", "255.255.255.0");
ipv4.Assign (d2345);
ipv4.SetBase ("172.16.1.0", "255.255.255.0");
Ipv4InterfaceContainer i1i6 = ipv4.Assign (d1d6);
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Create the OnOff application to send UDP datagrams of size
// 210 bytes at a rate of 448 Kb/s
NS_LOG_INFO ("Create Applications.");
uint16_t port = 9; // Discard port (RFC 863)
OnOffHelper onoff ("ns3::UdpSocketFactory",
InetSocketAddress (i5i6.GetAddress (1), port));
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
onoff.SetAttribute ("DataRate", StringValue ("2kbps"));
onoff.SetAttribute ("PacketSize", UintegerValue (50));
ApplicationContainer apps = onoff.Install (c.Get (1));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
// Create a second OnOff application to send UDP datagrams of size
// 210 bytes at a rate of 448 Kb/s
OnOffHelper onoff2 ("ns3::UdpSocketFactory",
InetSocketAddress (i1i6.GetAddress (1), port));
onoff2.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff2.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
onoff2.SetAttribute ("DataRate", StringValue ("2kbps"));
onoff2.SetAttribute ("PacketSize", UintegerValue (50));
ApplicationContainer apps2 = onoff2.Install (c.Get (1));
apps2.Start (Seconds (11.0));
apps2.Stop (Seconds (16.0));
// Create an optional packet sink to receive these packets
PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (c.Get (6));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
PacketSinkHelper sink2 ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps2 = sink2.Install (c.Get (6));
apps2.Start (Seconds (11.0));
apps2.Stop (Seconds (16.0));
AsciiTraceHelper ascii;
Ptr<OutputStreamWrapper> stream = ascii.CreateFileStream ("dynamic-global-routing.tr");
p2p.EnableAsciiAll (stream);
csma.EnableAsciiAll (stream);
internet.EnableAsciiIpv4All (stream);
p2p.EnablePcapAll ("dynamic-global-routing");
csma.EnablePcapAll ("dynamic-global-routing", false);
Ptr<Node> n1 = c.Get (1);
Ptr<Ipv4> ipv41 = n1->GetObject<Ipv4> ();
// The first ifIndex is 0 for loopback, then the first p2p is numbered 1,
// then the next p2p is numbered 2
uint32_t ipv4ifIndex1 = 2;
Simulator::Schedule (Seconds (2),&Ipv4::SetDown,ipv41, ipv4ifIndex1);
Simulator::Schedule (Seconds (4),&Ipv4::SetUp,ipv41, ipv4ifIndex1);
Ptr<Node> n6 = c.Get (6);
Ptr<Ipv4> ipv46 = n6->GetObject<Ipv4> ();
// The first ifIndex is 0 for loopback, then the first p2p is numbered 1,
// then the next p2p is numbered 2
uint32_t ipv4ifIndex6 = 2;
Simulator::Schedule (Seconds (6),&Ipv4::SetDown,ipv46, ipv4ifIndex6);
Simulator::Schedule (Seconds (8),&Ipv4::SetUp,ipv46, ipv4ifIndex6);
Simulator::Schedule (Seconds (12),&Ipv4::SetDown,ipv41, ipv4ifIndex1);
Simulator::Schedule (Seconds (14),&Ipv4::SetUp,ipv41, ipv4ifIndex1);
// Trace routing tables
Ipv4GlobalRoutingHelper g;
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("dynamic-global-routing.routes", std::ios::out);
g.PrintRoutingTableAllAt (Seconds (12), routingStream);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/routing/dynamic-global-routing.cc | C++ | gpl2 | 9,035 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// Test program for this 3-router scenario, using static routing
//
// (a.a.a.a/32)A<--x.x.x.0/30-->B<--y.y.y.0/30-->C(c.c.c.c/32)
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-static-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("StaticRoutingSlash32Test");
int
main (int argc, char *argv[])
{
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);
Ptr<Node> nA = CreateObject<Node> ();
Ptr<Node> nB = CreateObject<Node> ();
Ptr<Node> nC = CreateObject<Node> ();
NodeContainer c = NodeContainer (nA, nB, nC);
InternetStackHelper internet;
internet.Install (c);
// Point-to-point links
NodeContainer nAnB = NodeContainer (nA, nB);
NodeContainer nBnC = NodeContainer (nB, nC);
// We create the channels first without any IP addressing information
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer dAdB = p2p.Install (nAnB);
NetDeviceContainer dBdC = p2p.Install (nBnC);;
Ptr<CsmaNetDevice> deviceA = CreateObject<CsmaNetDevice> ();
deviceA->SetAddress (Mac48Address::Allocate ());
nA->AddDevice (deviceA);
Ptr<CsmaNetDevice> deviceC = CreateObject<CsmaNetDevice> ();
deviceC->SetAddress (Mac48Address::Allocate ());
nC->AddDevice (deviceC);
// Later, we add IP addresses.
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.252");
Ipv4InterfaceContainer iAiB = ipv4.Assign (dAdB);
ipv4.SetBase ("10.1.1.4", "255.255.255.252");
Ipv4InterfaceContainer iBiC = ipv4.Assign (dBdC);
Ptr<Ipv4> ipv4A = nA->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4B = nB->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4C = nC->GetObject<Ipv4> ();
int32_t ifIndexA = ipv4A->AddInterface (deviceA);
int32_t ifIndexC = ipv4C->AddInterface (deviceC);
Ipv4InterfaceAddress ifInAddrA = Ipv4InterfaceAddress (Ipv4Address ("172.16.1.1"), Ipv4Mask ("/32"));
ipv4A->AddAddress (ifIndexA, ifInAddrA);
ipv4A->SetMetric (ifIndexA, 1);
ipv4A->SetUp (ifIndexA);
Ipv4InterfaceAddress ifInAddrC = Ipv4InterfaceAddress (Ipv4Address ("192.168.1.1"), Ipv4Mask ("/32"));
ipv4C->AddAddress (ifIndexC, ifInAddrC);
ipv4C->SetMetric (ifIndexC, 1);
ipv4C->SetUp (ifIndexC);
Ipv4StaticRoutingHelper ipv4RoutingHelper;
// Create static routes from A to C
Ptr<Ipv4StaticRouting> staticRoutingA = ipv4RoutingHelper.GetStaticRouting (ipv4A);
// The ifIndex for this outbound route is 1; the first p2p link added
staticRoutingA->AddHostRouteTo (Ipv4Address ("192.168.1.1"), Ipv4Address ("10.1.1.2"), 1);
Ptr<Ipv4StaticRouting> staticRoutingB = ipv4RoutingHelper.GetStaticRouting (ipv4B);
// The ifIndex we want on node B is 2; 0 corresponds to loopback, and 1 to the first point to point link
staticRoutingB->AddHostRouteTo (Ipv4Address ("192.168.1.1"), Ipv4Address ("10.1.1.6"), 2);
// Create the OnOff application to send UDP datagrams of size
// 210 bytes at a rate of 448 Kb/s
uint16_t port = 9; // Discard port (RFC 863)
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (ifInAddrC.GetLocal (), port)));
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
onoff.SetAttribute ("DataRate", DataRateValue (DataRate (6000)));
ApplicationContainer apps = onoff.Install (nA);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
// Create a packet sink to receive these packets
PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (nC);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("static-routing-slash32.tr"));
p2p.EnablePcapAll ("static-routing-slash32");
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/routing/static-routing-slash32.cc | C++ | gpl2 | 5,062 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("dynamic-global-routing", "True", "True"),
("global-injection-slash32", "True", "True"),
("global-routing-slash32", "True", "True"),
("mixed-global-routing", "True", "True"),
("simple-alternate-routing", "True", "True"),
("simple-global-routing", "True", "True"),
("simple-routing-ping6", "True", "True"),
("static-routing-slash32", "True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = [
("simple-routing-ping6.py", "True"),
]
| zy901002-gpsr | examples/routing/examples-to-run.py | Python | gpl2 | 994 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// Test program for this 3-router scenario, using global routing
//
// (a.a.a.a/32)A<--x.x.x.0/30-->B<--y.y.y.0/30-->C(c.c.c.c/32)
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/csma-net-device.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-static-routing.h"
#include "ns3/ipv4-global-routing.h"
#include "ns3/ipv4-list-routing.h"
#include "ns3/ipv4-routing-table-entry.h"
#include "ns3/global-router-interface.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-list-routing-helper.h"
#include "ns3/ipv4-global-routing-helper.h"
using namespace ns3;
using std::cout;
NS_LOG_COMPONENT_DEFINE ("GlobalRouterInjectionTest");
int
main (int argc, char *argv[])
{
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);
Ptr<Node> nA = CreateObject<Node> ();
Ptr<Node> nB = CreateObject<Node> ();
Ptr<Node> nC = CreateObject<Node> ();
NodeContainer c = NodeContainer (nA, nB, nC);
InternetStackHelper internet;
// Point-to-point links
NodeContainer nAnB = NodeContainer (nA, nB);
NodeContainer nBnC = NodeContainer (nB, nC);
internet.Install (nAnB);
Ipv4ListRoutingHelper staticonly;
Ipv4ListRoutingHelper staticRouting;
staticonly.Add (staticRouting, 0);
internet.SetRoutingHelper (staticonly); // has effect on the next Install ()
internet.Install (NodeContainer (nC));
// We create the channels first without any IP addressing information
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer dAdB = p2p.Install (nAnB);
NetDeviceContainer dBdC = p2p.Install (nBnC);;
Ptr<CsmaNetDevice> deviceA = CreateObject<CsmaNetDevice> ();
deviceA->SetAddress (Mac48Address::Allocate ());
nA->AddDevice (deviceA);
Ptr<CsmaNetDevice> deviceC = CreateObject<CsmaNetDevice> ();
deviceC->SetAddress (Mac48Address::Allocate ());
nC->AddDevice (deviceC);
// Later, we add IP addresses.
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.252");
Ipv4InterfaceContainer iAiB = ipv4.Assign (dAdB);
ipv4.SetBase ("10.1.1.4", "255.255.255.252");
Ipv4InterfaceContainer iBiC = ipv4.Assign (dBdC);
Ptr<Ipv4> ipv4A = nA->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4B = nB->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4C = nC->GetObject<Ipv4> ();
int32_t ifIndexA = ipv4A->AddInterface (deviceA);
int32_t ifIndexC = ipv4C->AddInterface (deviceC);
Ipv4InterfaceAddress ifInAddrA = Ipv4InterfaceAddress (Ipv4Address ("172.16.1.1"), Ipv4Mask ("255.255.255.255"));
ipv4A->AddAddress (ifIndexA, ifInAddrA);
ipv4A->SetMetric (ifIndexA, 1);
ipv4A->SetUp (ifIndexA);
Ipv4InterfaceAddress ifInAddrC = Ipv4InterfaceAddress (Ipv4Address ("192.168.1.1"), Ipv4Mask ("255.255.255.255"));
ipv4C->AddAddress (ifIndexC, ifInAddrC);
ipv4C->SetMetric (ifIndexC, 1);
ipv4C->SetUp (ifIndexC);
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes.
// Populate routing tables for nodes nA and nB
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Inject global routes from Node B, including transit network...
Ptr<GlobalRouter> globalRouterB = nB->GetObject<GlobalRouter> ();
globalRouterB->InjectRoute ("10.1.1.4", "255.255.255.252");
// ...and the host in network "C"
globalRouterB->InjectRoute ("192.168.1.1", "255.255.255.255");
Ipv4GlobalRoutingHelper::RecomputeRoutingTables ();
// In addition, nB needs a static route to nC so it knows what to do with stuff
// going to 192.168.1.1
Ipv4StaticRoutingHelper ipv4RoutingHelper;
Ptr<Ipv4StaticRouting> staticRoutingB = ipv4RoutingHelper.GetStaticRouting (ipv4B);
staticRoutingB->AddHostRouteTo (Ipv4Address ("192.168.1.1"), Ipv4Address ("10.1.1.6"),2);
// Create the OnOff application to send UDP datagrams of size
// 210 bytes at a rate of 448 Kb/s
uint16_t port = 9; // Discard port (RFC 863)
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (ifInAddrC.GetLocal (), port)));
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
onoff.SetAttribute ("DataRate", DataRateValue (DataRate (6000)));
ApplicationContainer apps = onoff.Install (nA);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
// Create a packet sink to receive these packets
PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (nC);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("global-routing-injection32.tr"));
p2p.EnablePcapAll ("global-routing-injection32");
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/routing/global-injection-slash32.cc | C++ | gpl2 | 5,903 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
obj = bld.create_ns3_program('dynamic-global-routing',
['point-to-point', 'csma', 'internet'])
obj.source = 'dynamic-global-routing.cc'
obj = bld.create_ns3_program('static-routing-slash32',
['point-to-point', 'csma', 'internet'])
obj.source = 'static-routing-slash32.cc'
obj = bld.create_ns3_program('global-routing-slash32',
['point-to-point', 'csma', 'internet'])
obj.source = 'global-routing-slash32.cc'
obj = bld.create_ns3_program('global-injection-slash32',
['point-to-point', 'csma', 'internet'])
obj.source = 'global-injection-slash32.cc'
obj = bld.create_ns3_program('simple-global-routing',
['point-to-point', 'internet', 'applications', 'flow-monitor'])
obj.source = 'simple-global-routing.cc'
obj = bld.create_ns3_program('simple-alternate-routing',
['point-to-point', 'internet', 'applications'])
obj.source = 'simple-alternate-routing.cc'
obj = bld.create_ns3_program( 'mixed-global-routing',
['point-to-point', 'internet', 'csma'])
obj.source = 'mixed-global-routing.cc'
obj = bld.create_ns3_program('simple-routing-ping6',
['csma', 'internet'])
obj.source = 'simple-routing-ping6.cc'
obj = bld.create_ns3_program('manet-routing-compare',
['wifi', 'dsdv', 'aodv', 'olsr', 'internet', 'applications'])
obj.source = 'manet-routing-compare.cc'
bld.register_ns3_script('simple-routing-ping6.py', ['csma', 'internet', 'applications'])
| zy901002-gpsr | examples/routing/wscript | Python | gpl2 | 1,803 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// Test program for this 3-router scenario, using global routing
//
// (a.a.a.a/32)A<--x.x.x.0/30-->B<--y.y.y.0/30-->C(c.c.c.c/32)
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/csma-net-device.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("GlobalRouterSlash32Test");
int
main (int argc, char *argv[])
{
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);
Ptr<Node> nA = CreateObject<Node> ();
Ptr<Node> nB = CreateObject<Node> ();
Ptr<Node> nC = CreateObject<Node> ();
NodeContainer c = NodeContainer (nA, nB, nC);
InternetStackHelper internet;
internet.Install (c);
// Point-to-point links
NodeContainer nAnB = NodeContainer (nA, nB);
NodeContainer nBnC = NodeContainer (nB, nC);
// We create the channels first without any IP addressing information
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer dAdB = p2p.Install (nAnB);
NetDeviceContainer dBdC = p2p.Install (nBnC);;
Ptr<CsmaNetDevice> deviceA = CreateObject<CsmaNetDevice> ();
deviceA->SetAddress (Mac48Address::Allocate ());
nA->AddDevice (deviceA);
Ptr<CsmaNetDevice> deviceC = CreateObject<CsmaNetDevice> ();
deviceC->SetAddress (Mac48Address::Allocate ());
nC->AddDevice (deviceC);
// Later, we add IP addresses.
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.252");
Ipv4InterfaceContainer iAiB = ipv4.Assign (dAdB);
ipv4.SetBase ("10.1.1.4", "255.255.255.252");
Ipv4InterfaceContainer iBiC = ipv4.Assign (dBdC);
Ptr<Ipv4> ipv4A = nA->GetObject<Ipv4> ();
Ptr<Ipv4> ipv4C = nC->GetObject<Ipv4> ();
int32_t ifIndexA = ipv4A->AddInterface (deviceA);
int32_t ifIndexC = ipv4C->AddInterface (deviceC);
Ipv4InterfaceAddress ifInAddrA = Ipv4InterfaceAddress (Ipv4Address ("172.16.1.1"), Ipv4Mask ("255.255.255.255"));
ipv4A->AddAddress (ifIndexA, ifInAddrA);
ipv4A->SetMetric (ifIndexA, 1);
ipv4A->SetUp (ifIndexA);
Ipv4InterfaceAddress ifInAddrC = Ipv4InterfaceAddress (Ipv4Address ("192.168.1.1"), Ipv4Mask ("255.255.255.255"));
ipv4C->AddAddress (ifIndexC, ifInAddrC);
ipv4C->SetMetric (ifIndexC, 1);
ipv4C->SetUp (ifIndexC);
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Create the OnOff application to send UDP datagrams of size
// 210 bytes at a rate of 448 Kb/s
uint16_t port = 9; // Discard port (RFC 863)
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (ifInAddrC.GetLocal (), port)));
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0)));
onoff.SetAttribute ("DataRate", DataRateValue (DataRate (6000)));
ApplicationContainer apps = onoff.Install (nA);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
// Create a packet sink to receive these packets
PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (nC);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("global-routing-slash32.tr"));
p2p.EnablePcapAll ("global-routing-slash32");
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/routing/global-routing-slash32.cc | C++ | gpl2 | 4,582 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SixthScriptExample");
// ===========================================================================
//
// node 0 node 1
// +----------------+ +----------------+
// | ns-3 TCP | | ns-3 TCP |
// +----------------+ +----------------+
// | 10.1.1.1 | | 10.1.1.2 |
// +----------------+ +----------------+
// | point-to-point | | point-to-point |
// +----------------+ +----------------+
// | |
// +---------------------+
// 5 Mbps, 2 ms
//
//
// We want to look at changes in the ns-3 TCP congestion window. We need
// to crank up a flow and hook the CongestionWindow attribute on the socket
// of the sender. Normally one would use an on-off application to generate a
// flow, but this has a couple of problems. First, the socket of the on-off
// application is not created until Application Start time, so we wouldn't be
// able to hook the socket (now) at configuration time. Second, even if we
// could arrange a call after start time, the socket is not public so we
// couldn't get at it.
//
// So, we can cook up a simple version of the on-off application that does what
// we want. On the plus side we don't need all of the complexity of the on-off
// application. On the minus side, we don't have a helper, so we have to get
// a little more involved in the details, but this is trivial.
//
// So first, we create a socket and do the trace connect on it; then we pass
// this socket into the constructor of our simple application which we then
// install in the source node.
// ===========================================================================
//
class MyApp : public Application
{
public:
MyApp ();
virtual ~MyApp();
void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate);
private:
virtual void StartApplication (void);
virtual void StopApplication (void);
void ScheduleTx (void);
void SendPacket (void);
Ptr<Socket> m_socket;
Address m_peer;
uint32_t m_packetSize;
uint32_t m_nPackets;
DataRate m_dataRate;
EventId m_sendEvent;
bool m_running;
uint32_t m_packetsSent;
};
MyApp::MyApp ()
: m_socket (0),
m_peer (),
m_packetSize (0),
m_nPackets (0),
m_dataRate (0),
m_sendEvent (),
m_running (false),
m_packetsSent (0)
{
}
MyApp::~MyApp()
{
m_socket = 0;
}
void
MyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate)
{
m_socket = socket;
m_peer = address;
m_packetSize = packetSize;
m_nPackets = nPackets;
m_dataRate = dataRate;
}
void
MyApp::StartApplication (void)
{
m_running = true;
m_packetsSent = 0;
m_socket->Bind ();
m_socket->Connect (m_peer);
SendPacket ();
}
void
MyApp::StopApplication (void)
{
m_running = false;
if (m_sendEvent.IsRunning ())
{
Simulator::Cancel (m_sendEvent);
}
if (m_socket)
{
m_socket->Close ();
}
}
void
MyApp::SendPacket (void)
{
Ptr<Packet> packet = Create<Packet> (m_packetSize);
m_socket->Send (packet);
if (++m_packetsSent < m_nPackets)
{
ScheduleTx ();
}
}
void
MyApp::ScheduleTx (void)
{
if (m_running)
{
Time tNext (Seconds (m_packetSize * 8 / static_cast<double> (m_dataRate.GetBitRate ())));
m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this);
}
}
static void
CwndChange (Ptr<OutputStreamWrapper> stream, uint32_t oldCwnd, uint32_t newCwnd)
{
NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);
*stream->GetStream () << Simulator::Now ().GetSeconds () << "\t" << oldCwnd << "\t" << newCwnd << std::endl;
}
static void
RxDrop (Ptr<PcapFileWrapper> file, Ptr<const Packet> p)
{
NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());
file->Write (Simulator::Now (), p);
}
int
main (int argc, char *argv[])
{
NodeContainer nodes;
nodes.Create (2);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install (nodes);
Ptr<RateErrorModel> em = CreateObjectWithAttributes<RateErrorModel> (
"RanVar", RandomVariableValue (UniformVariable (0., 1.)),
"ErrorRate", DoubleValue (0.00001));
devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em));
InternetStackHelper stack;
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.252");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
uint16_t sinkPort = 8080;
Address sinkAddress (InetSocketAddress (interfaces.GetAddress (1), sinkPort));
PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
ApplicationContainer sinkApps = packetSinkHelper.Install (nodes.Get (1));
sinkApps.Start (Seconds (0.));
sinkApps.Stop (Seconds (20.));
Ptr<Socket> ns3TcpSocket = Socket::CreateSocket (nodes.Get (0), TcpSocketFactory::GetTypeId ());
Ptr<MyApp> app = CreateObject<MyApp> ();
app->Setup (ns3TcpSocket, sinkAddress, 1040, 1000, DataRate ("1Mbps"));
nodes.Get (0)->AddApplication (app);
app->SetStartTime (Seconds (1.));
app->SetStopTime (Seconds (20.));
AsciiTraceHelper asciiTraceHelper;
Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream ("sixth.cwnd");
ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", MakeBoundCallback (&CwndChange, stream));
PcapHelper pcapHelper;
Ptr<PcapFileWrapper> file = pcapHelper.CreateFile ("sixth.pcap", std::ios::out, PcapHelper::DLT_PPP);
devices.Get (1)->TraceConnectWithoutContext ("PhyRxDrop", MakeBoundCallback (&RxDrop, file));
Simulator::Stop (Seconds (20));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/tutorial/sixth.cc | C++ | gpl2 | 6,976 |
# /*
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License version 2 as
# * published by the Free Software Foundation;
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# */
import ns.applications
import ns.core
import ns.internet
import ns.network
import ns.point_to_point
ns.core.LogComponentEnable("UdpEchoClientApplication", ns.core.LOG_LEVEL_INFO)
ns.core.LogComponentEnable("UdpEchoServerApplication", ns.core.LOG_LEVEL_INFO)
nodes = ns.network.NodeContainer()
nodes.Create(2)
pointToPoint = ns.point_to_point.PointToPointHelper()
pointToPoint.SetDeviceAttribute("DataRate", ns.core.StringValue("5Mbps"))
pointToPoint.SetChannelAttribute("Delay", ns.core.StringValue("2ms"))
devices = pointToPoint.Install(nodes)
stack = ns.internet.InternetStackHelper()
stack.Install(nodes)
address = ns.internet.Ipv4AddressHelper()
address.SetBase(ns.network.Ipv4Address("10.1.1.0"), ns.network.Ipv4Mask("255.255.255.0"))
interfaces = address.Assign (devices);
echoServer = ns.applications.UdpEchoServerHelper(9)
serverApps = echoServer.Install(nodes.Get(1))
serverApps.Start(ns.core.Seconds(1.0))
serverApps.Stop(ns.core.Seconds(10.0))
echoClient = ns.applications.UdpEchoClientHelper(interfaces.GetAddress(1), 9)
echoClient.SetAttribute("MaxPackets", ns.core.UintegerValue(1))
echoClient.SetAttribute("Interval", ns.core.TimeValue(ns.core.Seconds (1.0)))
echoClient.SetAttribute("PacketSize", ns.core.UintegerValue(1024))
clientApps = echoClient.Install(nodes.Get(0))
clientApps.Start(ns.core.Seconds(2.0))
clientApps.Stop(ns.core.Seconds(10.0))
ns.core.Simulator.Run()
ns.core.Simulator.Destroy()
| zy901002-gpsr | examples/tutorial/first.py | Python | gpl2 | 2,115 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");
int
main (int argc, char *argv[])
{
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
NodeContainer nodes;
nodes.Create (2);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install (nodes);
InternetStackHelper stack;
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/tutorial/first.cc | C++ | gpl2 | 2,272 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
// Default Network Topology
//
// Wifi 10.1.3.0
// AP
// * * * *
// | | | | 10.1.1.0
// n5 n6 n7 n0 -------------- n1 n2 n3 n4
// point-to-point | | | |
// ================
// LAN 10.1.2.0
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("ThirdScriptExample");
int
main (int argc, char *argv[])
{
bool verbose = true;
uint32_t nCsma = 3;
uint32_t nWifi = 3;
CommandLine cmd;
cmd.AddValue ("nCsma", "Number of \"extra\" CSMA nodes/devices", nCsma);
cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi);
cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose);
cmd.Parse (argc,argv);
if (verbose)
{
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
}
NodeContainer p2pNodes;
p2pNodes.Create (2);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer p2pDevices;
p2pDevices = pointToPoint.Install (p2pNodes);
NodeContainer csmaNodes;
csmaNodes.Add (p2pNodes.Get (1));
csmaNodes.Create (nCsma);
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));
NetDeviceContainer csmaDevices;
csmaDevices = csma.Install (csmaNodes);
NodeContainer wifiStaNodes;
wifiStaNodes.Create (nWifi);
NodeContainer wifiApNode = p2pNodes.Get (0);
YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();
YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
phy.SetChannel (channel.Create ());
WifiHelper wifi = WifiHelper::Default ();
wifi.SetRemoteStationManager ("ns3::AarfWifiManager");
NqosWifiMacHelper mac = NqosWifiMacHelper::Default ();
Ssid ssid = Ssid ("ns-3-ssid");
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue (false));
NetDeviceContainer staDevices;
staDevices = wifi.Install (phy, mac, wifiStaNodes);
mac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));
NetDeviceContainer apDevices;
apDevices = wifi.Install (phy, mac, wifiApNode);
MobilityHelper mobility;
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (0.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (5.0),
"DeltaY", DoubleValue (10.0),
"GridWidth", UintegerValue (3),
"LayoutType", StringValue ("RowFirst"));
mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
"Bounds", RectangleValue (Rectangle (-50, 50, -50, 50)));
mobility.Install (wifiStaNodes);
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiApNode);
InternetStackHelper stack;
stack.Install (csmaNodes);
stack.Install (wifiApNode);
stack.Install (wifiStaNodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer p2pInterfaces;
p2pInterfaces = address.Assign (p2pDevices);
address.SetBase ("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer csmaInterfaces;
csmaInterfaces = address.Assign (csmaDevices);
address.SetBase ("10.1.3.0", "255.255.255.0");
address.Assign (staDevices);
address.Assign (apDevices);
UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (nCsma));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
ApplicationContainer clientApps =
echoClient.Install (wifiStaNodes.Get (nWifi - 1));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
Simulator::Stop (Seconds (10.0));
pointToPoint.EnablePcapAll ("third");
phy.EnablePcap ("third", apDevices.Get (0));
csma.EnablePcap ("third", csmaDevices.Get (0), true);
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/tutorial/third.cc | C++ | gpl2 | 5,631 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("FifthScriptExample");
// ===========================================================================
//
// node 0 node 1
// +----------------+ +----------------+
// | ns-3 TCP | | ns-3 TCP |
// +----------------+ +----------------+
// | 10.1.1.1 | | 10.1.1.2 |
// +----------------+ +----------------+
// | point-to-point | | point-to-point |
// +----------------+ +----------------+
// | |
// +---------------------+
// 5 Mbps, 2 ms
//
//
// We want to look at changes in the ns-3 TCP congestion window. We need
// to crank up a flow and hook the CongestionWindow attribute on the socket
// of the sender. Normally one would use an on-off application to generate a
// flow, but this has a couple of problems. First, the socket of the on-off
// application is not created until Application Start time, so we wouldn't be
// able to hook the socket (now) at configuration time. Second, even if we
// could arrange a call after start time, the socket is not public so we
// couldn't get at it.
//
// So, we can cook up a simple version of the on-off application that does what
// we want. On the plus side we don't need all of the complexity of the on-off
// application. On the minus side, we don't have a helper, so we have to get
// a little more involved in the details, but this is trivial.
//
// So first, we create a socket and do the trace connect on it; then we pass
// this socket into the constructor of our simple application which we then
// install in the source node.
// ===========================================================================
//
class MyApp : public Application
{
public:
MyApp ();
virtual ~MyApp();
void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate);
private:
virtual void StartApplication (void);
virtual void StopApplication (void);
void ScheduleTx (void);
void SendPacket (void);
Ptr<Socket> m_socket;
Address m_peer;
uint32_t m_packetSize;
uint32_t m_nPackets;
DataRate m_dataRate;
EventId m_sendEvent;
bool m_running;
uint32_t m_packetsSent;
};
MyApp::MyApp ()
: m_socket (0),
m_peer (),
m_packetSize (0),
m_nPackets (0),
m_dataRate (0),
m_sendEvent (),
m_running (false),
m_packetsSent (0)
{
}
MyApp::~MyApp()
{
m_socket = 0;
}
void
MyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate)
{
m_socket = socket;
m_peer = address;
m_packetSize = packetSize;
m_nPackets = nPackets;
m_dataRate = dataRate;
}
void
MyApp::StartApplication (void)
{
m_running = true;
m_packetsSent = 0;
m_socket->Bind ();
m_socket->Connect (m_peer);
SendPacket ();
}
void
MyApp::StopApplication (void)
{
m_running = false;
if (m_sendEvent.IsRunning ())
{
Simulator::Cancel (m_sendEvent);
}
if (m_socket)
{
m_socket->Close ();
}
}
void
MyApp::SendPacket (void)
{
Ptr<Packet> packet = Create<Packet> (m_packetSize);
m_socket->Send (packet);
if (++m_packetsSent < m_nPackets)
{
ScheduleTx ();
}
}
void
MyApp::ScheduleTx (void)
{
if (m_running)
{
Time tNext (Seconds (m_packetSize * 8 / static_cast<double> (m_dataRate.GetBitRate ())));
m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this);
}
}
static void
CwndChange (uint32_t oldCwnd, uint32_t newCwnd)
{
NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);
}
static void
RxDrop (Ptr<const Packet> p)
{
NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());
}
int
main (int argc, char *argv[])
{
NodeContainer nodes;
nodes.Create (2);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install (nodes);
Ptr<RateErrorModel> em = CreateObjectWithAttributes<RateErrorModel> (
"RanVar", RandomVariableValue (UniformVariable (0., 1.)),
"ErrorRate", DoubleValue (0.00001));
devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em));
InternetStackHelper stack;
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.252");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
uint16_t sinkPort = 8080;
Address sinkAddress (InetSocketAddress (interfaces.GetAddress (1), sinkPort));
PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
ApplicationContainer sinkApps = packetSinkHelper.Install (nodes.Get (1));
sinkApps.Start (Seconds (0.));
sinkApps.Stop (Seconds (20.));
Ptr<Socket> ns3TcpSocket = Socket::CreateSocket (nodes.Get (0), TcpSocketFactory::GetTypeId ());
ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", MakeCallback (&CwndChange));
Ptr<MyApp> app = CreateObject<MyApp> ();
app->Setup (ns3TcpSocket, sinkAddress, 1040, 1000, DataRate ("1Mbps"));
nodes.Get (0)->AddApplication (app);
app->SetStartTime (Seconds (1.));
app->SetStopTime (Seconds (20.));
devices.Get (1)->TraceConnectWithoutContext ("PhyRxDrop", MakeCallback (&RxDrop));
Simulator::Stop (Seconds (20));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/tutorial/fifth.cc | C++ | gpl2 | 6,490 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("first", "True", "True"),
("hello-simulator", "True", "True"),
("second", "True", "True"),
("third", "True", "True"),
("fourth", "True", "True"),
("fifth", "True", "True"),
("sixth", "True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = [
("first.py", "True"),
]
| zy901002-gpsr | examples/tutorial/examples-to-run.py | Python | gpl2 | 825 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
obj = bld.create_ns3_program('hello-simulator', ['core'])
obj.source = 'hello-simulator.cc'
obj = bld.create_ns3_program('first', ['core', 'point-to-point', 'internet', 'applications'])
obj.source = 'first.cc'
bld.register_ns3_script('first.py', ['internet', 'point-to-point', 'applications'])
obj = bld.create_ns3_program('second', ['core', 'point-to-point', 'csma', 'internet', 'applications'])
obj.source = 'second.cc'
obj = bld.create_ns3_program('third', ['core', 'point-to-point', 'csma', 'wifi', 'internet'])
obj.source = 'third.cc'
obj = bld.create_ns3_program('fourth', ['core'])
obj.source = 'fourth.cc'
obj = bld.create_ns3_program('fifth', ['core', 'point-to-point', 'internet', 'applications'])
obj.source = 'fifth.cc'
obj = bld.create_ns3_program('sixth', ['core', 'point-to-point', 'internet', 'applications'])
obj.source = 'sixth.cc'
| zy901002-gpsr | examples/tutorial/wscript | Python | gpl2 | 1,042 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ns3/object.h"
#include "ns3/uinteger.h"
#include "ns3/traced-value.h"
#include "ns3/trace-source-accessor.h"
#include <iostream>
using namespace ns3;
class MyObject : public Object
{
public:
static TypeId GetTypeId (void)
{
static TypeId tid = TypeId ("MyObject")
.SetParent (Object::GetTypeId ())
.AddConstructor<MyObject> ()
.AddTraceSource ("MyInteger",
"An integer value to trace.",
MakeTraceSourceAccessor (&MyObject::m_myInt))
;
return tid;
}
MyObject () {}
TracedValue<int32_t> m_myInt;
};
void
IntTrace (int32_t oldValue, int32_t newValue)
{
std::cout << "Traced " << oldValue << " to " << newValue << std::endl;
}
int
main (int argc, char *argv[])
{
Ptr<MyObject> myObject = CreateObject<MyObject> ();
myObject->TraceConnectWithoutContext ("MyInteger", MakeCallback (&IntTrace));
myObject->m_myInt = 1234;
}
| zy901002-gpsr | examples/tutorial/fourth.cc | C++ | gpl2 | 1,650 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
// Default Network Topology
//
// 10.1.1.0
// n0 -------------- n1 n2 n3 n4
// point-to-point | | | |
// ================
// LAN 10.1.2.0
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SecondScriptExample");
int
main (int argc, char *argv[])
{
bool verbose = true;
uint32_t nCsma = 3;
CommandLine cmd;
cmd.AddValue ("nCsma", "Number of \"extra\" CSMA nodes/devices", nCsma);
cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose);
cmd.Parse (argc,argv);
if (verbose)
{
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
}
nCsma = nCsma == 0 ? 1 : nCsma;
NodeContainer p2pNodes;
p2pNodes.Create (2);
NodeContainer csmaNodes;
csmaNodes.Add (p2pNodes.Get (1));
csmaNodes.Create (nCsma);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer p2pDevices;
p2pDevices = pointToPoint.Install (p2pNodes);
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));
NetDeviceContainer csmaDevices;
csmaDevices = csma.Install (csmaNodes);
InternetStackHelper stack;
stack.Install (p2pNodes.Get (0));
stack.Install (csmaNodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer p2pInterfaces;
p2pInterfaces = address.Assign (p2pDevices);
address.SetBase ("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer csmaInterfaces;
csmaInterfaces = address.Assign (csmaDevices);
UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (nCsma));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
ApplicationContainer clientApps = echoClient.Install (p2pNodes.Get (0));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
pointToPoint.EnablePcapAll ("second");
csma.EnablePcap ("second", csmaDevices.Get (1), true);
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| zy901002-gpsr | examples/tutorial/second.cc | C++ | gpl2 | 3,580 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ns3/core-module.h"
NS_LOG_COMPONENT_DEFINE ("HelloSimulator");
using namespace ns3;
int
main (int argc, char *argv[])
{
NS_LOG_UNCOND ("Hello Simulator");
}
| zy901002-gpsr | examples/tutorial/hello-simulator.cc | C++ | gpl2 | 894 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2007 INRIA
* 2009,2010 Contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Martín Giachino <martin.giachino@gmail.com>
*
*
* This example demonstrates the use of Ns2TransmobilityHelper class to work with mobility.
*
* Detailed example description.
*
* - intended usage: this should be used in order to load ns2 movement trace files into ns3.
* - behavior:
* - Ns2TransmobilityHelperTrace object is created, whith the specified trace file. At this moment, only
* specify the file, and no movements are scheduled.
* - A log file is created, using the log file name argument.
* - A node container is created with the correct node number specified in the command line.
* - Use Install method of Ns2TransmobilityHelperTrace to set mobility to nodes. At this moment, file is
* read line by line, and the movement is scheduled in the simulator.
* - A callback is configured, so each time a node changes its course a log message is printed.
* - expected output: example prints out messages generated by each read line from the ns2 movement trace file.
* For each line, it shows if the line is correct, or of it has errors and in this case it will
* be ignored.
*
* Usage of ns2-mobility-trace:
*
* ./waf --run "examples/mobility/ns2-mobility-trace \
* --traceFile=/home/mgiachino/ns-3-dev/examples/mobility/default.ns_movements
* --nodeNum=2 --duration=100.0 --logFile=ns2-mobility-trace.log"
*
* NOTE: ns2-traces-file could be an absolute or relative path. You could use the file default.ns_movements
* included in the same directory that the present file.
* NOTE 2: Number of nodes present in the trace file must match with the command line argument.
* Note that you must know it before to be able to load it.
* NOTE 3: Duration must be a positive number. Note that you must know it before to be able to load it.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include "ns3/core-module.h"
#include "ns3/mobility-module.h"
#include "ns3/mobility-module.h"
#include "ns3/ns2-mobility-helper.h"
using namespace ns3;
// Prints actual position and velocity when a course change event occurs
static void
CourseChange (std::ostream *os, std::string foo, Ptr<const MobilityModel> mobility)
{
Vector pos = mobility->GetPosition (); // Get position
Vector vel = mobility->GetVelocity (); // Get velocity
// Prints position and velocities
*os << Simulator::Now () << " POS: x=" << pos.x << ", y=" << pos.y
<< ", z=" << pos.z << "; VEL:" << vel.x << ", y=" << vel.y
<< ", z=" << vel.z << std::endl;
}
// Example to use ns2 traces file in ns3
int main (int argc, char *argv[])
{
std::string traceFile;
std::string logFile;
int nodeNum;
double duration;
// Enable logging from the ns2 helper
LogComponentEnable ("Ns2MobilityHelper",LOG_LEVEL_DEBUG);
// Parse command line attribute
CommandLine cmd;
cmd.AddValue ("traceFile", "Ns2 movement trace file", traceFile);
cmd.AddValue ("nodeNum", "Number of nodes", nodeNum);
cmd.AddValue ("duration", "Duration of Simulation", duration);
cmd.AddValue ("logFile", "Log file", logFile);
cmd.Parse (argc,argv);
// Check command line arguments
if (traceFile.empty () || nodeNum <= 0 || duration <= 0 || logFile.empty ())
{
std::cout << "Usage of " << argv[0] << " :\n\n"
"./waf --run \"ns2-mobility-trace"
" --traceFile=/home/mgiachino/ns-3-dev/examples/mobility/default.ns_movements"
" --nodeNum=2 --duration=100.0 --logFile=main-ns2-mob.log\" \n\n"
"NOTE: ns2-traces-file could be an absolute or relative path. You could use the file default.ns_movements\n"
" included in the same directory that the present file.\n\n"
"NOTE 2: Number of nodes present in the trace file must match with the command line argument and must\n"
" be a positive number. Note that you must know it before to be able to load it.\n\n"
"NOTE 3: Duration must be a positive number. Note that you must know it before to be able to load it.\n\n";
return 0;
}
// Create Ns2MobilityHelper with the specified trace log file as parameter
Ns2MobilityHelper ns2 = Ns2MobilityHelper (traceFile);
// open log file for output
std::ofstream os;
os.open (logFile.c_str ());
// Create all nodes.
NodeContainer stas;
stas.Create (nodeNum);
ns2.Install (); // configure movements for each node, while reading trace file
// Configure callback for logging
Config::Connect ("/NodeList/*/$ns3::MobilityModel/CourseChange",
MakeBoundCallback (&CourseChange, &os));
Simulator::Stop (Seconds (duration));
Simulator::Run ();
Simulator::Destroy ();
os.close (); // close log file
return 0;
}
| zy901002-gpsr | examples/mobility/ns2-mobility-trace.cc | C++ | gpl2 | 5,621 |
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
obj = bld.create_ns3_program('ns2-mobility-trace', ['internet', 'mobility', 'wifi', 'mesh', 'applications'])
obj.source = 'ns2-mobility-trace.cc'
| zy901002-gpsr | examples/mobility/wscript | Python | gpl2 | 256 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Network topology
//
// n0 n1 n2 n3
// | | | |
// =================
// LAN
//
// - UDP flows from n0 to n1 and back
// - DropTail queues
// - Tracing of queues and packet receptions to file "udp-echo.tr"
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("UdpEchoExample");
int
main (int argc, char *argv[])
{
//
// Users may find it convenient to turn on explicit debugging
// for selected modules; the below lines suggest how to do this
//
#if 0
LogComponentEnable ("UdpEchoExample", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_ALL);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_ALL);
#endif
//
// Allow the user to override any of the defaults and the above Bind() at
// run-time, via command-line arguments
//
CommandLine cmd;
cmd.Parse (argc, argv);
//
// Explicitly create the nodes required by the topology (shown above).
//
NS_LOG_INFO ("Create nodes.");
NodeContainer n;
n.Create (4);
InternetStackHelper internet;
internet.Install (n);
NS_LOG_INFO ("Create channels.");
//
// Explicitly create the channels required by the topology (shown above).
//
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (DataRate (5000000)));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
csma.SetDeviceAttribute ("Mtu", UintegerValue (1400));
NetDeviceContainer d = csma.Install (n);
Ipv4AddressHelper ipv4;
//
// We've got the "hardware" in place. Now we need to add IP addresses.
//
NS_LOG_INFO ("Assign IP Addresses.");
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer i = ipv4.Assign (d);
NS_LOG_INFO ("Create Applications.");
//
// Create a UdpEchoServer application on node one.
//
uint16_t port = 9; // well-known echo port number
UdpEchoServerHelper server (port);
ApplicationContainer apps = server.Install (n.Get (1));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
//
// Create a UdpEchoClient application to send UDP datagrams from node zero to
// node one.
//
uint32_t packetSize = 1024;
uint32_t maxPacketCount = 1;
Time interPacketInterval = Seconds (1.);
UdpEchoClientHelper client (i.GetAddress (1), port);
client.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
client.SetAttribute ("Interval", TimeValue (interPacketInterval));
client.SetAttribute ("PacketSize", UintegerValue (packetSize));
apps = client.Install (n.Get (0));
apps.Start (Seconds (2.0));
apps.Stop (Seconds (10.0));
#if 0
//
// Users may find it convenient to initialize echo packets with actual data;
// the below lines suggest how to do this
//
client.SetFill (apps.Get (0), "Hello World");
client.SetFill (apps.Get (0), 0xa5, 1024);
uint8_t fill[] = { 0, 1, 2, 3, 4, 5, 6};
client.SetFill (apps.Get (0), fill, sizeof(fill), 1024);
#endif
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("udp-echo.tr"));
csma.EnablePcapAll ("udp-echo", false);
//
// Now, do the actual simulation.
//
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| zy901002-gpsr | examples/udp/udp-echo.cc | C++ | gpl2 | 4,032 |
#! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("udp-echo", "True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
| zy901002-gpsr | examples/udp/examples-to-run.py | Python | gpl2 | 603 |