初次提交

This commit is contained in:
2022-09-19 18:05:01 +08:00
commit 57051fc44b
5401 changed files with 325410 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Sample8_6</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,12 @@
#Thu Nov 17 19:08:48 CST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bn.Sample8_6"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MyActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,12 @@
precision mediump float;
varying vec4 vaaColor; //接收从顶点着色器过来的参数
varying vec4 vambient;
varying vec4 vdiffuse;
varying vec4 vspecular;
void main()
{
//将颜色给此片元
vec4 finalColor = vaaColor;
//给此片元颜色值
gl_FragColor = finalColor*vambient+finalColor*vspecular+finalColor*vdiffuse;//给此片元颜色值
}

View File

@@ -0,0 +1,48 @@
uniform mat4 uMVPMatrix; //总变换矩阵
uniform mat4 uMMatrix; //变换矩阵
uniform vec3 uLightLocation; //光源位置
uniform vec3 uCamera; //摄像机位置
attribute vec3 aPosition; //顶点位置
attribute vec3 aNormal; //顶点法向量
attribute vec4 aColor; //顶点颜色
varying vec4 vaaColor; //用于传递给片元着色器的变量
varying vec4 vambient;
varying vec4 vdiffuse;
varying vec4 vspecular;
//定位光光照计算的方法
void pointLight( //定位光光照计算的方法
in vec3 normal, //法向量
inout vec4 ambient, //环境光最终强度
inout vec4 diffuse, //散射光最终强度
inout vec4 specular, //镜面光最终强度
in vec3 lightLocation, //光源位置
in vec4 lightAmbient, //环境光强度
in vec4 lightDiffuse, //散射光强度
in vec4 lightSpecular //镜面光强度
){
ambient=lightAmbient; //直接得出环境光的最终强度
vec3 normalTarget=aPosition+normal; //计算变换后的法向量
vec3 newNormal=(uMMatrix*vec4(normalTarget,1)).xyz-(uMMatrix*vec4(aPosition,1)).xyz;
newNormal=normalize(newNormal); //对法向量规格化
//计算从表面点到摄像机的向量
vec3 eye= normalize(uCamera-(uMMatrix*vec4(aPosition,1)).xyz);
//计算从表面点到光源位置的向量vp
vec3 vp= normalize(lightLocation-(uMMatrix*vec4(aPosition,1)).xyz);
vp=normalize(vp);//格式化vp
vec3 halfVector=normalize(vp+eye); //求视线与光线的半向量
float shininess=50.0; //粗糙度,越小越光滑
float nDotViewPosition=max(0.0,dot(newNormal,vp)); //求法向量与vp的点积与0的最大值
diffuse=lightDiffuse*nDotViewPosition; //计算散射光的最终强度
float nDotViewHalfVector=dot(newNormal,halfVector); //法线与半向量的点积
float powerFactor=max(0.0,pow(nDotViewHalfVector,shininess)); //镜面反射光强度因子
specular=lightSpecular*powerFactor; //计算镜面光的最终强度
}
void main()
{
gl_Position = uMVPMatrix * vec4(aPosition,1); //根据总变换矩阵计算此次绘制此顶点位置
pointLight(normalize(aNormal),vambient,vdiffuse,vspecular,uLightLocation,vec4(0.3,0.3,0.3,1.0),vec4(0.7,0.7,0.7,1.0),vec4(0.3,0.3,0.3,1.0));
vaaColor = aColor;//将接收的颜色传递给片元着色器
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-8

View File

@@ -0,0 +1,20 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bn.Sample8_6;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class string {
public static final int app_name=0x7f030001;
public static final int hello=0x7f030000;
}
}

View File

@@ -0,0 +1,40 @@
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Sample9_1Activity!</string>
<string name="app_name">Sample8_6</string>
</resources>

View File

