`
xhload3d
  • 浏览: 206593 次
社区版块
存档分类
最新评论

基于HT for Web的3D呈现A* Search Algorithm

阅读更多

IMG_1486

最近搞个游戏遇到最短路径的常规游戏问题,正巧看到老同事写的3D机房最短路径巡线文章,一时起兴基于HT for Web写了个A*算法的WebGL 3D呈现,算法基于开源 https://github.com/bgrins/javascript-astar 的javascript实现,其实作者也有个不错的2D例子实现 http://www.briangrinstead.com/files/astar/ ,只不过觉得所有A*算法的可视化实现都是平面的不够酷,另外还有不少参数需要调节控制,还是值得好好搞个全面的Demo,先上张2D和3D例子的对照图。

Screen Shot 2014-11-24 at 5.36.33 PM

实现代码比较容易一百多行,不过算法核心在astar.js了,界面核心在ht.js里面了,我只需要构建网格信息,只需监听用户点击,然后调用astar.js进行最短路径计算,将结果通过动画的方式呈现出走动的过程,所有代码如下:

function init() {                
	w = 40; m = 20; d = w * m / 2;            
	gridRows = [];                        
	dm = new ht.DataModel();             
	g3d = new ht.graph3d.Graph3dView(dm);                
	g3d.setGridVisible(true);
	g3d.setGridColor('#BBBBBB');
	g3d.setGridSize(m);
	g3d.setGridGap(w);            
	g3d.addToDOM();                                                                                                        
	g3d.sm().setSelectionMode('none');            
	anim = startBall = endBall = null;                        
	g3d.getView().addEventListener(ht.Default.isTouchable ? 'touchstart' : 'mousedown', function(e){                
		if(!anim){
			var p = g3d.getHitPosition(e);
			var x = Math.floor((p[0] + d)/ w);
			var y = Math.floor((p[2] + d)/ w);
			var endBall = dm.getDataByTag("cell_" + x + "_" + y);
			if(endBall && endBall.s('batch') !== 'wall'){                      
				if(startBall.a('x') === x && startBall.a('y') === y){
					return;
				}                        
				var g = new Graph(gridRows, { 
					diagonal: formPane.v('diagonal') 
				});
				var start = g.grid[startBall.a('x')][startBall.a('y')];
				var end = g.grid[x][y];
				var result = astar.search(g, start, end, {
					closest: formPane.v('closest')                            
				});  
				if(!result.length){
					return;
				}
				x = result[result.length-1].x;
				y = result[result.length-1].y;
				endBall = dm.getDataByTag("cell_" + x + "_" + y);
				endBall.s('3d.visible', true);
				startBall.s('3d.visible', false);
				formPane.setDisabled(true);
				anim = ht.Default.startAnim({
					duration: 700,
					finishFunc: function(){  
						for(var i=0; i<result.length; i++){
							var ball = dm.getDataByTag("cell_" + result[i].x + "_" + result[i].y);
							ball.s({
								'3d.visible': false,
								'shape3d.opacity': 1,
								'shape3d.transparent': false
							}); 
							startBall.p3(-d+w*x+w/2, w/2, -d+w*y+w/2);
							startBall.a({x: x, y: y});
							startBall.s('3d.visible', true);
						}
						anim = null;
						formPane.setDisabled(false);
					},
					action: function(v){
						var index = Math.round(v*result.length);
						for(var i=0; i<index; i++){
							var ball = dm.getDataByTag("cell_" + result[i].x + "_" + result[i].y);
							ball.s({
								'3d.visible': true,
								'shape3d.opacity': i/index*0.3 + 0.7,
								'shape3d.transparent': true
							});                                    
						}
					}
				});                                                
			}
		}               
	}, false);                                    
	createFormPane();
	createGrid();                                
}                
function createGrid(){
	dm.clear();            
	var ball;
	gridRows.length = 0;
	for(var x = 0; x < m; x++) {
		var nodeRow = [];
		gridRows.push(nodeRow);
		for(var y = 0; y < m; y++) {                                
			var isWall = Math.floor(Math.random()*(1/formPane.v('frequency')));
			if(isWall === 0){
				nodeRow.push(0);
				createNode(x, y).s({
					'batch': 'wall',
					'all.color': '#9CA69D'
				});
			}else{
				nodeRow.push(1);
				ball = createNode(x, y).s({
					'shape3d': 'sphere',  
					'shape3d.color': '#FF703F',
					'3d.visible': false
				});
			}            
		}       
	}
	if(!ball){
		createGrid();
		return;
	}            
	startBall = createNode(ball.a('x'), ball.a('y'), 'start').s({
		'shape3d': 'sphere',  
		'shape3d.color': '#FF703F'                    
	});  

	shape = new ht.Shape();
	shape.setPoints(new ht.List([
		{x: -d, y: d},
		{x: d, y: d},
		{x: d, y: -d},
		{x: -d, y: -d},
		{x: -d, y: d}
	]));
	shape.setThickness(4);
	shape.setTall(w);
	shape.setElevation(w/2);
	shape.setClosePath(true);
	shape.s({
		'all.color': 'rgba(187, 187, 187, 0.8)', 
		'all.transparent': true, 
		'all.reverse.cull': true
	});
	dm.add(shape);                            
}
function createNode(x, y, tag){
	var node = new ht.Node();
	tag = tag || "cell_" + x + "_" + y;               
	node.setTag(tag);            
	node.a({ x: x,  y: y });
	node.s3(w*0.9, w*0.9, w*0.9);
	node.p3(-d+w*x+w/2, w/2, -d+w*y+w/2);
	node.s({
		'all.reverse.cull': true,
		'shape3d.reverse.cull': true
	});
	dm.add(node);
	return node;
}                       
function createFormPane() {           
	formPane = new ht.widget.FormPane();
	formPane.setWidth(230);
	formPane.setHeight(70);
	formPane.getView().className = 'formpane';
	document.body.appendChild(formPane.getView());            
	formPane.addRow(['Wall Frequency', {
		id: 'frequency',
		slider: {
			min: 0,
			max: 0.8,
			value: 0.1,                            
			onValueChanged: function(){
				createGrid();
			}
		}
	}], [100, 0.1]);                               
	formPane.addRow([
		{
			id: 'closest',
			checkBox: {
				label: 'Try Closest'
			}
		},
		{
			id: 'diagonal',
			checkBox: {
				label: 'Allow Diagonal'
			}        
		}
	], [0.1, 0.1]);
}

 只从iOS8支持WebGL后在移动终端上测试3D应用比当前的大部分Android平板舒服多了,以上的例子在iOS系统下呈现和算法都挺流畅,http://v.youku.com/v_show/id_XODMzOTU1Njcy.html,当然这个小例子数据量也不大,本质其实还是2D的最短路径算法,并非真正意义的3D空间最短路径,但还是足够解决很多实际应用问题了。

Screen Shot 2014-11-24 at 5.09.13 PM

<iframe src="http://player.youku.com/embed/XODMzOTU1Njcy" frameborder="0" width="510" height="498"></iframe>

 

2
0
分享到:
评论

相关推荐

    2018-Obstacle_Avoidance_for_Drones_Using_a_3DVFH_Algorithm.pdf

    1. **3D点云到直方图的重投影**:将来自传感器的3D点云数据转换为直方图形式,这有助于减少数据量,同时保留关键的几何信息。 2. **从3D点构建直方图**:根据3D点云构建新的直方图,以反映当前的环境状态,这一步...

    A *Algorithm ppt

    A*算法在 路径搜索中的运用广泛。这里给出了A*算法的算法思想 以及具体流程

    A* algorithm

    This is an implementation for the world-famous algorithm A*. I had commented codes to give users impressions on how this algorithm is implemented in this code. This program will randomly generate a ...

    Topic-sensitive_pagerank_A_context-sensitive_ranking_algorithm_for_web_search

    原始的PageRank算法通过计算一个单一的向量来评估网页的重要性,这一向量基于网页之间的链接结构,而并不考虑具体的查询内容。为了更准确地反映某一特定话题下的页面重要性,本文提出了一种新的方法:计算一组针对...

    a_star_search_algorithm:搜索算法A *(A星)的实现

    A *(星级)搜索算法 搜索算法A *(A Star)的实现(以python语言实现)。 根据视频说明实施: : A *或“星星”是ASP和贪婪的组合。 统一成本订单(按路径成本或后向成本)-g(n)。 目标接近度或远期成本-h(n...

    爬行动物搜索算法 Reptile Search Algorithm RSA 2021

    爬行动物搜索算法 Reptile Search Algorithm RSA 2021 爬行动物搜索算法 Reptile Search Algorithm RSA 2021 爬行动物搜索算法 Reptile Search Algorithm RSA 2021 爬行动物搜索算法 Reptile Search Algorithm ...

    智能优化算法:爬行动物搜索算法Reptile Search Algorithm

    `Reptile Search Algorithm (RSA) A nature-inspired optimizer.pdf` 和 `Reptile Search Algorithm (RSA) A nature-inspired optimizer.zip` 文件可能包含了算法的详细描述和源代码,供研究人员和工程师参考和实践...

    A fast learning algorithm for deep belief nets

    It shows howtouse“complementarypriors”toeliminatetheexplaining- awayeffectsthatmakeinferencedifficultindenselyconnectedbeliefnets that have many hidden layers.

    《A fast learning algorithm for deep belief nets》原文

    《A fast learning algorithm for deep belief nets》是著名科学家Geoffrey Hinton于2006年发表的一篇具有里程碑意义的论文,它在神经网络和深度学习领域开辟了新的研究方向,对现代人工智能的发展产生了深远影响。...

    蜂群算法代码

    Basturk, A powerful and Efficient Algorithm for Numerical Function Optimization: Artificial Bee Colony (ABC) Algorithm, Journal of Global Optimization, Volume:39, Issue:3,pp:459-171, November 2007,...

    A Search Algorithm搜索算法介绍和java实现

    A Search Algorithm搜索算法介绍和java实现 A Search Algorithm是启发式搜索算法,用于在图形或网络中找到最短路径。该算法结合了广度优先搜索和贪婪算法的特点,通过评估每个节点的代价函数来决定下一步的移动。 ...

    A Polynomial-time Algorithm for the Change-Making Problem.pdf

    A Polynomial-time Algorithm for the Change-Making Problem Codeforces #10 E

    折半查找 binarySearch

    A binary search algorithm (or binary chop) is a technique for finding a particular value in a sorted list. It makes progressively better guesses, and closes in on the sought value, by comparing an ...

    AlgorithmVisualizer算法可视化

    这个项目基于JavaScript开发,利用了前端技术实现动态的、交互式的算法展示,特别是对于数据结构和算法的教学与自我提升非常有帮助。下面将详细探讨JavaScript在可视化/图表中的应用以及Algorithm Visualizer的具体...

    A Communication-Efficient Parallel Algorithm for Decision Tree

    基于投票的数据并行则进一步优化数据并行中的通信代价,使通信代价变成常数级别。在数据量很大的时候,使用...更具体的内容可以看NIPS2016的文章[A Communication-Efficient Parallel Algorithm for Decision Tree]。

    Sparrow Search algorithm (SSA).zip

    从麻雀的群体智慧、觅食行为和反捕食行为出发,提出了一种新的群体优化算法——麻雀搜索算法。在19个基准函数上进行了实验,测试了SSA算法的性能,并与其他算法如灰狼优化算法(GWO)、引力搜索算法(GSA)和粒子群...

    A fast learning algorithm for deep belief nets.rar

    本资源“A fast learning algorithm for deep belief nets”很可能详细介绍了优化DBN学习速率和提高训练效率的方法。 深度信念网络的核心是层次化的概率模型,通常由多个受限玻尔兹曼机(Restricted Boltzmann ...

    Grid Search Algorithm

    Grid search is a widely used algorithm in machine learning, which to use a brute-force approach to find optimal parameters. The code gives an example to use grid search to find optimal parameters of a...

    Python狼群搜索算法(Wolf Pack Search Algorithm)优化示例代码

    # Python狼群搜索算法(Wolf Pack Search Algorithm)优化示例代码 本项目演示了如何使用狼群搜索算法(Wolf Pack Search Algorithm)来优化函数,并绘制优化过程中的收敛曲线。狼群搜索算法(WPS)是一种基于群体...

    引力搜索算法Gravitational Search Algorithm

    This is the 'Gravitational Search Algorithm' Mathlab code for minimizing 23 benchmark functions. from the author

Global site tag (gtag.js) - Google Analytics