三维地形生成的相关代码matlab
1 function terrain() 2 n=9;%递归次数 3 H=2;%设置初始正方形四顶点值 4 t=0.2;%控制地貌形态 5 delta=0.01;%初始随机位移偏移量,控制地貌形态 6 size=2^n+1; 7 S=zeros(size,size);%设置size*size的初始方阵 8 S(1,1)=H+sqrt(1-2^(2*t-2))*normrnd(0,1)*delta;%赋初始高度值 9 S(1,size)=H+sqrt(1-2^(2*t-2))*normrnd(0,1)*delta; 10 S(size,1)=H+sqrt(1-2^(2*t-2))*normrnd(0,1)*delta; 11 S(size,size)=H+sqrt(1-2^(2*t-2))*normrnd(0,1)*delta; 12 x1=1; 13 y1=1; 14 x2=size; 15 y2=size; 16 depth=0; 17 S=fractal(S,x1,y1,x2,y2,depth,t,delta);%调用子函数,传递参数 18 x=1:size; 19 y=1:size; 20 [X,Y]=meshgrid(x,y); 21 hidden off; 22 surf(X,Y,S); 23 Smin=min(min(S)); 24 Smax=max(max(S)); 25 axis([0 size 0 size Smin Smax]); 26 grid off; 27 %box off 28 colormap(gray); 29 shading interp; 30 %material default; 31 32 33 function S=fractal(S,x1,y1,x2,y2,depth,t,delta)%子函数调用,返回矩阵S 34 if round((x2+x1)/2)==(x2+x1)/2 35 S((x1+x2)/2,(y2+y1)/2)=(S(x1,y1)+S(x1,y2)+S(x2,y1)+S(x2,y2))/4+2^(-depth*t)*sqrt(1-2^(2*t-2))*normrnd(0,1)*delta; 36 S((x1+x2)/2,y1)=(S(x1,y1)+S(x1,y2))/2+2^(-depth*t)*sqrt(1-2^(2*t-2))*normrnd(0,1)*delta; 37 S(x1,(y2+y1)/2)=(S(x1,y1)+S(x2,y2))/2+2^(-depth*t)*sqrt(1-2^(2*t-2))*normrnd(0,1)*delta; 38 S((x1+x2)/2,y2)=(S(x2,y1)+S(x2,y2))/2+2^(-depth*t)*sqrt(1-2^(2*t-2))*normrnd(0,1)*delta; 39 S(x2,(y2+y1)/2)=(S(x1,y2)+S(x2,y1))/2+2^(-depth*t)*sqrt(1-2^(2*t-2))*normrnd(0,1)*delta; 40 depth=depth+1; 41 S=fractal(S,x1,y1,(x1+x2)/2,(y2+y1)/2,depth,t,delta);%连续四次递归,分别计算上下左右四个正方形的高度,至今还不是很明白它的详细计算过程和规律,如有高手,请赐教 42 S=fractal(S,(x1+x2)/2,y1,x2,(y2+y1)/2,depth,t,delta); 43 S=fractal(S,(x1+x2)/2,(y2+y1)/2,x2,y2,depth,t,delta); 44 S=fractal(S,x1,(y2+y1)/2,(x1+x2)/2,y2,depth,t,delta); 45 end
原文地址:https://www.cnblogs.com/wylwyl/p/10267083.html
时间: 2024-10-13 17:49:55