1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use crate::b2_collision::*;
use crate::b2_growable_stack::B2growableStack;
use crate::b2_math::*;
use crate::b2_settings::*;
use crate::private::collision::b2_dynamic_tree as private;

pub const B2_NULL_NODE: i32 = -1;

// #[derive(Debug, Clone, Copy)]
// pub enum TParentOrNext
// {
// 	None,
// 	Parent(i32),
// 	Next(i32)
// }

// impl Default for TParentOrNext
// {
// 	fn default() -> TParentOrNext
// 	{
// 		TParentOrNext::None
// 	}
// }

/// A node in the dynamic tree. The client does not interact with this directly.
#[derive(Default, Clone, Debug)]
pub struct B2treeNode<UserDataType> {
	/// Enlarged AABB
	pub(crate) aabb: B2AABB,

	pub(crate) user_data: Option<UserDataType>,

	//union
	//{
	//	 parent:i32,
	//	 next:i32,
	//},
	//TODO_humman всё же тут надо сделать нормальный enum а то каша
	//pub(crate) parent_or_next: TParentOrNext,
	pub(crate) parent_or_next: i32,

	pub(crate) child1: i32,
	pub(crate) child2: i32,

	// leaf = 0, free node = -1
	pub(crate) height: i32,

	pub(crate) moved: bool,
}

impl<UserDataType> B2treeNode<UserDataType> {
	pub fn is_leaf(&self) -> bool {
		return self.child1 == B2_NULL_NODE;
	}
}

/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt.
/// A dynamic tree arranges data in a binary tree to accelerate
/// queries such as volume queries and ray casts. Leafs are proxies
/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor
/// so that the proxy AABB is bigger than the client object. This allows the client
/// object to move by small amounts without triggering a tree update.
///
/// Nodes are pooled and relocatable, so we use node indices rather than pointers.
#[derive(Default, Clone, Debug)]
pub struct B2dynamicTree<UserDataType> {
	pub(crate) m_root: i32,

	//TODO_humman а надо ли нам тут Rc RefCell - указателей больше нет, только индексы
	pub(crate) m_nodes: Vec<B2treeNode<UserDataType>>,
	pub(crate) m_node_count: i32,
	pub(crate) m_node_capacity: i32,

	pub(crate) m_free_list: i32,

	/// This is used to incrementally traverse the tree for re-balancing.
	pub(crate) m_path: u32,

	pub(crate) m_insertion_count: i32,
}

impl<UserDataType: Clone + Default> B2dynamicTree<UserDataType> {
	/// Constructing the tree initializes the node pool.
	pub fn new() -> Self {
		return private::b2_dynamic_tree();
	}

	/// destroy the tree, freeing the node pool.
	//~B2dynamicTree();

	/// create a proxy. Provide a tight fitting AABB and a user_data pointer.
	pub fn create_proxy(&mut self, aabb: B2AABB, user_data: &UserDataType) -> i32 {
		return private::create_proxy(self, aabb, user_data);
	}

	/// destroy a proxy. This asserts if the id is invalid.
	pub fn destroy_proxy(&mut self, proxy_id: i32) {
		private::destroy_proxy(self, proxy_id);
	}

	/// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB,
	/// then the proxy is removed from the tree and re-inserted. Otherwise
	/// the function returns immediately.
	/// @return true if the proxy was re-inserted.
	pub fn move_proxy(&mut self, proxy_id: i32, aabb1: B2AABB, displacement: B2vec2) -> bool {
		return private::move_proxy(self, proxy_id, aabb1, displacement);
	}

	/// Get proxy user data.
	/// @return the proxy user data or 0 if the id is invalid.
	pub fn get_user_data(&self, proxy_id: i32) -> Option<UserDataType> {
		return inline::get_user_data(self, proxy_id);
	}

	pub fn was_moved(&self, proxy_id: i32) -> bool {
		return inline::was_moved(self, proxy_id);
	}
	pub fn clear_moved(&mut self, proxy_id: i32) {
		inline::clear_moved(self, proxy_id);
	}

	/// Get the fat AABB for a proxy.
	pub fn get_fat_aabb(&self, proxy_id: i32) -> B2AABB {
		return inline::get_fat_aabb(self, proxy_id);
	}

