50ea62e41951db888036ef5f427bb1db69d1b71c
[carveJwlIkooP6JGAAIwe30JlM.git] / player_physics.h
1 /*
2 * Copyright (C) 2021-2022 Mt.ZERO Software, Harry Godden - All Rights Reserved
3 */
4
5 #ifndef PLAYER_PHYSICS_H
6 #define PLAYER_PHYSICS_H
7
8 #include "player.h"
9 #include "camera.h"
10
11 VG_STATIC void apply_gravity( v3f vel, float const timestep )
12 {
13 v3f gravity = { 0.0f, -9.6f, 0.0f };
14 v3_muladds( vel, gravity, timestep, vel );
15 }
16
17 VG_STATIC struct
18 grind_edge *player_grind_collect_edge( v3f p0, v3f p1,
19 v3f c0, v3f c1, float max_dist )
20 {
21 struct player_phys *phys = &player.phys;
22
23 bh_iter it;
24 bh_iter_init( 0, &it );
25
26 boxf region;
27
28 box_init_inf( region );
29 box_addpt( region, p0 );
30 box_addpt( region, p1 );
31
32 float k_r = max_dist;
33 v3_add( (v3f){ k_r, k_r, k_r}, region[1], region[1] );
34 v3_add( (v3f){-k_r,-k_r,-k_r}, region[0], region[0] );
35
36 float closest = k_r*k_r;
37 struct grind_edge *closest_edge = NULL;
38
39 int idx;
40 while( bh_next( world.grind_bh, &it, region, &idx ) )
41 {
42 struct grind_edge *edge = &world.grind_edges[ idx ];
43
44 float s,t;
45 v3f pa, pb;
46
47 float d2 =
48 closest_segment_segment( p0, p1, edge->p0, edge->p1, &s,&t, pa, pb );
49
50 if( d2 < closest )
51 {
52 closest = d2;
53 closest_edge = edge;
54 v3_copy( pa, c0 );
55 v3_copy( pb, c1 );
56 }
57 }
58
59 return closest_edge;
60 }
61
62 /*
63 * Cast a sphere from a to b and see what time it hits
64 */
65 VG_STATIC int spherecast_world( v3f pa, v3f pb, float r, float *t, v3f n )
66 {
67 struct player_phys *phys = &player.phys;
68
69 bh_iter it;
70 bh_iter_init( 0, &it );
71
72 boxf region;
73 box_init_inf( region );
74 box_addpt( region, pa );
75 box_addpt( region, pb );
76
77 v3_add( (v3f){ r, r, r}, region[1], region[1] );
78 v3_add( (v3f){-r,-r,-r}, region[0], region[0] );
79
80 v3f dir;
81 v3_sub( pb, pa, dir );
82
83 int hit = -1;
84 float min_t = 1.0f;
85
86 int idx;
87 while( bh_next( world.geo_bh, &it, region, &idx ) )
88 {
89 u32 *ptri = &world.scene_geo->arrindices[ idx*3 ];
90 v3f tri[3];
91
92 boxf box;
93 box_init_inf( box );
94
95 for( int j=0; j<3; j++ )
96 {
97 v3_copy( world.scene_geo->arrvertices[ptri[j]].co, tri[j] );
98 box_addpt( box, tri[j] );
99 }
100
101 v3_add( (v3f){ r, r, r}, box[1], box[1] );
102 v3_add( (v3f){-r,-r,-r}, box[0], box[0] );
103 if( !ray_aabb( box, pa, dir, 1.0f ) )
104 continue;
105
106 float t;
107 v3f n1;
108 if( spherecast_triangle( tri, pa, dir, r, &t, n1 ) )
109 {
110 if( t < min_t )
111 {
112 min_t = t;
113 hit = idx;
114 v3_copy( n1, n );
115 }
116 }
117 }
118
119 *t = min_t;
120 return hit;
121 }
122
123 /*
124 * Trace a path given a velocity rotation.
125 * Closest to 0 is best.
126 */
127 VG_STATIC void player_predict_land( m3x3f vr,
128 struct land_prediction *prediction )
129 {
130 struct player_phys *phys = &player.phys;
131
132 float pstep = VG_TIMESTEP_FIXED * 10.0f;
133 float k_bias = 0.96f;
134
135 v3f pco, pco1, pv;
136 v3_copy( phys->rb.co, pco );
137 v3_muls( phys->rb.v, k_bias, pv );
138
139 m3x3_mulv( vr, pv, pv );
140 v3_muladds( pco, pv, pstep, pco );
141
142 struct grind_edge *best_grind = NULL;
143 float closest_grind = INFINITY;
144
145 float grind_score = INFINITY,
146 air_score = INFINITY;
147
148 prediction->log_length = 0;
149
150 for( int i=0; i<vg_list_size(prediction->log); i++ )
151 {
152 v3_copy( pco, pco1 );
153 apply_gravity( pv, pstep );
154
155 m3x3_mulv( vr, pv, pv );
156 v3_muladds( pco, pv, pstep, pco );
157
158 v3f vdir;
159
160 v3_sub( pco, pco1, vdir );
161
162 float l = v3_length( vdir );
163 v3_muls( vdir, 1.0f/l, vdir );
164
165 v3f c0, c1;
166 struct grind_edge *ge = player_grind_collect_edge( pco, pco1,
167 c0, c1, 0.4f );
168
169 if( ge && (v3_dot((v3f){0.0f,1.0f,0.0f},vdir) < -0.2f ) )
170 {
171 float d2 = v3_dist2( c0, c1 );
172 if( d2 < closest_grind )
173 {
174 closest_grind = d2;
175 best_grind = ge;
176 grind_score = closest_grind * 0.05f;
177 }
178 }
179
180 v3f n1;
181
182 float t1;
183 int idx = spherecast_world( pco1, pco, 0.4f, &t1, n1 );
184 if( idx != -1 )
185 {
186 v3_copy( n1, prediction->n );
187 air_score = -v3_dot( pv, n1 );
188
189 u32 vert_index = world.scene_geo->arrindices[ idx*3 ];
190 struct world_material *mat = world_tri_index_material( vert_index );
191
192 /* Bias prediction towords ramps */
193 if( mat->info.flags & k_material_flag_skate_surface )
194 air_score *= 0.1f;
195
196 v3_lerp( pco1, pco, t1, prediction->log[ prediction->log_length ++ ] );
197 break;
198 }
199
200 v3_copy( pco, prediction->log[ prediction->log_length ++ ] );
201 }
202
203 if( grind_score < air_score )
204 {
205 prediction->score = grind_score;
206 prediction->type = k_prediction_grind;
207 }
208 else if( air_score < INFINITY )
209 {
210 prediction->score = air_score;
211 prediction->type = k_prediction_land;
212 }
213 else
214 {
215 prediction->score = INFINITY;
216 prediction->type = k_prediction_none;
217 }
218 }
219
220 /*
221 * Called when launching into the air to predict and adjust trajectories
222 */
223 VG_STATIC void player_start_air(void)
224 {
225 struct player_phys *phys = &player.phys;
226
227 float pstep = VG_TIMESTEP_FIXED * 10.0f;
228 float best_velocity_delta = -9999.9f;
229
230 v3f axis;
231 v3_cross( phys->rb.up, phys->rb.v, axis );
232 v3_normalize( axis );
233 player.prediction_count = 0;
234
235 m3x3_identity( phys->vr );
236
237 float
238 best_vmod = 0.0f,
239 min_score = INFINITY,
240 max_score = -INFINITY;
241
242 /*
243 * Search a broad selection of futures
244 */
245 for( int m=-3;m<=12; m++ )
246 {
247 struct land_prediction *p =
248 &player.predictions[ player.prediction_count ++ ];
249
250 float vmod = ((float)m / 15.0f)*0.09f;
251
252 m3x3f vr;
253 v4f vr_q;
254
255 q_axis_angle( vr_q, axis, vmod );
256 q_m3x3( vr_q, vr );
257
258 player_predict_land( vr, p );
259
260 if( p->type != k_prediction_none )
261 {
262 if( p->score < min_score )
263 {
264 min_score = p->score;
265 best_vmod = vmod;
266 }
267
268 if( p->score > max_score )
269 max_score = p->score;
270 }
271 }
272
273 v4f vr_q;
274 q_axis_angle( vr_q, axis, best_vmod*0.1f );
275 q_m3x3( vr_q, phys->vr );
276
277 q_axis_angle( vr_q, axis, best_vmod );
278 q_m3x3( vr_q, phys->vr_pstep );
279
280 /*
281 * Logging
282 */
283 for( int i=0; i<player.prediction_count; i ++ )
284 {
285 struct land_prediction *p = &player.predictions[i];
286
287 float l = p->score;
288
289 if( l < 0.0f )
290 {
291 vg_error( "negative score! (%f)\n", l );
292 }
293
294 l -= min_score;
295 l /= (max_score-min_score);
296 l = 1.0f - l;
297 l *= 255.0f;
298
299 p->colour = l;
300 p->colour <<= 8;
301 p->colour |= 0xff000000;
302 }
303 }
304
305
306 VG_STATIC void player_physics_control_passive(void)
307 {
308 struct player_phys *phys = &player.phys;
309 float grabt = player.input_grab->axis.value;
310
311 if( grabt > 0.5f )
312 {
313 v2_muladds( phys->grab_mouse_delta, vg.mouse_delta, 0.02f,
314 phys->grab_mouse_delta );
315 v2_normalize_clamp( phys->grab_mouse_delta );
316
317 if( freecam )
318 v2_zero( phys->grab_mouse_delta );
319 }
320 else
321 v2_zero( phys->grab_mouse_delta );
322
323 phys->grab = vg_lerpf( phys->grab, grabt, 0.14f );
324 player.phys.pushing = 0.0f;
325
326 if( !phys->jump_charge || phys->in_air )
327 {
328 phys->jump -= k_jump_charge_speed * VG_TIMESTEP_FIXED;
329 }
330
331 phys->jump_charge = 0;
332 phys->jump = vg_clampf( phys->jump, 0.0f, 1.0f );
333 }
334
335 /*
336 * Main friction interface model
337 */
338 VG_STATIC void player_physics_control(void)
339 {
340 struct player_phys *phys = &player.phys;
341
342 /*
343 * Computing localized friction forces for controlling the character
344 * Friction across X is significantly more than Z
345 */
346
347 v3f vel;
348 m3x3_mulv( phys->rb.to_local, phys->rb.v, vel );
349 float slip = 0.0f;
350
351 if( fabsf(vel[2]) > 0.01f )
352 slip = fabsf(-vel[0] / vel[2]) * vg_signf(vel[0]);
353
354 if( fabsf( slip ) > 1.2f )
355 slip = vg_signf( slip ) * 1.2f;
356 phys->slip = slip;
357 phys->reverse = -vg_signf(vel[2]);
358
359 float substep = VG_TIMESTEP_FIXED * 0.2f;
360 float fwd_resistance = k_friction_resistance;
361
362 for( int i=0; i<5; i++ )
363 {
364 vel[2] = stable_force( vel[2],vg_signf(vel[2]) * -fwd_resistance*substep);
365 vel[0] = stable_force( vel[0],vg_signf(vel[0]) * -k_friction_lat*substep);
366 }
367
368 if( player.input_jump->button.value )
369 {
370 phys->jump += VG_TIMESTEP_FIXED * k_jump_charge_speed;
371
372 if( !phys->jump_charge )
373 phys->jump_dir = phys->reverse > 0.0f? 1: 0;
374
375 phys->jump_charge = 1;
376 }
377
378 static int push_thresh_last = 0;
379 float push = player.input_push->button.value;
380 int push_thresh = push>0.15f? 1: 0;
381
382 if( push_thresh && !push_thresh_last )
383 player.phys.start_push = vg.time;
384
385 push_thresh_last = push_thresh;
386
387 if( !player.input_jump->button.value && push_thresh )
388 {
389 player.phys.pushing = 1.0f;
390 player.phys.push_time = vg.time - player.phys.start_push;
391
392 float cycle_time = player.phys.push_time*k_push_cycle_rate,
393 amt = k_push_accel * (sinf(cycle_time)*0.5f+0.5f)*VG_TIMESTEP_FIXED,
394 current = v3_length( vel ),
395 new_vel = vg_minf( current + amt, k_max_push_speed );
396
397 new_vel -= vg_minf(current, k_max_push_speed);
398 vel[2] -= new_vel * phys->reverse;
399 }
400
401 m3x3_mulv( phys->rb.to_world, vel, phys->rb.v );
402
403 float input = player.input_js1h->axis.value,
404 grab = player.input_grab->axis.value,
405 steer = input * (1.0f-(phys->jump+grab)*0.4f),
406 steer_scaled = vg_signf(steer) * powf(steer,2.0f) * k_steer_ground;
407
408 phys->iY -= steer_scaled * VG_TIMESTEP_FIXED;
409
410 if( !phys->jump_charge && phys->jump > 0.2f )
411 {
412 v3f jumpdir;
413
414 /* Launch more up if alignment is up else improve velocity */
415 float aup = fabsf(v3_dot( (v3f){0.0f,1.0f,0.0f}, phys->rb.up )),
416 mod = 0.5f,
417 dir = mod + aup*(1.0f-mod);
418
419 v3_copy( phys->rb.v, jumpdir );
420 v3_normalize( jumpdir );
421 v3_muls( jumpdir, 1.0f-dir, jumpdir );
422 v3_muladds( jumpdir, phys->rb.up, dir, jumpdir );
423 v3_normalize( jumpdir );
424
425 float force = k_jump_force*phys->jump;
426 v3_muladds( phys->rb.v, jumpdir, force, phys->rb.v );
427 phys->jump = 0.0f;
428
429 player.jump_time = vg.time;
430
431 /* TODO: Move to audio file */
432 audio_lock();
433 audio_player_set_flags( &audio_player_extra, AUDIO_FLAG_SPACIAL_3D );
434 audio_player_set_position( &audio_player_extra, phys->rb.co );
435 audio_player_set_vol( &audio_player_extra, 20.0f );
436 audio_player_playclip( &audio_player_extra, &audio_jumps[rand()%2] );
437 audio_unlock();
438 }
439 }
440
441 VG_STATIC void player_physics_control_grind(void)
442 {
443 struct player_phys *phys = &player.phys;
444 v2f steer = { player.input_js1h->axis.value,
445 player.input_js1v->axis.value };
446
447 float l2 = v2_length2( steer );
448 if( l2 > 1.0f )
449 v2_muls( steer, 1.0f/sqrtf(l2), steer );
450
451 phys->iY -= steer[0] * k_steer_air * VG_TIMESTEP_FIXED;
452
453 float iX = steer[1] * phys->reverse * k_steer_air * VG_TIMESTEP_FIXED;
454
455 static float siX = 0.0f;
456 siX = vg_lerpf( siX, iX, k_steer_air_lerp );
457
458 v4f rotate;
459 q_axis_angle( rotate, phys->rb.right, siX );
460 q_mul( rotate, phys->rb.q, phys->rb.q );
461
462 phys->slip = 0.0f;
463 }
464
465 /*
466 * Air control, no real physics
467 */
468 VG_STATIC void player_physics_control_air(void)
469 {
470 struct player_phys *phys = &player.phys;
471
472 m3x3_mulv( phys->vr, phys->rb.v, phys->rb.v );
473 //vg_line_cross( player.land_target, 0xff0000ff, 0.25f );
474
475 ray_hit hit;
476
477 /*
478 * Prediction
479 */
480 float pstep = VG_TIMESTEP_FIXED * 1.0f;
481 float k_bias = 0.98f;
482
483 v3f pco, pco1, pv;
484 v3_copy( phys->rb.co, pco );
485 v3_muls( phys->rb.v, 1.0f, pv );
486
487 float time_to_impact = 0.0f;
488 float limiter = 1.0f;
489
490 struct grind_edge *best_grind = NULL;
491 float closest_grind = INFINITY;
492
493 v3f target_normal = { 0.0f, 1.0f, 0.0f };
494 int has_target = 0;
495
496 for( int i=0; i<250; i++ )
497 {
498 v3_copy( pco, pco1 );
499 m3x3_mulv( phys->vr, pv, pv );
500 apply_gravity( pv, pstep );
501 v3_muladds( pco, pv, pstep, pco );
502
503 ray_hit contact;
504 v3f vdir;
505
506 v3_sub( pco, pco1, vdir );
507 contact.dist = v3_length( vdir );
508 v3_divs( vdir, contact.dist, vdir);
509
510 v3f c0, c1;
511 struct grind_edge *ge = player_grind_collect_edge( pco, pco1,
512 c0, c1, 0.4f );
513
514 if( ge && (v3_dot((v3f){0.0f,1.0f,0.0f},vdir) < -0.2f ) )
515 {
516 vg_line( ge->p0, ge->p1, 0xff0000ff );
517 vg_line_cross( pco, 0xff0000ff, 0.25f );
518 has_target = 1;
519 break;
520 }
521
522 float orig_dist = contact.dist;
523 if( ray_world( pco1, vdir, &contact ) )
524 {
525 v3_copy( contact.normal, target_normal );
526 has_target = 1;
527 time_to_impact += (contact.dist/orig_dist)*pstep;
528 vg_line_cross( contact.pos, 0xffff0000, 0.25f );
529 break;
530 }
531 time_to_impact += pstep;
532 }
533
534 if( has_target )
535 {
536 float angle = v3_dot( phys->rb.up, target_normal );
537 v3f axis;
538 v3_cross( phys->rb.up, target_normal, axis );
539
540 limiter = vg_minf( 5.0f, time_to_impact )/5.0f;
541 limiter = 1.0f-limiter;
542 limiter *= limiter;
543 limiter = 1.0f-limiter;
544
545 if( fabsf(angle) < 0.99f )
546 {
547 v4f correction;
548 q_axis_angle( correction, axis,
549 acosf(angle)*(1.0f-limiter)*3.0f*VG_TIMESTEP_FIXED );
550 q_mul( correction, phys->rb.q, phys->rb.q );
551 }
552 }
553
554 v2f steer = { player.input_js1h->axis.value,
555 player.input_js1v->axis.value };
556
557 float l2 = v2_length2( steer );
558 if( l2 > 1.0f )
559 v2_muls( steer, 1.0f/sqrtf(l2), steer );
560
561 phys->iY -= steer[0] * k_steer_air * VG_TIMESTEP_FIXED;
562
563 float iX = steer[1] *
564 phys->reverse * k_steer_air * limiter * VG_TIMESTEP_FIXED;
565
566 static float siX = 0.0f;
567 siX = vg_lerpf( siX, iX, k_steer_air_lerp );
568
569 v4f rotate;
570 q_axis_angle( rotate, phys->rb.right, siX );
571 q_mul( rotate, phys->rb.q, phys->rb.q );
572
573 #if 0
574 v2f target = {0.0f,0.0f};
575 v2_muladds( target, (v2f){ vg_get_axis("grabh"), vg_get_axis("grabv") },
576 phys->grab, target );
577 #endif
578 }
579
580 VG_STATIC void player_walk_update_collision(void)
581 {
582 struct player_phys *phys = &player.phys;
583 float h0 = 0.3f,
584 h1 = 0.9f;
585
586 rigidbody *rbf = &player.collide_front,
587 *rbb = &player.collide_back;
588
589 v3_add( phys->rb.co, (v3f){0.0f,h0,0.0f}, rbf->co );
590 v3_add( phys->rb.co, (v3f){0.0f,h1,0.0f}, rbb->co );
591 v3_copy( rbf->co, rbf->to_world[3] );
592 v3_copy( rbb->co, rbb->to_world[3] );
593 m4x3_invert_affine( rbf->to_world, rbf->to_local );
594 m4x3_invert_affine( rbb->to_world, rbb->to_local );
595
596 rb_update_bounds( rbf );
597 rb_update_bounds( rbb );
598 }
599
600 VG_STATIC void player_integrate(void);
601 /*
602 * Entire Walking physics model
603 * TODO: sleep when under certain velotiy
604 */
605 VG_STATIC void player_walk_physics(void)
606 {
607 struct player_phys *phys = &player.phys;
608 rigidbody *rbf = &player.collide_front,
609 *rbb = &player.collide_back;
610
611 m3x3_identity( player.collide_front.to_world );
612 m3x3_identity( player.collide_back.to_world );
613
614 v3_zero( phys->rb.w );
615 q_axis_angle( phys->rb.q, (v3f){0.0f,1.0f,0.0f}, -player.angles[0] );
616
617 rb_ct manifold[64];
618 int len;
619
620 v3f forward_dir = { sinf(player.angles[0]),0.0f,-cosf(player.angles[0]) };
621 v3f right_dir = { -forward_dir[2], 0.0f, forward_dir[0] };
622
623 v2f walk = { player.input_walkh->axis.value,
624 player.input_walkv->axis.value };
625
626 if( freecam )
627 v2_zero( walk );
628
629 if( v2_length2(walk) > 0.001f )
630 v2_normalize_clamp( walk );
631
632 if( phys->in_air )
633 {
634 player_walk_update_collision();
635 rb_debug( rbf, 0xff0000ff );
636 rb_debug( rbb, 0xff0000ff );
637
638 /* allow player to accelerate a bit */
639 v3f walk_3d;
640 v3_muls( forward_dir, walk[1], walk_3d );
641 v3_muladds( walk_3d, right_dir, walk[0], walk_3d );
642
643 float current_vel = fabsf(v3_dot( walk_3d, phys->rb.v )),
644 new_vel = current_vel + VG_TIMESTEP_FIXED*k_air_accelerate,
645 clamped_new = vg_clampf( new_vel, 0.0f, k_walkspeed ),
646 vel_diff = vg_maxf( 0.0f, clamped_new - current_vel );
647
648 v3_muladds( phys->rb.v, right_dir, walk[0] * vel_diff, phys->rb.v );
649 v3_muladds( phys->rb.v, forward_dir, walk[1] * vel_diff, phys->rb.v );
650
651
652 len = 0;
653 len += rb_sphere_scene( rbf, &world.rb_geo, manifold+len );
654 len += rb_sphere_scene( rbb, &world.rb_geo, manifold+len );
655 rb_presolve_contacts( manifold, len );
656
657 for( int i=0; i<len; i++ )
658 {
659 struct contact *ct = &manifold[i];
660 if( v3_dot( ct->n, (v3f){0.0f,1.0f,0.0f} ) > 0.5f )
661 phys->in_air = 0;
662 }
663
664 for( int j=0; j<5; j++ )
665 {
666 for( int i=0; i<len; i++ )
667 {
668 struct contact *ct = &manifold[i];
669
670 /*normal */
671 float vn = -v3_dot( phys->rb.v, ct->n );
672 vn += ct->bias;
673
674 float temp = ct->norm_impulse;
675 ct->norm_impulse = vg_maxf( temp + vn, 0.0f );
676 vn = ct->norm_impulse - temp;
677
678 v3f impulse;
679 v3_muls( ct->n, vn, impulse );
680
681 v3_add( impulse, phys->rb.v, phys->rb.v );
682
683 /* friction */
684 for( int j=0; j<2; j++ )
685 {
686 float f = k_friction * ct->norm_impulse,
687 vt = v3_dot( phys->rb.v, ct->t[j] ),
688 lambda = -vt;
689
690 float temp = ct->tangent_impulse[j];
691 ct->tangent_impulse[j] = vg_clampf( temp + lambda, -f, f );
692 lambda = ct->tangent_impulse[j] - temp;
693
694 v3_muladds( phys->rb.v, ct->t[j], lambda, phys->rb.v );
695 }
696 }
697 }
698
699 player_integrate();
700 }
701 else
702 {
703 player.walk = v2_length( walk );
704
705 if( player.input_walk->button.value )
706 v2_muls( walk, 0.5f, walk );
707
708 v2_muls( walk, k_walkspeed * VG_TIMESTEP_FIXED, walk );
709
710 v3f walk_apply;
711 v3_zero( walk_apply );
712
713 /* Do XY translation */
714 v3_muladds( walk_apply, right_dir, walk[0], walk_apply );
715 v3_muladds( walk_apply, forward_dir, walk[1], walk_apply );
716 v3_add( walk_apply, phys->rb.co, phys->rb.co );
717 v3_divs( walk_apply, VG_TIMESTEP_FIXED, phys->rb.v );
718
719 /* Directly resolve collisions */
720 player_walk_update_collision();
721 rb_debug( rbf, 0xffffff00 );
722 rb_debug( rbb, 0xffffff00 );
723
724 len = 0;
725 len += rb_sphere_scene( rbf, &world.rb_geo, manifold+len );
726 len += rb_sphere_scene( rbb, &world.rb_geo, manifold+len );
727
728 v3f dt;
729 v3_zero( dt );
730 for( int j=0; j<3; j++ )
731 {
732 for( int i=0; i<len; i++ )
733 {
734 struct contact *ct = &manifold[i];
735
736 float p = vg_maxf( 0.0f, ct->p - 0.00f ),
737 cur = vg_clampf( v3_dot( ct->n, dt ), 0.0f, p );
738 v3_muladds( dt, ct->n, (p - cur) * 0.333333333f, dt );
739 }
740 }
741 v3_add( dt, phys->rb.co, phys->rb.co );
742
743 if( len )
744 {
745 struct world_material *surface_mat = world_contact_material(manifold);
746 player.surface_prop = surface_mat->info.surface_prop;
747 }
748
749 /* jump */
750 if( player.input_jump->button.value )
751 {
752 phys->rb.v[1] = 5.0f;
753 phys->in_air = 1;
754 return;
755 }
756
757 /* if we've put us in the air, step down slowly */
758 phys->in_air = 1;
759 float max_dist = 0.3f,
760 start_y = phys->rb.co[1];
761
762 for( int j=0; j<8; j++ )
763 {
764 for( int i=0; i<len; i++ )
765 {
766 struct contact *ct = &manifold[i];
767 if( v3_dot( ct->n, (v3f){0.0f,1.0f,0.0f} ) > 0.5f )
768 {
769 phys->in_air = 0;
770 if( j == 0 )
771 return;
772
773 v3f dt;
774 v3_zero( dt );
775 for( int j=0; j<3; j++ )
776 {
777 for( int i=0; i<len; i++ )
778 {
779 struct contact *ct = &manifold[i];
780
781 float p = vg_maxf( 0.0f, ct->p - 0.0025f ),
782 cur = vg_clampf( v3_dot( ct->n, dt ), 0.0f, p );
783 v3_muladds( dt, ct->n, (p - cur) * 0.333333333f, dt );
784 }
785 }
786 v3_add( dt, phys->rb.co, phys->rb.co );
787 return;
788 }
789 }
790
791 phys->rb.co[1] -= max_dist * 0.125f;
792
793 player_walk_update_collision();
794 len = 0;
795 len += rb_sphere_scene( rbf, &world.rb_geo, manifold+len );
796 len += rb_sphere_scene( rbb, &world.rb_geo, manifold+len );
797 }
798
799 /* Transitioning into air mode */
800 phys->rb.co[1] = start_y;
801 }
802 }
803
804 VG_STATIC void player_grind(void)
805 {
806 struct player_phys *phys = &player.phys;
807
808 v3f closest;
809 int idx = bh_closest_point( world.grind_bh, phys->rb.co, closest, INFINITY );
810 if( idx == -1 )
811 return;
812
813 struct grind_edge *edge = &world.grind_edges[ idx ];
814
815 vg_line( phys->rb.co, closest, 0xff000000 );
816 vg_line_cross( closest, 0xff000000, 0.3f );
817 vg_line( edge->p0, edge->p1, 0xff000000 );
818
819 v3f grind_delta;
820 v3_sub( closest, phys->rb.co, grind_delta );
821
822 float p = v3_dot( phys->rb.forward, grind_delta );
823 v3_muladds( grind_delta, phys->rb.forward, -p, grind_delta );
824
825 float a = vg_maxf( 0.0f, 4.0f-v3_dist2( closest, phys->rb.co ) );
826 v3_muladds( phys->rb.v, grind_delta, a*0.2f, phys->rb.v );
827 }
828
829 VG_STATIC int player_update_grind_collision( rb_ct *contact )
830 {
831 struct player_phys *phys = &player.phys;
832
833 v3f p0, p1, c0, c1;
834 v3_muladds( phys->rb.co, phys->rb.forward, 0.5f, p0 );
835 v3_muladds( phys->rb.co, phys->rb.forward, -0.5f, p1 );
836 v3_muladds( p0, phys->rb.up, 0.125f, p0 );
837 v3_muladds( p1, phys->rb.up, 0.125f, p1 );
838
839 float const k_r = 0.25f;
840 struct grind_edge *closest_edge = player_grind_collect_edge( p0, p1,
841 c0, c1, k_r );
842
843
844 vg_line( p0, p1, 0xff0000ff );
845
846 if( closest_edge )
847 {
848 vg_line_cross( c0, 0xff000000, 0.1f );
849 vg_line_cross( c1, 0xff000000, 0.1f );
850 vg_line( c0, c1, 0xff000000 );
851
852 v3f delta;
853 v3_sub( c1, c0, delta );
854
855 if( v3_dot( delta, phys->rb.up ) > 0.0001f )
856 {
857 contact->p = v3_length( delta );
858 contact->type = k_contact_type_edge;
859 contact->element_id = 0;
860 v3_copy( c1, contact->co );
861 contact->rba = &player.phys.rb;
862 contact->rbb = &world.rb_geo;
863
864 v3f edge_dir, axis_dir;
865 v3_sub( closest_edge->p1, closest_edge->p0, edge_dir );
866 v3_normalize( edge_dir );
867 v3_cross( (v3f){0.0f,1.0f,0.0f}, edge_dir, axis_dir );
868 v3_cross( edge_dir, axis_dir, contact->n );
869
870 #if 0
871 vg_info( "%f %f\n", v3_length( contact->n ), contact->p );
872 #endif
873
874 return 1;
875 }
876 else
877 return -1;
878 }
879
880 return 0;
881 }
882
883 /* Manifold must be able to hold at least 64 elements */
884 VG_STATIC int player_update_collision_manifold( rb_ct *manifold )
885 {
886 struct player_phys *phys = &player.phys;
887
888 phys->rise = vg_lerpf( phys->rise, phys->in_air? -0.25f: 0.0f,
889 VG_TIMESTEP_FIXED );
890
891 rigidbody *rbf = &player.collide_front,
892 *rbb = &player.collide_back;
893
894 m3x3_copy( phys->rb.to_world, player.collide_front.to_world );
895 m3x3_copy( phys->rb.to_world, player.collide_back.to_world );
896
897 player.air_blend = vg_lerpf( player.air_blend, phys->in_air, 0.1f );
898 float h = player.air_blend*0.0f;
899
900 m4x3_mulv( phys->rb.to_world, (v3f){0.0f,h,-k_board_length}, rbf->co );
901 v3_copy( rbf->co, rbf->to_world[3] );
902 m4x3_mulv( phys->rb.to_world, (v3f){0.0f,h, k_board_length}, rbb->co );
903 v3_copy( rbb->co, rbb->to_world[3] );
904
905 m4x3_invert_affine( rbf->to_world, rbf->to_local );
906 m4x3_invert_affine( rbb->to_world, rbb->to_local );
907
908 rb_update_bounds( rbf );
909 rb_update_bounds( rbb );
910
911 rb_debug( rbf, 0xff00ffff );
912 rb_debug( rbb, 0xffffff00 );
913
914 int len_f = 0,
915 len_b = 0;
916
917 len_f = rb_sphere_scene( rbf, &world.rb_geo, manifold );
918 rb_manifold_filter_coplanar( manifold, len_f, 0.05f );
919 if( len_f > 1 )
920 {
921 rb_manifold_filter_backface( manifold, len_f );
922 rb_manifold_filter_joint_edges( manifold, len_f, 0.05f );
923 rb_manifold_filter_pairs( manifold, len_f, 0.05f );
924 }
925 int new_len_f = rb_manifold_apply_filtered( manifold, len_f );
926 if( len_f && !new_len_f )
927 len_f = 1;
928 else
929 len_f = new_len_f;
930
931 rb_ct *man_b = &manifold[len_f];
932 len_b = rb_sphere_scene( rbb, &world.rb_geo, man_b );
933 rb_manifold_filter_coplanar( man_b, len_b, 0.05f );
934 if( len_b > 1 )
935 {
936 rb_manifold_filter_backface( man_b, len_b );
937 rb_manifold_filter_joint_edges( man_b, len_b, 0.05f );
938 rb_manifold_filter_pairs( man_b, len_b, 0.05f );
939 }
940 int new_len_b = rb_manifold_apply_filtered( man_b, len_b );
941 if( len_b && !new_len_b )
942 len_b = 1;
943 else
944 len_b = new_len_b;
945 #if 0
946 /*
947 * Preprocess collision points, and create a surface picture.
948 * we want contacts that are within our 'capsule's internal line to be
949 * clamped so that they face the line and do not oppose, to stop the
950 * player hanging up on stuff
951 */
952 for( int i=0; i<len; i++ )
953 {
954 v3f dfront, dback;
955 v3_sub( manifold[i].co, rbf->co, dfront );
956 v3_sub( manifold[i].co, rbb->co, dback );
957
958 if( (v3_dot( dfront, phys->rb.forward ) < -0.02f) &&
959 (v3_dot( dback, phys->rb.forward ) > 0.02f))
960 {
961 float p = v3_dot( manifold[i].n, phys->rb.forward );
962 v3_muladds( manifold[i].n, phys->rb.forward, -p, manifold[i].n );
963 v3_normalize( manifold[i].n );
964 }
965 }
966 #endif
967
968 return len_f + len_b;
969 }
970
971 VG_STATIC void player_adhere_ground( rb_ct *manifold, int len )
972 {
973 struct player_phys *phys = &player.phys;
974 int was_in_air = phys->in_air;
975
976 v3f surface_avg;
977 v3_zero( surface_avg );
978
979 if( len == 0 )
980 {
981 phys->lift_frames ++;
982
983 if( phys->lift_frames >= 8 )
984 phys->in_air = 1;
985 }
986 else
987 {
988 for( int i=0; i<len; i++ )
989 v3_add( surface_avg, manifold[i].n, surface_avg );
990 v3_normalize( surface_avg );
991
992 if( v3_dot( phys->rb.v, surface_avg ) > 0.7f )
993 {
994 phys->lift_frames ++;
995
996 if( phys->lift_frames >= 8 )
997 phys->in_air = 1;
998 }
999 else
1000 {
1001 phys->in_air = 0;
1002 phys->lift_frames = 0;
1003 v3f projected, axis;
1004
1005 float const DOWNFORCE = -k_downforce*VG_TIMESTEP_FIXED;
1006 v3_muladds( phys->rb.v, phys->rb.up, DOWNFORCE, phys->rb.v );
1007
1008 float d = v3_dot( phys->rb.forward, surface_avg );
1009 v3_muladds( surface_avg, phys->rb.forward, -d, projected );
1010 v3_normalize( projected );
1011
1012 float angle = v3_dot( phys->rb.up, projected );
1013 v3_cross( phys->rb.up, projected, axis );
1014
1015 v3f p0, p1;
1016 v3_add( phys->rb.co, projected, p0 );
1017 v3_add( phys->rb.co, phys->rb.up, p1 );
1018 vg_line( phys->rb.co, p0, 0xff00ff00 );
1019 vg_line( phys->rb.co, p1, 0xff000fff );
1020
1021 if( fabsf(angle) < 0.999f )
1022 {
1023 v4f correction;
1024 q_axis_angle( correction, axis,
1025 acosf(angle)*4.0f*VG_TIMESTEP_FIXED );
1026 q_mul( correction, phys->rb.q, phys->rb.q );
1027 }
1028 }
1029 }
1030
1031 if( !was_in_air && phys->in_air )
1032 player_start_air();
1033 }
1034
1035 VG_STATIC void player_collision_response( rb_ct *manifold, int len )
1036 {
1037 struct player_phys *phys = &player.phys;
1038
1039 for( int j=0; j<5; j++ )
1040 {
1041 for( int i=0; i<len; i++ )
1042 {
1043 struct contact *ct = &manifold[i];
1044
1045 v3f dv, delta;
1046 v3_sub( ct->co, phys->rb.co, delta );
1047 v3_cross( phys->rb.w, delta, dv );
1048 v3_add( phys->rb.v, dv, dv );
1049
1050 float vn = -v3_dot( dv, ct->n );
1051 vn += ct->bias;
1052
1053 float temp = ct->norm_impulse;
1054 ct->norm_impulse = vg_maxf( temp + vn, 0.0f );
1055 vn = ct->norm_impulse - temp;
1056
1057 v3f impulse;
1058 v3_muls( ct->n, vn, impulse );
1059
1060 if( fabsf(v3_dot( impulse, phys->rb.forward )) > 10.0f ||
1061 fabsf(v3_dot( impulse, phys->rb.up )) > 50.0f )
1062 {
1063 player_kill();
1064 return;
1065 }
1066
1067 v3_add( impulse, phys->rb.v, phys->rb.v );
1068 v3_cross( delta, impulse, impulse );
1069
1070 /*
1071 * W Impulses are limited to the Y and X axises, we don't really want
1072 * roll angular velocities being included.
1073 *
1074 * Can also tweak the resistance of each axis here by scaling the wx,wy
1075 * components.
1076 */
1077
1078 float wy = v3_dot( phys->rb.up, impulse ) * 0.8f,
1079 wx = v3_dot( phys->rb.right, impulse )*1.0f;
1080
1081 v3_muladds( phys->rb.w, phys->rb.up, wy, phys->rb.w );
1082 v3_muladds( phys->rb.w, phys->rb.right, wx, phys->rb.w );
1083 }
1084 }
1085 }
1086
1087 VG_STATIC void player_save_frame(void)
1088 {
1089 player.phys_gate_frame = player.phys;
1090 }
1091
1092 VG_STATIC void player_restore_frame(void)
1093 {
1094 player.phys = player.phys_gate_frame;
1095 rb_update_transform( &player.phys.rb );
1096 }
1097
1098 VG_STATIC void player_integrate(void)
1099 {
1100 struct player_phys *phys = &player.phys;
1101 apply_gravity( phys->rb.v, VG_TIMESTEP_FIXED );
1102 v3_muladds( phys->rb.co, phys->rb.v, VG_TIMESTEP_FIXED, phys->rb.co );
1103 }
1104
1105 VG_STATIC void player_do_motion(void)
1106 {
1107 struct player_phys *phys = &player.phys;
1108
1109 if( world.water.enabled )
1110 {
1111 if( (phys->rb.co[1] < 0.0f) && !player.is_dead )
1112 {
1113 audio_lock();
1114 audio_player_set_flags( &audio_player_extra, AUDIO_FLAG_SPACIAL_3D );
1115 audio_player_set_position( &audio_player_extra, phys->rb.co );
1116 audio_player_set_vol( &audio_player_extra, 20.0f );
1117 audio_player_playclip( &audio_player_extra, &audio_splash );
1118 audio_unlock();
1119
1120 player_kill();
1121 }
1122 }
1123
1124 v3f prevco;
1125 v3_copy( phys->rb.co, prevco );
1126
1127 if( phys->on_board )
1128 {
1129 rb_ct manifold[72];
1130 int len = player_update_collision_manifold( manifold );
1131 int grind_col = player_update_grind_collision( &manifold[len] );
1132
1133 static int _grind_col_pre = 0;
1134
1135 if( grind_col )
1136 {
1137 phys->grind = 1;
1138 v3f up = { 0.0f, 1.0f, 0.0f };
1139 float angle = v3_dot( phys->rb.up, up );
1140
1141 if( fabsf(angle) < 0.99f )
1142 {
1143 v3f axis;
1144 v3_cross( phys->rb.up, up, axis );
1145
1146 v4f correction;
1147 q_axis_angle( correction, axis,
1148 VG_TIMESTEP_FIXED * 10.0f * acosf(angle) );
1149 q_mul( correction, phys->rb.q, phys->rb.q );
1150 }
1151
1152 float const DOWNFORCE = -k_downforce*1.2f*VG_TIMESTEP_FIXED;
1153 v3_muladds( phys->rb.v, manifold[len].n, DOWNFORCE, phys->rb.v );
1154 m3x3_identity( phys->vr );
1155 m3x3_identity( phys->vr_pstep );
1156
1157 if( !_grind_col_pre )
1158 {
1159 audio_lock();
1160 audio_player_set_flags( &audio_player_extra,
1161 AUDIO_FLAG_SPACIAL_3D );
1162 audio_player_set_position( &audio_player_extra, phys->rb.co );
1163 audio_player_set_vol( &audio_player_extra, 20.0f );
1164 audio_player_playclip( &audio_player_extra, &audio_board[5] );
1165 audio_unlock();
1166 }
1167 }
1168 else
1169 {
1170 phys->grind = 0;
1171 player_adhere_ground( manifold, len );
1172
1173 if( _grind_col_pre )
1174 {
1175 audio_lock();
1176 audio_player_set_flags( &audio_player_extra,
1177 AUDIO_FLAG_SPACIAL_3D );
1178 audio_player_set_position( &audio_player_extra, phys->rb.co );
1179 audio_player_set_vol( &audio_player_extra, 20.0f );
1180 audio_player_playclip( &audio_player_extra, &audio_board[6] );
1181 audio_unlock();
1182 }
1183 }
1184
1185 _grind_col_pre = grind_col;
1186
1187 rb_presolve_contacts( manifold, len+ VG_MAX(0,grind_col) );
1188 player_collision_response( manifold, len+ VG_MAX(0,grind_col) );
1189
1190 player_physics_control_passive();
1191
1192 if( grind_col )
1193 {
1194 phys->in_air = 0;
1195 player_physics_control_grind();
1196 }
1197 else
1198 {
1199 if( phys->in_air )
1200 player_physics_control_air();
1201 else
1202 player_physics_control();
1203 }
1204
1205 player_integrate();
1206 }
1207 else
1208 player_walk_physics();
1209
1210
1211 /* Real angular velocity integration */
1212 v3_lerp( phys->rb.w, (v3f){0.0f,0.0f,0.0f}, 0.125f*0.5f, phys->rb.w );
1213 if( v3_length2( phys->rb.w ) > 0.0f )
1214 {
1215 v4f rotation;
1216 v3f axis;
1217 v3_copy( phys->rb.w, axis );
1218
1219 float mag = v3_length( axis );
1220 v3_divs( axis, mag, axis );
1221 q_axis_angle( rotation, axis, mag*k_rb_delta );
1222 q_mul( rotation, phys->rb.q, phys->rb.q );
1223 }
1224
1225 /* Faux angular velocity */
1226 v4f rotate;
1227
1228 float lerpq = phys->in_air? 0.04f: 0.3f;
1229 phys->siY = vg_lerpf( phys->siY, phys->iY, lerpq );
1230
1231 q_axis_angle( rotate, phys->rb.up, phys->siY );
1232 q_mul( rotate, phys->rb.q, phys->rb.q );
1233 phys->iY = 0.0f;
1234
1235 /*
1236 * Gate intersection, by tracing a line over the gate planes
1237 */
1238 for( int i=0; i<world.gate_count; i++ )
1239 {
1240 struct route_gate *rg = &world.gates[i];
1241 teleport_gate *gate = &rg->gate;
1242
1243 if( gate_intersect( gate, phys->rb.co, prevco ) )
1244 {
1245 m4x3_mulv( gate->transport, phys->rb.co, phys->rb.co );
1246 m3x3_mulv( gate->transport, phys->rb.v, phys->rb.v );
1247 m3x3_mulv( gate->transport, phys->vl, phys->vl );
1248 m3x3_mulv( gate->transport, phys->v_last, phys->v_last );
1249 m3x3_mulv( gate->transport, phys->m, phys->m );
1250 m3x3_mulv( gate->transport, phys->bob, phys->bob );
1251
1252 /* Pre-emptively edit the camera matrices so that the motion vectors
1253 * are correct */
1254 m4x3f transport_i;
1255 m4x4f transport_4;
1256 m4x3_invert_affine( gate->transport, transport_i );
1257 m4x3_expand( transport_i, transport_4 );
1258 m4x4_mul( main_camera.mtx.pv, transport_4, main_camera.mtx.pv );
1259 m4x4_mul( main_camera.mtx.v, transport_4, main_camera.mtx.v );
1260
1261 v4f transport_rotation;
1262 m3x3_q( gate->transport, transport_rotation );
1263 q_mul( transport_rotation, phys->rb.q, phys->rb.q );
1264
1265 world_routes_activate_gate( i );
1266
1267 if( !phys->on_board )
1268 {
1269 v3f fwd_dir = {cosf(player.angles[0]),
1270 0.0f,
1271 sinf(player.angles[0])};
1272 m3x3_mulv( gate->transport, fwd_dir, fwd_dir );
1273
1274 player.angles[0] = atan2f( fwd_dir[2], fwd_dir[0] );
1275 }
1276
1277 player.rewind_length = 0;
1278 player.rewind_total_length = 0.0f;
1279 player.rewind_incrementer = 10000;
1280 player_save_frame();
1281
1282 audio_lock();
1283 audio_play_oneshot( &audio_gate_pass, 1.0f );
1284 audio_unlock();
1285 break;
1286 }
1287 }
1288
1289 rb_update_transform( &phys->rb );
1290 }
1291
1292 VG_STATIC void player_freecam(void)
1293 {
1294 player_mouseview();
1295
1296 float movespeed = fc_speed * VG_TIMESTEP_FIXED;
1297 v3f lookdir = { 0.0f, 0.0f, -1.0f },
1298 sidedir = { 1.0f, 0.0f, 0.0f };
1299
1300 m3x3_mulv( main_camera.transform, lookdir, lookdir );
1301 m3x3_mulv( main_camera.transform, sidedir, sidedir );
1302
1303 static v3f move_vel = { 0.0f, 0.0f, 0.0f };
1304
1305 v2f steer = { player.input_js1h->axis.value,
1306 player.input_js1v->axis.value };
1307
1308 v3_muladds( move_vel, sidedir, movespeed*steer[0], move_vel );
1309 v3_muladds( move_vel, lookdir, -movespeed*steer[1], move_vel );
1310
1311 v3_muls( move_vel, 0.7f, move_vel );
1312 v3_add( move_vel, player.camera_pos, player.camera_pos );
1313 }
1314
1315 VG_STATIC int reset_player( int argc, char const *argv[] )
1316 {
1317 struct player_phys *phys = &player.phys;
1318 struct respawn_point *rp = NULL, *r;
1319
1320 if( argc == 1 )
1321 {
1322 for( int i=0; i<world.spawn_count; i++ )
1323 {
1324 r = &world.spawns[i];
1325 if( !strcmp( r->name, argv[0] ) )
1326 {
1327 rp = r;
1328 break;
1329 }
1330 }
1331
1332 if( !rp )
1333 vg_warn( "No spawn named '%s'\n", argv[0] );
1334 }
1335
1336 if( !rp )
1337 {
1338 float min_dist = INFINITY;
1339
1340 for( int i=0; i<world.spawn_count; i++ )
1341 {
1342 r = &world.spawns[i];
1343 float d = v3_dist2( r->co, phys->rb.co );
1344
1345 vg_info( "Dist %s : %f\n", r->name, d );
1346 if( d < min_dist )
1347 {
1348 min_dist = d;
1349 rp = r;
1350 }
1351 }
1352 }
1353
1354 if( !rp )
1355 {
1356 vg_error( "No spawn found\n" );
1357 vg_info( "Player position: %f %f %f\n", player.phys.rb.co[0],
1358 player.phys.rb.co[1],
1359 player.phys.rb.co[2] );
1360 vg_info( "Player velocity: %f %f %f\n", player.phys.rb.v[0],
1361 player.phys.rb.v[1],
1362 player.phys.rb.v[2] );
1363
1364 if( !world.spawn_count )
1365 return 0;
1366
1367 rp = &world.spawns[0];
1368 }
1369
1370 player.is_dead = 0;
1371
1372 m3x3f the_long_way;
1373 q_m3x3( rp->q, the_long_way );
1374
1375 v3f delta = {1.0f,0.0f,0.0f};
1376 m3x3_mulv( the_long_way, delta, delta );
1377
1378 player.angles[0] = atan2f( delta[0], -delta[2] );
1379 player.angles[1] = -asinf( delta[1] );
1380
1381
1382 v4_copy( rp->q, phys->rb.q );
1383 v3_copy( rp->co, phys->rb.co );
1384 v3_zero( phys->rb.v );
1385
1386 phys->vswitch = 1.0f;
1387 phys->slip_last = 0.0f;
1388 phys->in_air = 1;
1389 phys->on_board = 0;
1390 m3x3_identity( phys->vr );
1391
1392 player.mdl.shoes[0] = 1;
1393 player.mdl.shoes[1] = 1;
1394
1395 rb_update_transform( &phys->rb );
1396 player_save_frame();
1397 return 1;
1398 }
1399
1400 #endif /* PLAYER_PHYSICS_H */