2017-07-25 102 views
1

我目前正在使用babylonjs進行一些3D建模。我需要從特定點的給定壓力創建壓力圖。我正在使用IDW。然而,這意味着即使我的地圖大小爲70x90,我也需要一個25200的數組(每個像素有4個rgba值)。然後這個緩衝區被傳遞給一個RawTexture用於將它分配給一個物體,它覆蓋在物體上將巨大數組傳遞給webworker時不斷增加內存使用

我正在使用網絡工作者,因爲我必須每隔100ms更新一次壓力值,而且我不想阻止主線程。當我從服務工作者返回該數組(在calculate函數中創建)時發生該問題。

由於某些原因,內存使用量不斷增加而不停止。它最終會達到大約1.5千兆字節,我必須殺死它。

問題:有沒有什麼辦法可以防止這種情況,以及可能導致如此高的內存使用情況?

工人:

// @flow 
import { find, propEq, both } from 'ramda'; 
import { colorFromValue } from './color'; 
import { inverseDistance, distanceValues } from './math'; 

const findPoint = (x: number, y: number) => 
    find(both(propEq('x', x), propEq('y', y))); 

const distanceDict = {}; 

/* eslint-disable */ 
function calculate(options: Object, pList: Array<*>) { 
    const points = pList || []; 
    const { height, width } = options; 
    const gridWidth = width * 4; 
    const grid = new Uint8Array(options.width * options.height * 4); 

    for (let y = 0; y < height; y += 1) { 
    const rW = y * gridWidth; 
    for (let i = 0; i < gridWidth; i += 4) { 
     const index = i + rW; 
     const x = i/4; 
     const dictKey = `${x}--${y}`; 
     let bottoms = distanceDict[dictKey]; 

     if (bottoms === undefined) { 
     bottoms = distanceValues(points, x, y); 
     distanceDict[dictKey] = bottoms; 
     } 
     const point = findPoint(x, y)(points); 

     const value = point !== undefined && point !== null ? 
     point.value : inverseDistance(points, bottoms); 
     const color = colorFromValue(value); 
     grid[index] = color[0]; 
     grid[index + 1] = color[1]; 
     grid[index + 2] = color[2]; 
     grid[index + 3] = 255; 
    } 
    } 
    return grid; 
} 

self.onmessage = (e) => { 
    const { points, options } = e.data; 
    const grid = calculate(options, points); 
    self.postMessage(grid.buffer, [grid.buffer]); 
}; 

繪畫:

modifyNodes = (points: Array<*>) => new Promise((res, rej) => { 
    this.worker.onmessage = (e) => { 
    this._texture.update(new Uint8Array(e.data)); 
    res(); 
    } 
    const data = { 
    options: this._options, 
    points, 
    }; 
    this.worker.postMessage(data); 
}) 
+0

好問queston。 +1 – Zim84

+0

謝謝@ Zim84 – August

回答

1

這麼看來這個問題是在被memoized的colorFromValue功能。由於這些值的小數點很少,因此可以創建多達9個!新的條目進入緩存,所以它驅動了內存使用...