For loops are disturbing rendering

2019-08-17 07:05发布

问题:

I have some pretty simple 3D objects (basically THREE.Sphere which is a parent of 1-30 other THREE.Spheres, with RGB color and no texture) to display in somewhat real time animation.

The rendering is done in no time indeed, but I have some simple iterative calculation (for-loops) that are disturbing my display capabilities. The rendering itself is not the problem, but the computation for the next frame vertices is what causing the pain

Meaning, when I just run the script, I can see that the for-loops are taking too much time to compute, and just then it goes to the rendering section which is done in no time.

I was thinking of dealing with this problem in a parallel computing manner- running a thread (worker, whatever it is called in JS) that would calculate the for-loop, but I thought that considering my lack of experience in computer graphocs, perhaps there is a more "graphic"ed way of doing so. Meaning a more elegant/performance-improved/natural way of dealing with such a fundamental problem of computer graphics design.

回答1:

This is the basic idea I am using to do long slow calculations that don't get caught by the watchdog timers and bog down the browser or the render rate. The basic idea is that you use a javascript generator that allows you to yield in the middle of a computation, and continue later on. Then, I run the generator pump on a timeout chain. The key to this method is the "yield" operator that saves the function state and returns awaiting a future call to the .next() function. (btw this demo code might have to be re arraged to handle firefoxs forward references)

 //function Chain represents the slow code
function *Chain()
{
    for(i=0;i<1000000;i++)  //this represents a long slow calculation
    {
        if(i%100==0)        //on occassion, yield 
            yield;
    }

}
console.log("starting chain");
gChain=Chain(); //startup and get the next generator pointer
timeout = setTimeout(function () { ChainStart(); }, 1);
 //function ChainStart is a pump that runs the generator using a timeout chain so other threads can run
function ChainStart(){                 
        if(gChain.next().done){
            clearTimeout(timeout);
            console.log("endingchain");                 
        }
        else{                       
            clearTimeout(timeout);
            timeout = setTimeout(function () { ChainStart(); }, 1);
        }
}