@@ -0,0 +1,212 @@
package com.bn.Sample8_6;
import static com.bn.Sample8_6.ShaderUtil.createProgram;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import android.opengl.GLES20;
/*
* 球体
*/
public class Ball
{
int mProgram;//自定义渲染管线着色器程序id
int muMVPMatrixHandle;//总变换矩阵引用
int maPositionHandle; //顶点位置属性引用
int maColorHandle; //顶点颜色属性引用
int muMMatrixHandle;
int maCameraHandle; //摄像机位置属性引用
int maNormalHandle; //顶点法向量属性引用
int maLightLocationHandle;//光源位置属性引用
String mVertexShader;//顶点着色器
String mFragmentShader;//片元着色器
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mColorBuffer; //顶点颜色数据缓冲
FloatBuffer mNormalBuffer;//顶点法向量数据缓冲
int vCount=0;
float xAngle=0;//绕x轴旋转的角度
float yAngle=0;//绕y轴旋转的角度
float zAngle=0;//绕z轴旋转的角度
float bHalf=0;//黄金长方形的宽
float r=0;//球的半径
public Ball(MySurfaceView mv,float r,float[] colorValue)
{
//调用初始化顶点数据的initVertexData方法
initVertexData(r,colorValue);
//调用初始化着色器的intShader方法
initShader(mv);
}
//自定义的初始化顶点数据的方法
public void initVertexData(float r,float[] colorValue)
{
//顶点坐标数据的初始化================begin============================
final float UNIT_SIZE=0.4f;
ArrayList<Float> alVertix=new ArrayList<Float>();//存放顶点坐标的ArrayList
final float angleSpan=15f;//将球进行单位切分的角度
for(float vAngle=-90;vAngle<90;vAngle=vAngle+angleSpan)//垂直方向angleSpan度一份
{
for(float hAngle=0;hAngle<=360;hAngle=hAngle+angleSpan)//水平方向angleSpan度一份
{//纵向横向各到一个角度后计算对应的此点在球面上的坐标
float x0=(float)(r*UNIT_SIZE*Math.cos(Math.toRadians(vAngle))*Math.cos(Math.toRadians(hAngle)));
float y0=(float)(r*UNIT_SIZE*Math.cos(Math.toRadians(vAngle))*Math.sin(Math.toRadians(hAngle)));
float z0=(float)(r*UNIT_SIZE*Math.sin(Math.toRadians(vAngle)));
float x1=(float)(r*UNIT_SIZE*Math.cos(Math.toRadians(vAngle))*Math.cos(Math.toRadians(hAngle+angleSpan)));
float y1=(float)(r*UNIT_SIZE*Math.cos(Math.toRadians(vAngle))*Math.sin(Math.toRadians(hAngle+angleSpan)));
float z1=(float)(r*UNIT_SIZE*Math.sin(Math.toRadians(vAngle)));
float x2=(float)(r*UNIT_SIZE*Math.cos(Math.toRadians(vAngle+angleSpan))*Math.cos(Math.toRadians(hAngle+angleSpan)));
float y2=(float)(r*UNIT_SIZE*Math.cos(Math.toRadians(vAngle+angleSpan))*Math.sin(Math.toRadians(hAngle+angleSpan)));
float z2=(float)(r*UNIT_SIZE*Math.sin(Math.toRadians(vAngle+angleSpan)));
float x3=(float)(r*UNIT_SIZE*Math.cos(Math.toRadians(vAngle+angleSpan))*Math.cos(Math.toRadians(hAngle)));
float y3=(float)(r*UNIT_SIZE*Math.cos(Math.toRadians(vAngle+angleSpan))*Math.sin(Math.toRadians(hAngle)));
float z3=(float)(r*UNIT_SIZE*Math.sin(Math.toRadians(vAngle+angleSpan)));
//将计算出来的XYZ坐标加入存放顶点坐标的ArrayList
alVertix.add(x1);alVertix.add(y1);alVertix.add(z1);
alVertix.add(x3);alVertix.add(y3);alVertix.add(z3);
alVertix.add(x0);alVertix.add(y0);alVertix.add(z0);
alVertix.add(x1);alVertix.add(y1);alVertix.add(z1);
alVertix.add(x2);alVertix.add(y2);alVertix.add(z2);
alVertix.add(x3);alVertix.add(y3);alVertix.add(z3);
}
}
vCount=alVertix.size()/3;//顶点的数量为坐标值数量的1/3因为一个顶点有3个坐标
//将alVertix中的坐标值转存到一个float数组中
float vertices[]=new float[vCount*3];
for(int i=0;i<alVertix.size();i++)
{
vertices[i]=alVertix.get(i);
}
//创建顶点坐标数据缓冲
//vertices.length*4是因为一个整数四个字节
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为int型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
//顶点颜色数据的初始化
float colors[]=new float[vCount*4];
for(int i=0;i<vCount;i++){
colors[4*i]=colorValue[0];
colors[4*i+1]=colorValue[1];
colors[4*i+2]=colorValue[2];
colors[4*i+3]=colorValue[3];
}
/*
* 在指定颜色时,发生了顶点颜色融合
*/
//创建顶点着色数据缓冲
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
cbb.order(ByteOrder.nativeOrder());//设置字节顺序
mColorBuffer = cbb.asFloatBuffer();//转换为Float型缓冲
mColorBuffer.put(colors);//向缓冲区中放入顶点着色数据
mColorBuffer.position(0);//设置缓冲区起始位置
}
//初始化着色器
public void initShader(MySurfaceView mv)
{
//加载顶点着色器的脚本内容
mVertexShader=ShaderUtil.loadFromAssetsFile("vertex_color_light.sh", mv.getResources());
//加载片元着色器的脚本内容
mFragmentShader=ShaderUtil.loadFromAssetsFile("frag_color_light.sh", mv.getResources());
//基于顶点着色器与片元着色器创建程序
mProgram = createProgram(mVertexShader, mFragmentShader);
//获取程序中顶点位置属性引用id
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点颜色属性引用id
maColorHandle= GLES20.glGetAttribLocation(mProgram, "aColor");
//获取程序中总变换矩阵引用id
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
//获取程序中顶点法向量属性引用id
maNormalHandle= GLES20.glGetAttribLocation(mProgram, "aNormal");
//获取程序中摄像机位置引用id
maCameraHandle=GLES20.glGetUniformLocation(mProgram, "uCamera");
//获取程序中光源位置引用id
maLightLocationHandle=GLES20.glGetUniformLocation(mProgram, "uLightLocation");
//获取位置、旋转变换矩阵引用id
muMMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMMatrix");
}
public void drawSelf()
{
MatrixState.rotate(xAngle, 1, 0, 0);
MatrixState.rotate(yAngle, 0, 1, 0);
MatrixState.rotate(zAngle, 0, 0, 1);
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将位置、旋转变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMMatrixHandle, 1, false, MatrixState.getMMatrix(), 0);
//将摄像机位置传入shader程序
GLES20.glUniform3fv(maCameraHandle, 1, MatrixState.cameraFB);
//将光源位置传入shader程序
GLES20.glUniform3fv(maLightLocationHandle, 1, MatrixState.lightPositionFB);
//传送顶点位置数据
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//传送顶点颜色数据
GLES20.glVertexAttribPointer
(
maColorHandle,
4,
GLES20.GL_FLOAT,
false,
4*4,
mColorBuffer
);
//传送顶点法向量数据
GLES20.glVertexAttribPointer
(
maNormalHandle,
4,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//启用顶点位置数据
GLES20.glEnableVertexAttribArray(maPositionHandle);
//启用顶点颜色数据
GLES20.glEnableVertexAttribArray(maColorHandle);
//启用顶点法向量数据
GLES20.glEnableVertexAttribArray(maNormalHandle);
//绘制线条的粗细
GLES20.glLineWidth(2);
//绘制
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
}
}

