this example uses the random-number generation functions in Boost.Compute to calculate a large number of random "steps" and then plots the final random "walk" in a 2D image on the GPU and displays it with OpenCV
| 29 | // to calculate a large number of random "steps" and then plots the final |
| 30 | // random "walk" in a 2D image on the GPU and displays it with OpenCV |
| 31 | int main() |
| 32 | { |
| 33 | // number of random steps to take |
| 34 | size_t steps = 250000; |
| 35 | |
| 36 | // height and width of image |
| 37 | size_t height = 800; |
| 38 | size_t width = 800; |
| 39 | |
| 40 | // get default device and setup context |
| 41 | compute::device gpu = compute::system::default_device(); |
| 42 | compute::context context(gpu); |
| 43 | compute::command_queue queue(context, gpu); |
| 44 | |
| 45 | using compute::int2_; |
| 46 | |
| 47 | // calaculate random values for each step |
| 48 | compute::vector<float> random_values(steps, context); |
| 49 | compute::default_random_engine random_engine(queue); |
| 50 | compute::uniform_real_distribution<float> random_distribution(0.f, 4.f); |
| 51 | |
| 52 | random_distribution.generate( |
| 53 | random_values.begin(), random_values.end(), random_engine, queue |
| 54 | ); |
| 55 | |
| 56 | // calaculate coordinates for each step |
| 57 | compute::vector<int2_> coordinates(steps, context); |
| 58 | |
| 59 | // function to convert random values to random directions (in 2D) |
| 60 | BOOST_COMPUTE_FUNCTION(int2_, take_step, (const float x), |
| 61 | { |
| 62 | if(x < 1.f){ |
| 63 | // move right |
| 64 | return (int2)(1, 0); |
| 65 | } |
| 66 | if(x < 2.f){ |
| 67 | // move up |
| 68 | return (int2)(0, 1); |
| 69 | } |
| 70 | if(x < 3.f){ |
| 71 | // move left |
| 72 | return (int2)(-1, 0); |
| 73 | } |
| 74 | else { |
| 75 | // move down |
| 76 | return (int2)(0, -1); |
| 77 | } |
| 78 | }); |
| 79 | |
| 80 | // transform the random values into random steps |
| 81 | compute::transform( |
| 82 | random_values.begin(), random_values.end(), coordinates.begin(), take_step, queue |
| 83 | ); |
| 84 | |
| 85 | // set staring position |
| 86 | int2_ starting_position(width / 2, height / 2); |
| 87 | compute::copy_n(&starting_position, 1, coordinates.begin(), queue); |
| 88 |
nothing calls this directly
no test coverage detected