	/// query an AABB for overlapping proxies. The callback class
	/// is called for each proxy that overlaps the supplied AABB.
	pub fn query<F:  QueryCallback>(&self, callback: F, aabb: B2AABB) {
		inline::query(self, callback, aabb);
	}

	/// Ray-cast against the proxies in the tree. This relies on the callback
	/// to perform a exact ray-cast in the case were the proxy contains a shape.
	/// The callback also performs the any collision filtering. This has performance
	/// roughly equal to k * log(n), where k is the number of collisions and n is the
	/// number of proxies in the tree.
	/// * `input` - the ray-cast input data. The ray extends from p1 to p1 + max_fraction * (p2 - p1).
	/// * `callback` - a callback class that is called for each proxy that is hit by the ray.
	pub fn ray_cast<T: RayCastCallback>(&self, callback: T, input: &B2rayCastInput) {
		inline::ray_cast(self, callback, input);
	}

	/// Validate this tree. For testing.
	pub fn validate(&self) {
		private::validate(self);
	}

	/// Compute the height of the binary tree in O(n) time. Should not be
	/// called often.
	pub fn get_height(&self) -> i32 {
		return private::get_height(self);
	}

	/// Get the maximum balance of an node in the tree. The balance is the difference
	/// in height of the two children of a node.
	pub fn get_max_balance(&self) -> i32 {
		return private::get_max_balance(self);
	}

	/// Get the ratio of the sum of the node areas to the root area.
	pub fn get_area_ration(&self) -> f32 {
		return private::get_area_ratio(self);
	}

	/// Build an optimal tree. Very expensive. For testing.
	pub fn rebuild_bottom_up(&mut self) {
		private::rebuild_bottom_up(self);
	}

	/// Shift the world origin. Useful for large worlds.
	/// The shift formula is: position -= new_origin
	/// * `new_origin` - the new origin with respect to the old origin
	pub fn shift_origin(&mut self, new_origin: B2vec2) {
		private::shift_origin(self, new_origin);
	}

	pub(crate) fn allocate_node(&mut self) -> i32 {
		return private::allocate_node(self);
	}
	pub(crate) fn free_node(&mut self, node: i32) {
		private::free_node(self, node);
	}

	pub(crate) fn insert_leaf(&mut self, node: i32) {
		private::insert_leaf(self, node);
	}
	pub(crate) fn remove_leaf(&mut self, node: i32) {
		private::remove_leaf(self, node);
	}

	pub(crate) fn balance(&mut self, index: i32) -> i32 {
		return private::balance(self, index);
	}

	pub(crate) fn compute_height(&self) -> i32 {
		return private::compute_height(self);
	}
	pub(crate) fn compute_height_by_node(&self, node_id: i32) -> i32 {
		return private::compute_height_by_node(self, node_id);
	}

	pub(crate) fn validate_structure(&self, index: i32) {
		private::validate_structure(self, index);
	}
	pub(crate) fn validate_metrics(&self, index: i32) {
		private::validate_metrics(self, index);
	}
}

// pub trait QueryCallback {
// 	fn query_callback(&mut self, proxy_id: i32) -> bool;
// }
pub trait QueryCallback: FnMut(i32) -> bool {}
impl <F> QueryCallback for F where F: FnMut(i32) -> bool {}

// pub trait RayCastCallback {
// 	fn ray_cast_callback(&mut self, input: &B2rayCastInput, proxy_id: i32) -> f32;
// }
pub trait RayCastCallback: FnMut(&B2rayCastInput, i32) -> f32 {}
impl <F> RayCastCallback for F where F: FnMut(&B2rayCastInput, i32) -> f32 {}

mod inline {
	use super::*;

	pub fn get_user_data<UserDataType: Clone + Default>(
		this: &B2dynamicTree<UserDataType>,
		proxy_id: i32,
	) -> Option<UserDataType> {
		//b2_assert(0 <= proxy_id && proxy_id < this.m_nodeCapacity);
		return this.m_nodes[proxy_id as usize].user_data.clone();
	}