View File

@@ -0,0 +1,13 @@
package com.bn.Sample8_6;
public class Constant
{
//边长
public static final float LENGTH = 0.8f;
//球半径
public static final float BALL_R=0.5f;
//圆柱半径
public static final float R=0.05f;
//切分角度
public static final float ANGLE_SPAN=18;
}

View File

@@ -0,0 +1,182 @@
package com.bn.Sample8_6;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import android.opengl.Matrix;
//存储系统矩阵状态的类
public class MatrixState
{
private static float[] mProjMatrix = new float[16];//4x4矩阵 投影用
private static float[] mVMatrix = new float[16];//摄像机位置朝向9参数矩阵
private static float[] currMatrix;//当前变换矩阵
public static float[] lightLocation=new float[]{0,0,0};//定位光光源位置
public static FloatBuffer cameraFB;
public static FloatBuffer lightPositionFB;
//保护变换矩阵的栈
static float[][] mStack=new float[10][16];
static int stackTop=-1;
public static void setInitStack()//获取不变换初始矩阵
{
currMatrix=new float[36];
Matrix.setRotateM(currMatrix, 0, 0, 1, 0, 0);
}
public static void pushMatrix()//保护变换矩阵
{
stackTop++;
for(int i=0;i<16;i++)
{
mStack[stackTop][i]=currMatrix[i];
}
}
public static void popMatrix()//恢复变换矩阵
{
for(int i=0;i<16;i++)
{
currMatrix[i]=mStack[stackTop][i];
}
stackTop--;
}
public static void translate(float x,float y,float z)//设置沿xyz轴移动
{
Matrix.translateM(currMatrix, 0, x, y, z);
}
public static void rotate(float angle,float x,float y,float z)//设置绕xyz轴移动
{
Matrix.rotateM(currMatrix,0,angle,x,y,z);
}
public static void scale(float x,float y,float z)
{
Matrix.scaleM(currMatrix,0, x, y, z);
}
//插入自带矩阵
public static void matrix(float[] self)
{
float[] result=new float[16];
Matrix.multiplyMM(result,0,currMatrix,0,self,0);
currMatrix=result;
}
//设置摄像机
static ByteBuffer llbb= ByteBuffer.allocateDirect(3*4);
static float[] cameraLocation=new float[3];//摄像机位置
public static void setCamera
(
float cx, //摄像机位置x
float cy, //摄像机位置y
float cz, //摄像机位置z
float tx, //摄像机目标点x
float ty, //摄像机目标点y
float tz, //摄像机目标点z
float upx, //摄像机UP向量X分量
float upy, //摄像机UP向量Y分量
float upz //摄像机UP向量Z分量
)
{
Matrix.setLookAtM
(
mVMatrix,
0,
cx,
cy,
cz,
tx,
ty,
tz,
upx,
upy,
upz
);
cameraLocation[0]=cx;
cameraLocation[1]=cy;
cameraLocation[2]=cz;
llbb.clear();
llbb.order(ByteOrder.nativeOrder());//设置字节顺序
cameraFB=llbb.asFloatBuffer();
cameraFB.put(cameraLocation);
cameraFB.position(0);
}
//设置透视投影参数
public static void setProjectFrustum
(
float left, //near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near, //near面距离
float far //far面距离
)
{
Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//设置正交投影参数
public static void setProjectOrtho
(
float left, //near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near, //near面距离
float far //far面距离
)
{
Matrix.orthoM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//获取具体物体的总变换矩阵
static float[] mMVPMatrix=new float[16];
public static float[] getFinalMatrix()
{
Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, currMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
return mMVPMatrix;
}
//获取具体物体的变换矩阵
public static float[] getMMatrix()
{
return currMatrix;
}
//获取投影矩阵
public static float[] getProjMatrix()
{
return mProjMatrix;
}
//获取摄像机朝向的矩阵
public static float[] getCaMatrix()
{
return mVMatrix;
}
//设置灯光位置的方法
static ByteBuffer llbbL = ByteBuffer.allocateDirect(3*4);
public static void setLightLocation(float x,float y,float z)
{
llbbL.clear();
lightLocation[0]=x;
lightLocation[1]=y;
lightLocation[2]=z;
llbbL.order(ByteOrder.nativeOrder());//设置字节顺序
lightPositionFB=llbbL.asFloatBuffer();
lightPositionFB.put(lightLocation);
lightPositionFB.position(0);
}
}

View File

@@ -0,0 +1,52 @@
package com.bn.Sample8_6;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
public class MyActivity extends Activity {
MySurfaceView mySurfaceView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置为全屏
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//设置为横屏模式
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//初始化GLSurfaceView
mySurfaceView = new MySurfaceView(this);
mySurfaceView.requestFocus();//获取焦点
mySurfaceView.setFocusableInTouchMode(true);//设置为可触控
//切换到主界面
setContentView(mySurfaceView);
}
@Override
protected void onResume() {
super.onResume();
mySurfaceView.onResume();
mySurfaceView.lightFlag=true;
}
@Override
protected void onPause() {
super.onPause();
mySurfaceView.onPause();
mySurfaceView.lightFlag=false;
}
public boolean onKeyDown(int keyCode,KeyEvent e)
{
switch(keyCode)
{
case 4:
System.exit(0);
break;
}
return true;
};
}

View File

@@ -0,0 +1,164 @@
package com.bn.Sample8_6;
import android.opengl.GLSurfaceView;
import android.opengl.GLES20;
import android.view.MotionEvent;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
class MySurfaceView extends GLSurfaceView {
private final float TOUCH_SCALE_FACTOR = 180.0f/320;//角度缩放比例
private float mPreviousY;//上次的触控位置Y坐标
private float mPreviousX;//上次的触控位置X坐标
private SceneRenderer mRenderer;//场景渲染器
boolean lightFlag=true; //光照旋转的标志位
float yAngle=0;//绕y轴旋转的角度
float xAngle=0;//绕x轴旋转的角度
float zAngle=0;//绕z轴旋转的角度
Ball ball;
Stick stick;
public MySurfaceView(Context context) {
super(context);
this.setEGLContextClientVersion(2); //设置使用OPENGL ES2.0
mRenderer = new SceneRenderer(); //创建场景渲染器
setRenderer(mRenderer); //设置渲染器
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);//设置渲染模式为主动渲染
}
//触摸事件回调方法
@Override
public boolean onTouchEvent(MotionEvent e) {
float y = e.getY();
float x = e.getX();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
float dy = y - mPreviousY;//计算触控笔Y位移
float dx = x - mPreviousX;//计算触控笔X位移
yAngle += dx * TOUCH_SCALE_FACTOR;//设置绕y轴旋转角度
zAngle+= dy * TOUCH_SCALE_FACTOR;//设置绕z轴旋转角度
}
mPreviousY = y;//记录触控笔位置
mPreviousX = x;//记录触控笔位置
return true;
}
private class SceneRenderer implements GLSurfaceView.Renderer
{
RegularPolygon first;
public void onDrawFrame(GL10 gl)
{
//清除深度缓冲与颜色缓冲
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
MatrixState.pushMatrix();
MatrixState.translate(0, 0, -6f);
MatrixState.pushMatrix();
MatrixState.rotate(xAngle, 1, 0, 0);
MatrixState.rotate(yAngle, 0, 1, 0);
MatrixState.rotate(zAngle, 0, 0, 1);
for(int i=0;i<5;i++){ //五部分循环
MatrixState.pushMatrix();
MatrixState.rotate(72*i,0,0,1); //根据绘制的为第几部分旋转72*i度
first.drawSelf(0, 0); //绘制足球碳的五分之一部分,最后的五边形由五部分组合形成,所以不用绘制
MatrixState.popMatrix();
}
MatrixState.popMatrix();
MatrixState.popMatrix();
Utils.drawnVertices.clear();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
//设置视窗大小及位置
GLES20.glViewport(0, 0, width, height);
//计算GLSurfaceView的宽高比
float ratio= (float) width / height;
//调用此方法计算产生透视投影矩阵
MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 4f, 100);
//调用此方法产生摄像机9参数位置矩阵
MatrixState.setCamera(0,0,8.0f,0f,0f,0f,0f,1.0f,0.0f);
//初始化光源
MatrixState.setLightLocation(10 , 0 , -10);
//启动一个线程定时修改灯光的位置
new Thread()
{
public void run()
{
float redAngle = 0;
while(lightFlag)
{
//根据角度计算灯光的位置
redAngle=(redAngle+5)%360;
float rx=(float) (15*Math.sin(Math.toRadians(redAngle)));
float rz=(float) (15*Math.cos(Math.toRadians(redAngle)));
MatrixState.setLightLocation(rx, 0, rz);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//设置屏幕背景色RGBA
GLES20.glClearColor(0.9f,0.9f,0.9f, 1.0f);
//启用深度测试
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
//设置为打开背面剪裁
GLES20.glEnable(GLES20.GL_CULL_FACE);
//初始化变换矩阵
MatrixState.setInitStack();
float[] colorValue = {1,0,0,1}; //创建颜色数组
ball = new Ball(MySurfaceView.this,Constant.BALL_R,colorValue);//创建球对象
colorValue = new float[]{1,1,0,1};
stick = new Stick(MySurfaceView.this,Constant.LENGTH,Constant.R,Constant.ANGLE_SPAN,colorValue);//创建圆管对象
double[] initPoint = Utils.getFirstPoint(Constant.LENGTH);//得到第一个五边形左下点的坐标
double[] initVector={1,0,0,1}; //初始化方向向量
double[] zPivot = {0,0,1,1}; //以z轴为旋转轴
int[] vertices = {0,1,2,3,4}; //球的索引
int[] borders = {0,1,2,3,4}; //圆管的索引
first = new RegularPolygon(MySurfaceView.this, 5,72 ,
Constant.LENGTH, initPoint, initVector,zPivot,vertices,borders);//1
vertices = new int[]{2,3,4}; //球的索引
borders = new int[]{1,2,3,4}; //圆管的索引
RegularPolygon rp2 = first.buildChild( 6, -60,1,vertices,borders);//2
vertices = new int[]{2,3,4,5};
borders = new int[]{1,2,3,4,5};
RegularPolygon rp4 = rp2.buildChild( 6, 60,3,vertices,borders);//4
vertices = new int[]{};
borders = new int[]{1,5};
rp4.buildChild( 6, -60,2,vertices,borders);//5
vertices = new int[]{2};
borders = new int[]{1,2};
RegularPolygon rp6 = rp4.buildChild( 5, -72,3,vertices,borders);//6
vertices = new int[]{3,4,5};
borders = new int[]{2,3,4,5};
rp6.buildChild( 6, 60,2,vertices,borders);//7
}
}
}

View File

@@ -0,0 +1,113 @@
package com.bn.Sample8_6;
import java.util.ArrayList;
import java.util.List;
public class RegularPolygon {
int vCount=0;
int iCount=0;
float length;
int borderCount;
List<Float> verticesList;//多边形的顶点数据
double[][] vectors;//每条便的方向向量,每条边的起点的索引与该边方向向量的索引一致
double[] initVector;//保存初始的方向向量
double[] pivot;//旋转轴
int[] vertices;//记录要绘制的球的索引
int[] borders;//记录要绘制的圆管的索引
List<RegularPolygon> children;
MySurfaceView mv;
public RegularPolygon(MySurfaceView mv,
int borderCount, //圆管的编号
double angle, //旋转的角度
float length, //长度
double[] initPoint, //初始的点
double[] initVector,//初始向量
double[] pivot, //旋转轴
int[] vertices, //绘制球的索引
int[] borders //绘制圆管的索引
){
this.mv=mv;
this.borderCount=borderCount;
this.length=length;
this.vectors = new double[borderCount][3];
this.initVector=initVector;
this.vertices=vertices;
this.borders=borders;
this.pivot = pivot;//父对象的旋转轴,本对象的旋转轴在父对象的旋转轴的基础上旋转得到
children = new ArrayList<RegularPolygon>();
this.verticesList = Utils.getRegularPentagonVertexData(
initPoint, initVector, length,angle,vectors,borderCount,pivot);
}
public void drawSelf(float xOffset,float yOffset)
{
//绘制顶点
for(int i=0;i<vertices.length;i++){
int index = vertices[i];
float x = verticesList.get(3*index);
float y = verticesList.get(3*index+1);
float z = verticesList.get(3*index+2);
MatrixState.pushMatrix();
//移动到顶点的位置,绘制球
MatrixState.translate(x, y, z);
mv.ball.drawSelf();
MatrixState.popMatrix();
}
//绘制圆管
for(int i=0;i<borders.length;i++){
int index = borders[i];
//获取圆管的起点坐标
float x = verticesList.get(3*index);
float y = verticesList.get(3*index+1);
float z = verticesList.get(3*index+2);
//获取圆管的向量
double[] vector = vectors[index];
MatrixState.pushMatrix();
//首先移动到起点
MatrixState.translate(x, y, z);
MatrixState.pushMatrix();
Utils.moveXToSomeVector(vector); //x轴变换到指定向量的坐标系
MatrixState.translate(Constant.LENGTH/2, 0, 0);
mv.stick.drawSelf(); //绘制木棒
MatrixState.popMatrix();
MatrixState.popMatrix();
}
drawChildren( xOffset, yOffset); //绘制
}
public RegularPolygon buildChild(
int borderCount, //圆管的数量
double angle, //旋转角度
int position,
int[] vertices, //球索引
int[] borders //圆管索引
){
double[] initPoint = new double[3];
for(int i=0;i<3;i++){
initPoint[i]=verticesList.get(3*position+i);
}
double[] initVector = vectors[position];
double[] tempPivot = Utils.copyVecor(this.pivot);
RegularPolygon child = new RegularPolygon(this.mv,
borderCount, angle, length, initPoint, initVector,tempPivot,vertices,borders);
children.add(child);
return child;
}
private void drawChildren(float xOffset,float yOffset){
for(int i=0;i<children.size();i++){
RegularPolygon child = children.get(i);
MatrixState.pushMatrix();
child.drawSelf(xOffset, yOffset);
MatrixState.popMatrix();
}
}
}

View File

@@ -0,0 +1,126 @@
package com.bn.Sample8_6;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import android.content.res.Resources;
import android.opengl.GLES20;
import android.util.Log;
//加载顶点Shader与片元Shader的工具类
public class ShaderUtil
{
//加载制定shader的方法
public static int loadShader
(
int shaderType, //shader的类型 GLES20.GL_VERTEX_SHADER GLES20.GL_FRAGMENT_SHADER
String source //shader的脚本字符串
)
{
//创建一个新shader
int shader = GLES20.glCreateShader(shaderType);
//若创建成功则加载shader
if (shader != 0)
{
//加载shader的源代码
GLES20.glShaderSource(shader, source);
//编译shader
GLES20.glCompileShader(shader);
//存放编译成功shader数量的数组
int[] compiled = new int[1];
//获取Shader的编译情况
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0)
{//若编译失败则显示错误日志并删除此shader
Log.e("ES20_ERROR", "Could not compile shader " + shaderType + ":");
Log.e("ES20_ERROR", GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
//创建shader程序的方法
public static int createProgram(String vertexSource, String fragmentSource)
{
//加载顶点着色器
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0)
{
return 0;
}
//加载片元着色器
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0)
{
return 0;
}
//创建程序
int program = GLES20.glCreateProgram();
//若程序创建成功则向程序中加入顶点着色器与片元着色器
if (program != 0)
{
//向程序中加入顶点着色器
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
//向程序中加入片元着色器
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
//链接程序
GLES20.glLinkProgram(program);
//存放链接成功program数量的数组
int[] linkStatus = new int[1];
//获取program的链接情况
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
//若链接失败则报错并删除程序
if (linkStatus[0] != GLES20.GL_TRUE)
{
Log.e("ES20_ERROR", "Could not link program: ");
Log.e("ES20_ERROR", GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
}
return program;
}
//检查每一步操作是否有错误的方法
public static void checkGlError(String op)
{
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR)
{
Log.e("ES20_ERROR", op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
//从sh脚本中加载shader内容的方法
public static String loadFromAssetsFile(String fname,Resources r)
{
String result=null;
try
{
InputStream in=r.getAssets().open(fname);
int ch=0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((ch=in.read())!=-1)
{
baos.write(ch);
}
byte[] buff=baos.toByteArray();
baos.close();
in.close();
result=new String(buff,"UTF-8");
result=result.replaceAll("\\r\\n","\n");
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
}

View File

@@ -0,0 +1,271 @@
package com.bn.Sample8_6;
import static com.bn.Sample8_6.ShaderUtil.createProgram;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import android.opengl.GLES20;
/*
* 连接两个球之间的圆柱
*/
public class Stick
{
int mProgram;//自定义渲染管线着色器程序id
int muMVPMatrixHandle;//总变换矩阵引用
int maPositionHandle; //顶点位置属性引用
int maColorHandle; //顶点颜色属性引用
int muMMatrixHandle;
int maCameraHandle; //摄像机位置属性引用
int maNormalHandle; //顶点法向量属性引用
int maLightLocationHandle;//光源位置属性引用
String mVertexShader;//顶点着色器
String mFragmentShader;//片元着色器
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mColorBuffer; //顶点颜色数据缓冲
FloatBuffer mNormalBuffer;//顶点法向量数据缓冲
int vCount=0;
float xAngle=0;//绕x轴旋转的角度
float yAngle=0;//绕y轴旋转的角度
float zAngle=0;//绕z轴旋转的角度
float length=10f;//圆柱长度
float circle_radius=2f;//圆截环半径
float degreespan=18f; //圆截环每一份的度数大小
public Stick(MySurfaceView mv,float length,float circle_radius,float degreespan,float[] colorValue)
{
//调用初始化顶点数据的initVertexData方法
initVertexData( length, circle_radius, degreespan,colorValue);
//调用初始化着色器的intShader方法
initShader(mv);
}
//自定义的初始化顶点数据的方法
public void initVertexData(float length,float circle_radius,float degreespan,float[] colorValue)
{
//顶点坐标数据的初始化
ArrayList<Float> val=new ArrayList<Float>();//顶点存放列表
ArrayList<Float> ial=new ArrayList<Float>();//法向量存放列表
this.length = length;
this.circle_radius = circle_radius;
this.degreespan = degreespan;
for(float circle_degree=360.0f;circle_degree>0.0f;circle_degree-=degreespan)//循环行
{
float x1 =(float)(-length/2);
float y1=(float) (circle_radius*Math.sin(Math.toRadians(circle_degree)));
float z1=(float) (circle_radius*Math.cos(Math.toRadians(circle_degree)));
float a1=0;
float b1=y1;
float c1=z1;
//向量规格化
float[] result=Utils.normalizeVector(a1,b1,c1);
a1=result[0];
b1=result[1];
c1=result[2];
float x2 =(float)(-length/2);
float y2=(float) (circle_radius*Math.sin(Math.toRadians(circle_degree-degreespan)));
float z2=(float) (circle_radius*Math.cos(Math.toRadians(circle_degree-degreespan)));
float a2=0;
float b2=y2;
float c2=z2;
//向量规格化
result=Utils.normalizeVector(a2,b2,c2);
a2=result[0];
b2=result[1];
c2=result[2];
float x3 =(float)(length/2);
float y3=(float) (circle_radius*Math.sin(Math.toRadians(circle_degree-degreespan)));
float z3=(float) (circle_radius*Math.cos(Math.toRadians(circle_degree-degreespan)));
float a3=0;
float b3=y3;
float c3=z3;
//向量规格化
result=Utils.normalizeVector(a3,b3,c3);
a3=result[0];
b3=result[1];
c3=result[2];
float x4 =(float)(length/2);
float y4=(float) (circle_radius*Math.sin(Math.toRadians(circle_degree)));
float z4=(float) (circle_radius*Math.cos(Math.toRadians(circle_degree)));
float a4=0;
float b4=y4;
float c4=z4;
//向量规格化
result=Utils.normalizeVector(a4,b4,c4);
a4=result[0];
b4=result[1];
c4=result[2];
val.add(x1);val.add(y1);val.add(z1);//两个三角形共6个顶点的坐标
val.add(x2);val.add(y2);val.add(z2);
val.add(x4);val.add(y4);val.add(z4);
val.add(x2);val.add(y2);val.add(z2);
val.add(x3);val.add(y3);val.add(z3);
val.add(x4);val.add(y4);val.add(z4);
ial.add(a1);ial.add(b1);ial.add(c1);//顶点对应的法向量
ial.add(a2);ial.add(b2);ial.add(c2);
ial.add(a4);ial.add(b4);ial.add(c4);
ial.add(a2);ial.add(b2);ial.add(c2);
ial.add(a3);ial.add(b3);ial.add(c3);
ial.add(a4);ial.add(b4);ial.add(c4);
}
vCount=val.size()/3;//顶点的数量为坐标值数量的1/3因为一个顶点有3个坐标
//将alVertix中的坐标值转存到一个float数组中
float vertices[]=new float[vCount*3];
for(int i=0;i<val.size();i++)
{
vertices[i]=val.get(i);
}
//创建顶点坐标数据缓冲
//vertices.length*4是因为一个整数四个字节
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为int型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
//特别提示由于不同平台字节顺序不同数据单元不是字节的一定要经过ByteBuffer
//转换关键是要通过ByteOrder设置nativeOrder(),否则有可能会出问题
//将alVertix中的坐标值转存到一个float数组中
float normals[]=new float[ial.size()];
for(int i=0;i<ial.size();i++)
{
normals[i]=ial.get(i);
}
//创建顶点坐标数据缓冲
//vertices.length*4是因为一个整数四个字节
ByteBuffer nbb = ByteBuffer.allocateDirect(normals.length*4);
nbb.order(ByteOrder.nativeOrder());//设置字节顺序
mNormalBuffer = nbb.asFloatBuffer();//转换为int型缓冲
mNormalBuffer.put(normals);//向缓冲区中放入顶点坐标数据
mNormalBuffer.position(0);//设置缓冲区起始位置
//顶点着色数据的初始化
float colors[]=new float[vCount*4];
for(int i=0;i<vCount;i++){
colors[4*i]=colorValue[0];
colors[4*i+1]=colorValue[1];
colors[4*i+2]=colorValue[2];
colors[4*i+3]=colorValue[3];
}
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
cbb.order(ByteOrder.nativeOrder());//设置字节顺序
mColorBuffer = cbb.asFloatBuffer();//转换为Float型缓冲
mColorBuffer.put(colors);//向缓冲区中放入顶点着色数据
mColorBuffer.position(0);//设置缓冲区起始位置
}
//初始化着色器
public void initShader(MySurfaceView mv)
{
//加载顶点着色器的脚本内容
mVertexShader=ShaderUtil.loadFromAssetsFile("vertex_color_light.sh", mv.getResources());
//加载片元着色器的脚本内容
mFragmentShader=ShaderUtil.loadFromAssetsFile("frag_color_light.sh", mv.getResources());
//基于顶点着色器与片元着色器创建程序
mProgram = createProgram(mVertexShader, mFragmentShader);
//获取程序中顶点位置属性引用id
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点颜色属性引用id
maColorHandle= GLES20.glGetAttribLocation(mProgram, "aColor");
//获取程序中总变换矩阵引用id
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
//获取程序中顶点法向量属性引用id
maNormalHandle= GLES20.glGetAttribLocation(mProgram, "aNormal");
//获取程序中摄像机位置引用id
maCameraHandle=GLES20.glGetUniformLocation(mProgram, "uCamera");
//获取程序中光源位置引用id
maLightLocationHandle=GLES20.glGetUniformLocation(mProgram, "uLightLocation");
//获取位置、旋转变换矩阵引用id
muMMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMMatrix");
}
public void drawSelf()
{
MatrixState.rotate(xAngle, 1, 0, 0);
MatrixState.rotate(yAngle, 0, 1, 0);
MatrixState.rotate(zAngle, 0, 0, 1);
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将位置、旋转变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMMatrixHandle, 1, false, MatrixState.getMMatrix(), 0);
//将摄像机位置传入shader程序
GLES20.glUniform3fv(maCameraHandle, 1, MatrixState.cameraFB);
//将光源位置传入shader程序
GLES20.glUniform3fv(maLightLocationHandle, 1, MatrixState.lightPositionFB);
//传送顶点位置数据
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//传送顶点颜色数据
GLES20.glVertexAttribPointer
(
maColorHandle,
4,
GLES20.GL_FLOAT,
false,
4*4,
mColorBuffer
);
//传送顶点法向量数据
GLES20.glVertexAttribPointer
(
maNormalHandle,
4,
GLES20.GL_FLOAT,
false,
3*4,
mNormalBuffer
);
//启用顶点位置数据
GLES20.glEnableVertexAttribArray(maPositionHandle);
//启用顶点颜色数据
GLES20.glEnableVertexAttribArray(maColorHandle);
//启用顶点法向量数据
GLES20.glEnableVertexAttribArray(maNormalHandle);
//绘制线条的粗细
GLES20.glLineWidth(2);
//绘制
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
}
}

View File

@@ -0,0 +1,207 @@
package com.bn.Sample8_6;
import java.util.ArrayList;
import java.util.List;
public class Utils {
static boolean first=true;
//将一个向量规格化的方法
public static float[] normalizeVector(float x, float y, float z){
float mod=module(x,y,z);
return new float[]{x/mod, y/mod, z/mod};//返回规格化后的向量
}
//求向量的模的方法
public static float module(float x, float y, float z){
return (float) Math.sqrt(x*x+y*y+z*z);
}
public static double[] nRotate(
double angle, //旋转角度
double n[], //旋转轴
double gVector[] //旋转向量
){
angle = Math.toRadians(angle);
double[][] matrix=//绕任意轴旋转变换矩阵
{
{n[0]*n[0]*(1-Math.cos(angle))+Math.cos(angle),n[0]*n[1]*(1-Math.cos(angle))+n[2]*Math.sin(angle),n[0]*n[2]*(1-Math.cos(angle))-n[1]*Math.sin(angle),0},
{n[0]*n[1]*(1-Math.cos(angle))-n[2]*Math.sin(angle),n[1]*n[1]*(1-Math.cos(angle))+Math.cos(angle),n[1]*n[2]*(1-Math.cos(angle))+n[0]*Math.sin(angle),0},
{n[0]*n[2]*(1-Math.cos(angle))+n[1]*Math.sin(angle),n[1]*n[2]*(1-Math.cos(angle))-n[0]*Math.sin(angle),n[2]*n[2]*(1-Math.cos(angle))+Math.cos(angle),0},
{0,0,0,1}
};
double[] tempDot={gVector[0],gVector[1],gVector[2],gVector[3]};
for(int j=0;j<4;j++)
{
gVector[j]=(tempDot[0]*matrix[0][j]+tempDot[1]*matrix[1][j]+
tempDot[2]*matrix[2][j]+tempDot[3]*matrix[3][j]);
}
return gVector; //返回结果
}
//给出初始点,初始向量,边长,获取正多边形的顶点坐标
public static List<Float> getRegularPentagonVertexData(
double[] initPoint, //起点
double[] initVector, //初始向量(方向向量)
double length, //边长
double angle, //旋转角度
double[][] vectors, //保存上一条边的方向向量
int borderCount,
double[] pivot //旋转轴
){
List<Float> verticesList = new ArrayList<Float>(); //新建一个ArrayList
double[] startPoint=initPoint;//起点
double[] endPoint; //终点坐标
double[] vector = copyVecor(initVector);//复制第一条边的方向向量
int index=0;
double[] vectorS = copyVecor(vector); //将向量复制一份
vectors[index++]=vectorS; //将第一个向量保存
for(int i=0;i<initPoint.length;i++){ //将第一个点的坐标添加到list中
verticesList.add((float) initPoint[i]);
}
while(index<borderCount){ //循环计算其余的点的坐标
endPoint = new double[3];//创建当前线段的终点
//终点坐标等于起点加上长度与方向向量的点积
endPoint[0]=startPoint[0]+length*vector[0];//计算终点x
endPoint[1]=startPoint[1]+length*vector[1];//计算终点y
endPoint[2]=startPoint[2]+length*vector[2];//计算终点z
//如果计算出来的终点等于第一个点,则计算完毕,循环退出
if(
compare(endPoint[0],initPoint[0])==0 //调用compare方法进行比较
&& compare(endPoint[1],initPoint[1])==0
&& compare(endPoint[2],initPoint[2])==0
){
break;
}
for(int i=0;i<endPoint.length;i++){ //将终点的坐标添加到list中
float value = (float) endPoint[i];
if(Math.abs(value)<0.000001){
verticesList.add(new Float(0.0f));
continue;
}else{
verticesList.add((float) endPoint[i]);
}
}
//计算下一条边的方向向量
if(index==1){
vector = nRotate(angle,pivot,vector);//绕父对象的旋转轴生成第二个向量,与父对象在同一平面的
if(!first){//如果不是第一个多边形
double tempAngle = 39*angle/Math.abs(angle);//getDihedralAngle()*(angle/Math.abs(angle));
vector = nRotate(tempAngle,initVector,vector);//将第二个向量绕第一个向量旋转
pivot = nRotate(tempAngle,initVector,pivot);//生成新的旋转轴
}
first=false;
}else{
vector = nRotate(angle,pivot,vector);//将当前的方向向量旋转得到新的方向向量
}
vectorS = copyVecor(vector);//将向量复制一份
vectors[index++]=vectorS;//将新的向量保存
startPoint = endPoint;//将当前线段的终点作为下条线段的起点
}
return verticesList;
}
public static double[] copyVecor(double[] vector){ //复制数组中数组的方法
double[] copy = new double[vector.length];
for(int i=0;i<vector.length;i++){
copy[i]=vector[i];
}
return copy;
}
//比较两个数的方法
public static int compare(double x,double y){
if(Math.abs(x-y)<0.000001){
return 0;
}else if(x-y>0.000001){
return 1;
}else{
return -1;
}
}
//计算第一个点的坐标--五边形的左下角点,使第一个五边形中心为坐标原点
public static double[] getFirstPoint(
float length //正五边形的边长
){
double first[] = new double[3]; //正五边形坐下点坐标数组
first[0]=-length/2; //x坐标值
first[1]=-length/(2*Math.tan(Math.toRadians(36))); //y坐标值
first[2]=0; //由于在xy平面上z自然为0
return first;
}
//求二面角--套结果公式
public static double getDihedralAngle(){
return Math.toDegrees(Math.acos(Math.sqrt(5)/3));
}
//计算两个向量的夹角--结果为度
public static double getAngleBetweenTwoVector(double[] vector1,double[] vector2){
double angle=0;
double DJ = vector1[0]*vector2[0]+vector1[1]*vector2[1]+vector1[2]*vector2[2];//计算点积
double mode = getMode(vector1)*getMode(vector2);//求向量模的积
double cosa = DJ/mode;
if(compare(cosa,1)==0){
return 0;
}
angle = Math.toDegrees(Math.acos(cosa));
return angle;
}
//求向量的模
public static double getMode(double[] vector){
return Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]+vector[2]*vector[2]);
}
public static double[] getCJ(double[] v1,double[] v2){//计算叉积--v1叉乘v2
double[] result = new double[3];
result[0]=v1[1]*v2[2]-v1[2]*v2[1];
result[1]=v1[2]*v2[0]-v1[0]*v2[2];
result[2]=v1[0]*v2[1]-v1[1]*v2[0];
return result;
}
//变换坐标系--是x轴变换到指定向量的位置
public static void moveXToSomeVector(double[] vector){
double x[]={1,0,0};
double angle = getAngleBetweenTwoVector(x,vector);//vector与x轴的夹角
//通过x与vector的叉积计算出旋转轴的向量
double pivot[] = getCJ(x,vector); //调用求叉乘的方法
MatrixState.rotate((float)angle, (float)pivot[0], (float)pivot[1],(float)pivot[2]);
}
static List<Float> drawnVertices = new ArrayList<Float>();//已经绘制的点的坐标
public static boolean isExist(float x,float y,float z){
for(int i=0;i<drawnVertices.size()/3;i++){
float tempx = drawnVertices.get(3*i);
float tempy = drawnVertices.get(3*i+1);
float tempz = drawnVertices.get(3*i+2);
double[] tempp=new double[]{tempx,tempy,tempz};
double[] p = new double[]{x,y,z};
if(getDistanceSquare(tempp, p)<=0.2*0.2*4){
return true;
}
}
return false;
}
public static double getDistanceSquare(double[] p1,double[] p2){
return getSquare(p1[0]-p2[0])+getSquare(p1[1]-p2[1])+getSquare(p1[2]-p2[2]);
}
public static double getSquare(double x){
return x*x;
}
}