The Lightning generation algorithm that I wanted to figure out in my childhood was finally remembered and understood.
The algorithm is simple.
Keep the start and end points in two points until a limit is reached, and then all are connected.
1 voidDrawlightning (HDC hdc,ConstPoint &start,ConstPoint &end,floatdiff)2 {3 if(diff <S_mindiff)4 {5 Movetoex (hdc, Start.x, START.Y, nullptr);6 LineTo (hdc, end.x, END.Y);7 }8 Else9 {TenPoint mid = { One(Start.x + end.x)/2, A(Start.y + end.y)/2, - }; -Mid.x + = LONG (random ()-0.5f) *diff); theMid.y + = LONG (random ()-0.5f) *diff); -Drawlightning (hdc, Start, Mid, diff/2); -Drawlightning (hdc, End, Mid, diff/2); - } +}
The third parameter diff controls how the Lightning twists and turns,
The internal variable s_mindiff is the limit value.
These two variables determine how many key points a lightning bolt has.
Suppose diff = =, S_mindiff = 5
It is known that each recursive DIFF/2, so the final diff will be less than S_mindiff, which is 2.5.
To facilitate understanding, you can use a binary tree to identify the image.
0
0 0
0 0 0 0
The binary tree has 3 layers, each of which is recursive.
The first layer of recursion DIFF/2 = 10/2.
The second level of recursion DIFF/2 = 5/2.
Third Level recursive diff < S_mindiff.
The sum of all the nodes is the total number of calls.
All lines are drawn in the leaf node.
With the above, you can calculate the following
Number of recursive layers = Diff/s_mindiff + 1
Draw number of lines = 2 ^ (recursive layer-1)
Number of calls = 2 ^ (number of recursive layers)-1
Demo download
Lightning Generation algorithm