	pub fn was_moved<UserDataType: Clone + Default>(
		this: &B2dynamicTree<UserDataType>,
		proxy_id: i32,
	) -> bool {
		//b2_assert(0 <= proxy_id && proxy_id < this.m_nodeCapacity);
		return this.m_nodes[proxy_id as usize].moved;
	}

	pub fn clear_moved<UserDataType: Clone + Default>(
		this: &mut B2dynamicTree<UserDataType>,
		proxy_id: i32,
	) {
		//b2_assert(0 <= proxy_id && proxy_id < this.m_nodeCapacity);
		this.m_nodes[proxy_id as usize].moved = false;
	}

	pub fn get_fat_aabb<UserDataType: Clone + Default>(
		this: &B2dynamicTree<UserDataType>,
		proxy_id: i32,
	) -> B2AABB {
		//b2_assert(0 <= proxy_id && proxy_id < this.m_nodeCapacity);
		return this.m_nodes[proxy_id as usize].aabb;
	}

	pub fn query<UserDataType, F:  QueryCallback>(
		this: &B2dynamicTree<UserDataType>,
		mut callback: F,
		aabb: B2AABB,
	) {
		let mut stack = B2growableStack::<i32>::new();
		stack.push(&this.m_root);

		while stack.get_count() > 0 {
			let node_id: i32 = stack.pop();
			if node_id == B2_NULL_NODE {
				continue;
			}

			let node = &this.m_nodes[node_id as usize];

			if b2_test_overlap(node.aabb, aabb) {
				if node.is_leaf() {
					let proceed: bool = callback(node_id);
					if proceed == false {
						return;
					}
				} else {
					stack.push(&node.child1);
					stack.push(&node.child2);
				}
			}
		}
	}

	pub fn ray_cast<T: RayCastCallback, UserDataType>(
		this: &B2dynamicTree<UserDataType>,
		mut callback: T,
		input: &B2rayCastInput,
	) {
		let p1: B2vec2 = input.p1;
		let p2: B2vec2 = input.p2;
		let mut r: B2vec2 = p2 - p1;
		b2_assert(r.length_squared() > 0.0);
		r.normalize();

		// v is perpendicular to the segment.
		let v: B2vec2 = b2_cross_scalar_by_vec(1.0, r);
		let abs_v: B2vec2 = b2_abs_vec2(v);

		// Separating axis for segment (Gino, p80).
		// |dot(v, p1 - c)| > dot(|v|, h)

		let mut max_fraction: f32 = input.max_fraction;

		// Build a bounding box for the segment.
		let mut segment_aabb = B2AABB::default();
		{
			let t: B2vec2 = p1 + max_fraction * (p2 - p1);
			segment_aabb.lower_bound = b2_min_vec2(p1, t);
			segment_aabb.upper_bound = b2_max_vec2(p1, t);
		}

		let mut stack = B2growableStack::<i32>::new();
		stack.push(&this.m_root);

		while stack.get_count() > 0 {
			let node_id: i32 = stack.pop();
			if node_id == B2_NULL_NODE {
				continue;
			}

			let node = &this.m_nodes[node_id as usize];

			if b2_test_overlap(node.aabb, segment_aabb) == false {
				continue;
			}

			// Separating axis for segment (Gino, p80).
			// |dot(v, p1 - c)| > dot(|v|, h)
			let c: B2vec2 = node.aabb.get_center();
			let h: B2vec2 = node.aabb.get_extents();
			let separation: f32 = b2_abs(b2_dot(v, p1 - c)) - b2_dot(abs_v, h);
			if separation > 0.0 {
				continue;
			}

			if node.is_leaf() {
				let sub_input = B2rayCastInput {
					p1: input.p1,
					p2: input.p2,
					max_fraction: max_fraction,
				};

				let value: f32 = callback(&sub_input, node_id);

				if value == 0.0 {
					// The client has terminated the ray cast.
					return;
				}

				if value > 0.0 {
					// update segment bounding box.
					max_fraction = value;
					let t: B2vec2 = p1 + max_fraction * (p2 - p1);
					segment_aabb.lower_bound = b2_min_vec2(p1, t);
					segment_aabb.upper_bound = b2_max_vec2(p1, t);
				}
			} else {
				stack.push(&node.child1);
				stack.push(&node.child2);
			}
		}
	}
}