Android 上實現水傳輸速率效二--最佳化
羅朝輝 (http://www.cnblogs.com/kesalin/)本文遵循“署名-非商業用途-保持一致”創作公用協議
在上一篇文章《Android 上實現水傳輸速率效》中對水波波幅的計算是針對每一個像素的,效率比較低,尤其是在手機上運行,相當緩慢。我們可以利用線性插值進行最佳化,這樣可以將計算減少一半(MeshSize 為 2)或減少四分之三(MeshSize 為 4),效率得以大大提升,即使是在水機上也能較為流暢地運行。
在下面的代碼中,為了充分使用移位元運算替代乘除法,MeshSize 必須為 2 的整次冪,MeshShift 就是其冪數,表示計算時的移位位元。代碼下載連結:http://www.cppblog.com/Files/kesalin/RippleDemo_opt.zip
線性插值最佳化之後的水波擴散代碼如下:
static final int MeshSize = 2;
static final int MeshShift = 1;
int m_meshWidth;
int m_meshHeight;
m_meshWidth = m_width / MeshSize + 1;
m_meshHeight = m_height / MeshSize + 1;;
void rippleSpread()
{
m_waveFlag = false;
int i = 0, offset = 0;
for (int y = 1; y < m_meshHeight - 1; ++y) {
offset = y * m_meshWidth;
for (int x = 1; x < m_meshWidth - 1; ++x) {
i = offset + x;
m_buf2[i] = (short)(((m_buf1[i - 1] + m_buf1[i + 1]
+ m_buf1[i - m_meshWidth]
+ m_buf1[i + m_meshWidth]) >> 1) -m_buf2[i]);
m_buf2[i] -= (m_buf2[i] >> 5);
m_waveFlag |= (m_buf2[i] != 0);
}
}
if (m_waveFlag){
m_waveFlag = false;
for (int y = 1; y < m_meshHeight - 1; ++y) {
offset = y * m_meshWidth;
for (int x = 1; x < m_meshWidth - 1; ++x) {
i = offset + x;
m_bufDiffX[i] = (short)((m_buf2[i + 1] - m_buf2[i - 1]) >> 3);
m_bufDiffY[i] = (short)((m_buf2[i + m_meshWidth] -m_buf2[i - m_meshWidth]) >> 3);
m_waveFlag |= (m_bufDiffX[i] != 0 || m_bufDiffY[i] != 0);
}
}
}
//交換波能資料緩衝區
short[] temp = m_buf1;
m_buf1 = m_buf2;
m_buf2 = temp;
}
既然波幅計算使用了線性插值,描繪時的代碼也許相應變更:
Point p1, p2, p3, p4;
Point pRowStart, pRowEnd, p, rowStartInc, rowEndInc, pInc;
void rippleRender()
{
int px = 0, py = 0, dx = 0, dy = 0;
int index = 0, offset = 0;
for (int j = 1; j < m_meshHeight; ++j) {
offset = j * m_meshWidth;
for (int i = 1; i < m_meshWidth; ++i) {
index = offset + i;
p1.x = m_bufDiffX[index - m_meshWidth - 1];
p1.y = m_bufDiffY[index - m_meshWidth - 1];
p2.x = m_bufDiffX[index - m_meshWidth];
p2.y = m_bufDiffY[index - m_meshWidth];
p3.x = m_bufDiffX[index - 1];
p3.y = m_bufDiffY[index - 1];
p4.x = m_bufDiffX[index];
p4.y = m_bufDiffY[index];
pRowStart.x = p1.x << MeshShift;
pRowStart.y = p1.y << MeshShift;
rowStartInc.x = p3.x - p1.x;
rowStartInc.y = p3.y - p1.y;
pRowEnd.x = p2.x << MeshShift;
pRowEnd.y = p2.y << MeshShift;
rowEndInc.x = p4.x - p2.x;
rowEndInc.y = p4.y - p2.y;
py = (j - 1) << MeshShift;
for (int y = 0; y < MeshSize; ++y) {
p.x = pRowStart.x;
p.y = pRowStart.y;
// scaled by MeshSize times
pInc.x = (pRowEnd.x - pRowStart.x) >> MeshShift;
pInc.y = (pRowEnd.y - pRowStart.y) >> MeshShift;
px = (i - 1) << MeshShift;
for (int x = 0; x < MeshSize; ++x) {
dx = px + p.x >> MeshShift;
dy = py + p.y >> MeshShift;
if ((dx >= 0) && (dy >= 0) && (dx < m_width) && (dy < m_height) ) {
m_bitmap2[py * m_width + px] = m_bitmap1[dy * m_width + dx];
}
else {
m_bitmap2[py * m_width + px] = m_bitmap1[py * m_width + px];
}
p.x += pInc.x;
p.y += pInc.y;
++px;
}
pRowStart.x += rowStartInc.x;
pRowStart.y += rowStartInc.y;
pRowEnd.x += rowEndInc.x;
pRowEnd.y += rowEndInc.y;
++py;
}
}
}
}