From 631126494c4527bbd982692ec551a43606c228a2 Mon Sep 17 00:00:00 2001 From: cim Date: Tue, 2 Jul 2013 18:43:59 +0100 Subject: [PATCH] Upgrade world-space coordinate vectors to double-precision (issue #22) Introduces several bugs, probably. --- GNUmakefile | 1 + src/Core/CollisionRegion.h | 6 +- src/Core/CollisionRegion.m | 45 +- src/Core/Entities/DockEntity.m | 102 ++--- src/Core/Entities/DustEntity.m | 5 +- src/Core/Entities/Entity.h | 16 +- src/Core/Entities/Entity.m | 50 ++- src/Core/Entities/OOExhaustPlumeEntity.h | 2 +- src/Core/Entities/OOExhaustPlumeEntity.m | 12 +- src/Core/Entities/OOFlashEffectEntity.h | 2 +- src/Core/Entities/OOFlashEffectEntity.m | 10 +- src/Core/Entities/OOLaserShotEntity.m | 6 +- src/Core/Entities/OOLightParticleEntity.m | 8 +- src/Core/Entities/OOParticleSystem.h | 2 +- src/Core/Entities/OOParticleSystem.m | 12 +- src/Core/Entities/OOPlasmaBurstEntity.h | 2 +- src/Core/Entities/OOPlasmaBurstEntity.m | 2 +- src/Core/Entities/OOPlasmaShotEntity.h | 2 +- src/Core/Entities/OOPlasmaShotEntity.m | 2 +- src/Core/Entities/OOSparkEntity.h | 2 +- src/Core/Entities/OOSparkEntity.m | 2 +- src/Core/Entities/OOSunEntity.m | 6 +- src/Core/Entities/OOVisualEffectEntity.m | 20 +- src/Core/Entities/PlanetEntity.m | 8 +- src/Core/Entities/PlayerEntity.h | 4 +- src/Core/Entities/PlayerEntity.m | 72 +-- .../Entities/PlayerEntityLegacyScriptEngine.m | 21 +- src/Core/Entities/ShipEntity.h | 30 +- src/Core/Entities/ShipEntity.m | 338 +++++++------- src/Core/Entities/ShipEntityAI.m | 103 +++-- src/Core/Entities/ShipEntityLoadRestore.m | 6 +- src/Core/Entities/StationEntity.h | 4 +- src/Core/Entities/StationEntity.m | 10 +- src/Core/Entities/WormholeEntity.h | 2 +- src/Core/Entities/WormholeEntity.m | 14 +- src/Core/HeadUpDisplay.m | 14 +- src/Core/OOBoundingBox.h | 1 + src/Core/OOCollectionExtractors.h | 6 + src/Core/OOCollectionExtractors.m | 57 +++ src/Core/OOHPVector.h | 354 +++++++++++++++ src/Core/OOHPVector.m | 132 ++++++ src/Core/OOMaths.h | 3 + src/Core/OOMatrix.h | 9 +- src/Core/OOMatrix.m | 21 +- src/Core/OOQuaternion.h | 2 + src/Core/OOQuaternion.m | 5 + src/Core/OOStringParsing.h | 1 + src/Core/OOStringParsing.m | 12 + src/Core/OOVector.h | 5 +- src/Core/OOVector.m | 5 +- src/Core/Scripting/OOJSEntity.m | 4 +- src/Core/Scripting/OOJSPopulatorDefinition.h | 4 +- src/Core/Scripting/OOJSPopulatorDefinition.m | 6 +- src/Core/Scripting/OOJSShip.m | 8 +- src/Core/Scripting/OOJSSystem.m | 12 +- src/Core/Scripting/OOJSVector.m | 6 +- src/Core/Universe.h | 42 +- src/Core/Universe.m | 422 +++++++++--------- 58 files changed, 1338 insertions(+), 722 deletions(-) create mode 100644 src/Core/OOHPVector.h create mode 100644 src/Core/OOHPVector.m diff --git a/GNUmakefile b/GNUmakefile index 8afe5545..fc5a2b6c 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -235,6 +235,7 @@ OOLITE_MATHS_FILES = \ CollisionRegion.m \ OOMeshToOctreeConverter.m \ Octree.m \ + OOHPVector.m \ OOMatrix.m \ OOQuaternion.m \ OOVector.m \ diff --git a/src/Core/CollisionRegion.h b/src/Core/CollisionRegion.h index 53948001..f3df2f92 100644 --- a/src/Core/CollisionRegion.h +++ b/src/Core/CollisionRegion.h @@ -42,7 +42,7 @@ MA 02110-1301, USA. BOOL isUniverse; // if YES location is origin and radius is 0.0f int crid; // identifier - Vector location; // center of the region + HPVector location; // center of the region GLfloat radius; // inner radius of the region GLfloat border_radius; // additiønal, border radius of the region (typically 32km or some value > the scanner range) @@ -61,10 +61,10 @@ MA 02110-1301, USA. } - (id) initAsUniverse; -- (id) initAtLocation:(Vector) locn withRadius:(GLfloat) rad withinRegion:(CollisionRegion*) otherRegion; +- (id) initAtLocation:(HPVector) locn withRadius:(GLfloat) rad withinRegion:(CollisionRegion*) otherRegion; - (void) clearSubregions; -- (void) addSubregionAtPosition:(Vector) pos withRadius:(GLfloat) rad; +- (void) addSubregionAtPosition:(HPVector) pos withRadius:(GLfloat) rad; // collision checking - (void) clearEntityList; diff --git a/src/Core/CollisionRegion.m b/src/Core/CollisionRegion.m index f4cd7e07..3ae75195 100644 --- a/src/Core/CollisionRegion.m +++ b/src/Core/CollisionRegion.m @@ -34,9 +34,9 @@ MA 02110-1301, USA. #import "OODebugFlags.h" -static BOOL positionIsWithinRegion(Vector position, CollisionRegion *region); -static BOOL sphereIsWithinRegion(Vector position, GLfloat rad, CollisionRegion *region); -static BOOL positionIsWithinBorders(Vector position, CollisionRegion *region); +static BOOL positionIsWithinRegion(HPVector position, CollisionRegion *region); +static BOOL sphereIsWithinRegion(HPVector position, GLfloat rad, CollisionRegion *region); +static BOOL positionIsWithinBorders(HPVector position, CollisionRegion *region); @implementation CollisionRegion @@ -74,7 +74,7 @@ static int crid_counter = 1; } -- (id) initAtLocation:(Vector)locn withRadius:(GLfloat)rad withinRegion:(CollisionRegion *)otherRegion +- (id) initAtLocation:(HPVector)locn withRadius:(GLfloat)rad withinRegion:(CollisionRegion *)otherRegion { if ((self = [self init])) { @@ -109,7 +109,7 @@ static int crid_counter = 1; } -- (void) addSubregionAtPosition:(Vector)pos withRadius:(GLfloat)rad +- (void) addSubregionAtPosition:(HPVector)pos withRadius:(GLfloat)rad { // check if this can be fitted within any of the subregions // @@ -139,12 +139,12 @@ static int crid_counter = 1; // update routines to check if a position is within the radius or within its borders // -static BOOL positionIsWithinRegion(Vector position, CollisionRegion *region) +static BOOL positionIsWithinRegion(HPVector position, CollisionRegion *region) { if (region == nil) return NO; if (region->isUniverse) return YES; - Vector loc = region->location; + HPVector loc = region->location; GLfloat r1 = region->radius; if ((position.x < loc.x - r1)||(position.x > loc.x + r1)|| @@ -158,12 +158,12 @@ static BOOL positionIsWithinRegion(Vector position, CollisionRegion *region) } -static BOOL sphereIsWithinRegion(Vector position, GLfloat rad, CollisionRegion *region) +static BOOL sphereIsWithinRegion(HPVector position, GLfloat rad, CollisionRegion *region) { if (region == nil) return NO; if (region->isUniverse) return YES; - Vector loc = region->location; + HPVector loc = region->location; GLfloat r1 = region->radius; if ((position.x - rad < loc.x - r1)||(position.x + rad > loc.x + r1)|| @@ -177,12 +177,12 @@ static BOOL sphereIsWithinRegion(Vector position, GLfloat rad, CollisionRegion * } -static BOOL positionIsWithinBorders(Vector position, CollisionRegion *region) +static BOOL positionIsWithinBorders(HPVector position, CollisionRegion *region) { if (region == nil) return NO; if (region->isUniverse) return YES; - Vector loc = region->location; + HPVector loc = region->location; GLfloat r1 = region->radius + region->border_radius; if ((position.x < loc.x - r1)||(position.x > loc.x + r1)|| @@ -229,7 +229,7 @@ static BOOL positionIsWithinBorders(Vector position, CollisionRegion *region) - (BOOL) checkEntity:(Entity *)ent { - Vector position = ent->position; + HPVector position = ent->position; // check subregions CollisionRegion *sub = nil; @@ -264,7 +264,7 @@ static BOOL positionIsWithinBorders(Vector position, CollisionRegion *region) // According to Shark, when this was in Universe this was where Oolite spent most time! // Entity *e1, *e2; - Vector p1, p2; + HPVector p1; double dist2, r1, r2, r0, min_dist2; unsigned i; Entity *entities_to_test[n_entities]; @@ -323,10 +323,9 @@ static BOOL positionIsWithinBorders(Vector position, CollisionRegion *region) { checks_this_tick++; - p2 = vector_subtract(e2->position, p1); r2 = e2->collision_radius; r0 = r1 + r2; - dist2 = magnitude2(p2); + dist2 = HPdistance2(e2->position, p1); min_dist2 = r0 * r0; if (dist2 < PROXIMITY_WARN_DISTANCE2 * min_dist2) { @@ -451,15 +450,15 @@ static BOOL entityByEntityOcclusionToValue(Entity *e1, Entity *e2, OOSunEntity * // return NO; // things already /in/ shade can't shade things more. // // check projected sizes of discs - GLfloat d2_sun = distance2(e1->position, the_sun->position); - GLfloat d2_e2sun = distance2(e2->position, the_sun->position); + GLfloat d2_sun = HPdistance2(e1->position, the_sun->position); + GLfloat d2_e2sun = HPdistance2(e2->position, the_sun->position); if (d2_e2sun > d2_sun) { // you are nearer the sun than the potential occluder, so it can't shade you return NO; } - GLfloat d2_e2 = distance2( e1->position, e2->position); + GLfloat d2_e2 = HPdistance2( e1->position, e2->position); GLfloat cr_sun = the_sun->collision_radius; GLfloat cr2_sun_scaled = cr_sun * cr_sun * d2_e2 / d2_sun; @@ -475,13 +474,13 @@ static BOOL entityByEntityOcclusionToValue(Entity *e1, Entity *e2, OOSunEntity * // find the difference between the angles subtended by occluder and sun float theta_diff = asin(cr_e2 / sqrt(d2_e2)) - asin(cr_sun / sqrt(d2_sun)); - Vector p_sun = the_sun->position; - Vector p_e2 = e2->position; - Vector p_e1 = e1->position; - Vector v_sun = vector_subtract(p_sun, p_e1); + HPVector p_sun = the_sun->position; + HPVector p_e2 = e2->position; + HPVector p_e1 = e1->position; + Vector v_sun = HPVectorToVector(HPvector_subtract(p_sun, p_e1)); v_sun = vector_normal_or_zbasis(v_sun); - Vector v_e2 = vector_subtract(p_e2, p_e1); + Vector v_e2 = HPVectorToVector(HPvector_subtract(p_e2, p_e1)); v_e2 = vector_normal_or_xbasis(v_e2); float phi = acos(dot_product(v_sun, v_e2)); // angle between sun and e2 from e1's viewpoint diff --git a/src/Core/Entities/DockEntity.m b/src/Core/Entities/DockEntity.m index 538a6266..71ac0141 100644 --- a/src/Core/Entities/DockEntity.m +++ b/src/Core/Entities/DockEntity.m @@ -108,7 +108,7 @@ MA 02110-1301, USA. if (isDockingStation && [player status] == STATUS_IN_FLIGHT && [player getDockingClearanceStatus] >= DOCKING_CLEARANCE_STATUS_REQUESTED) { - if (magnitude2(vector_subtract([player position], [self absolutePositionForSubentity])) > 2250000) // within 1500m of the dock + if (HPmagnitude2(HPvector_subtract([player position], [self absolutePositionForSubentity])) > 2250000) // within 1500m of the dock { [station sendExpandedMessage:@"[station-docking-clearance-abort-cancelled]" toShip:player]; [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE]; @@ -275,19 +275,19 @@ MA 02110-1301, USA. NSNumber *shipID = [NSNumber numberWithUnsignedShort:ship_id]; StationEntity *station = (StationEntity *)[self parentEntity]; - Vector launchVector = vector_forward_from_quaternion(quaternion_multiply(orientation, [station orientation])); - Vector temp = (fabs(launchVector.x) < 0.8)? make_vector(1,0,0) : make_vector(0,1,0); - temp = cross_product(launchVector, temp); // 90 deg to launchVector & temp - Vector vi = cross_product(launchVector, temp); - Vector vj = cross_product(launchVector, vi); - Vector vk = launchVector; + HPVector launchVector = HPvector_forward_from_quaternion(quaternion_multiply(orientation, [station orientation])); + HPVector temp = (fabs(launchVector.x) < 0.8)? make_HPvector(1,0,0) : make_HPvector(0,1,0); + temp = HPcross_product(launchVector, temp); // 90 deg to launchVector & temp + HPVector vi = HPcross_product(launchVector, temp); + HPVector vj = HPcross_product(launchVector, vi); + HPVector vk = launchVector; // check if this is a new ship on approach // if (![shipsOnApproach objectForKey:shipID]) { - Vector delta = vector_subtract([ship position], [self absolutePositionForSubentity]); - float ship_distance = magnitude(delta); + HPVector delta = HPvector_subtract([ship position], [self absolutePositionForSubentity]); + float ship_distance = HPmagnitude(delta); if (ship_distance > SCANNER_MAX_RANGE) { @@ -300,12 +300,12 @@ MA 02110-1301, USA. if (ship_distance < 1000.0 + [station collisionRadius] + ship->collision_radius) // too close - back off return OOMakeDockingInstructions(station, [self absolutePositionForSubentity], 0, 5000, @"BACK_OFF", nil, NO); - float dot = dot_product(launchVector, delta); + float dot = HPdot_product(launchVector, delta); if (dot < 0) // approaching from the wrong side of the station - construct a vector to the side of the station. { - Vector approachVector = cross_product(vector_normal(delta), launchVector); - approachVector = cross_product(launchVector, approachVector); // vector, 90 degr rotated from launchVector towards target. - return OOMakeDockingInstructions(station, OOVectorTowards([self absolutePositionForSubentity], approachVector, [station collisionRadius] + 5000) , 0, 1000, @"APPROACH", nil, NO); + HPVector approachVector = HPcross_product(HPvector_normal(delta), launchVector); + approachVector = HPcross_product(launchVector, approachVector); // vector, 90 degr rotated from launchVector towards target. + return OOMakeDockingInstructions(station, OOHPVectorTowards([self absolutePositionForSubentity], approachVector, [station collisionRadius] + 5000) , 0, 1000, @"APPROACH", nil, NO); } if (ship_distance > 12500.0) @@ -342,22 +342,22 @@ MA 02110-1301, USA. float rangeAdvised = [nextCoords oo_floatForKey:@"range"]; // calculate world coordinates from relative coordinates - Vector rel_coords; - rel_coords.x = [nextCoords oo_floatForKey:@"rx"]; - rel_coords.y = [nextCoords oo_floatForKey:@"ry"]; - rel_coords.z = [nextCoords oo_floatForKey:@"rz"]; - Vector coords = [self absolutePositionForSubentity]; + HPVector rel_coords; + rel_coords.x = [nextCoords oo_doubleForKey:@"rx"]; + rel_coords.y = [nextCoords oo_doubleForKey:@"ry"]; + rel_coords.z = [nextCoords oo_doubleForKey:@"rz"]; + HPVector coords = [self absolutePositionForSubentity]; coords.x += rel_coords.x * vi.x + rel_coords.y * vj.x + rel_coords.z * vk.x; coords.y += rel_coords.x * vi.y + rel_coords.y * vj.y + rel_coords.z * vk.y; coords.z += rel_coords.x * vi.z + rel_coords.y * vj.z + rel_coords.z * vk.z; // check if the ship is at the control point double max_allowed_range = 2.0 * rangeAdvised + ship->collision_radius; // maximum distance permitted from control point - twice advised range - Vector delta = vector_subtract(ship->position, coords); + HPVector delta = HPvector_subtract(ship->position, coords); - if (magnitude2(delta) > max_allowed_range * max_allowed_range) // too far from the coordinates - do not remove them from the stack! + if (HPmagnitude2(delta) > max_allowed_range * max_allowed_range) // too far from the coordinates - do not remove them from the stack! { - if ((docking_stage == 1) &&(magnitude2(delta) < 1000000.0)) // 1km*1km + if ((docking_stage == 1) &&(HPmagnitude2(delta) < 1000000.0)) // 1km*1km speedAdvised *= 0.5; // half speed return OOMakeDockingInstructions(station, coords, speedAdvised, rangeAdvised, @"APPROACH_COORDINATES", nil, NO); @@ -450,11 +450,11 @@ MA 02110-1301, USA. NSNumber *shipID = [NSNumber numberWithUnsignedShort:[ship universalID]]; StationEntity *station = (StationEntity *)[self parentEntity]; - Vector launchVector = vector_forward_from_quaternion(quaternion_multiply(orientation, [station orientation])); - Vector temp = (fabs(launchVector.x) < 0.8)? make_vector(1,0,0) : make_vector(0,1,0); - temp = cross_product(launchVector, temp); // 90 deg to launchVector & temp - Vector rightVector = cross_product(launchVector, temp); - Vector upVector = cross_product(launchVector, rightVector); + HPVector launchVector = HPvector_forward_from_quaternion(quaternion_multiply(orientation, [station orientation])); + HPVector temp = (fabs(launchVector.x) < 0.8)? make_HPvector(1,0,0) : make_HPvector(0,1,0); + temp = HPcross_product(launchVector, temp); // 90 deg to launchVector & temp + HPVector rightVector = HPcross_product(launchVector, temp); + HPVector upVector = HPcross_product(launchVector, rightVector); // will select a direction for offset based on the entity personality (was ship ID) int offset_id = [ship entityPersonalityInt] & 0xf; // 16 point compass @@ -462,18 +462,18 @@ MA 02110-1301, USA. float s = sin(offset_id * M_PI * ONE_EIGHTH); // test if this points at the ship - Vector point1 = [self absolutePositionForSubentity]; + HPVector point1 = [self absolutePositionForSubentity]; point1.x += launchVector.x * corridor_offset[corridor_count - 1]; point1.y += launchVector.x * corridor_offset[corridor_count - 1]; point1.z += launchVector.x * corridor_offset[corridor_count - 1]; - Vector alt1 = point1; + HPVector alt1 = point1; point1.x += c * upVector.x * corridor_offset[corridor_count - 1] + s * rightVector.x * corridor_offset[corridor_count - 1]; point1.y += c * upVector.y * corridor_offset[corridor_count - 1] + s * rightVector.y * corridor_offset[corridor_count - 1]; point1.z += c * upVector.z * corridor_offset[corridor_count - 1] + s * rightVector.z * corridor_offset[corridor_count - 1]; alt1.x -= c * upVector.x * corridor_offset[corridor_count - 1] + s * rightVector.x * corridor_offset[corridor_count - 1]; alt1.y -= c * upVector.y * corridor_offset[corridor_count - 1] + s * rightVector.y * corridor_offset[corridor_count - 1]; alt1.z -= c * upVector.z * corridor_offset[corridor_count - 1] + s * rightVector.z * corridor_offset[corridor_count - 1]; - if (distance2(alt1, ship->position) < distance2(point1, ship->position)) + if (HPdistance2(alt1, ship->position) < HPdistance2(point1, ship->position)) { s = -s; c = -c; // turn 180 degrees @@ -578,7 +578,7 @@ MA 02110-1301, USA. if ([player status] == STATUS_IN_FLIGHT && [player getDockingClearanceStatus] >= DOCKING_CLEARANCE_STATUS_REQUESTED) { - if (magnitude2(vector_subtract([player position], [self absolutePositionForSubentity])) > 2250000) // within 1500m of the dock + if (HPmagnitude2(HPvector_subtract([player position], [self absolutePositionForSubentity])) > 2250000) // within 1500m of the dock { [[self parentEntity] sendExpandedMessage:@"[station-docking-clearance-abort-cancelled]" toShip:player]; [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE]; @@ -661,7 +661,7 @@ MA 02110-1301, USA. Vector vj = vector_up_from_quaternion(q0); Vector vk = vector_forward_from_quaternion(q0); - Vector port_pos = [self absolutePositionForSubentity]; + HPVector port_pos = [self absolutePositionForSubentity]; BoundingBox shipbb = [ship boundingBox]; BoundingBox arbb = [ship findBoundingBoxRelativeToPosition: port_pos InVectors: vi : vj : vk]; @@ -710,9 +710,9 @@ MA 02110-1301, USA. { // launch-only dock: will collide! [ship takeScrapeDamage: 5 * [UNIVERSE getTimeDelta]*[ship flightSpeed] from:station]; // and bounce - Vector rel = vector_subtract([ship position],port_pos); - rel = vector_multiply_scalar(vector_normal(rel),[ship flightSpeed]*0.4); - [ship adjustVelocity:rel]; + HPVector rel = HPvector_subtract([ship position],port_pos); + rel = HPvector_multiply_scalar(HPvector_normal(rel),[ship flightSpeed]*0.4); + [ship adjustVelocity:HPVectorToVector(rel)]; if (arbb.max.z < 0.0) { // give some warning before exploding... @@ -762,7 +762,7 @@ MA 02110-1301, USA. } // adjust the ship back to the center of the port - Vector pos = [ship position]; + HPVector pos = [ship position]; pos.x -= delta.y * vj.x + delta.x * vi.x; pos.y -= delta.y * vj.y + delta.x * vi.y; pos.z -= delta.y * vj.z + delta.x * vi.z; @@ -823,7 +823,7 @@ MA 02110-1301, USA. BoundingBox bb = [ship boundingBox]; StationEntity *station = (StationEntity *)[self parentEntity]; - Vector launchPos = [self absolutePositionForSubentity]; + HPVector launchPos = [self absolutePositionForSubentity]; Vector launchVel = [station velocity]; double launchSpeed = 0.5 * [ship maxFlightSpeed]; if ([station maxFlightSpeed] > 0 && [station flightSpeed] > 0) // is self a carrier in flight. @@ -948,24 +948,24 @@ MA 02110-1301, USA. for (i = 0; (i < ship_count)&&(isEmpty); i++) { ShipEntity* ship = (ShipEntity*)my_entities[i]; - double d2 = distance2([station position], [ship position]); + double d2 = HPdistance2([station position], [ship position]); if ((ship != station) && (d2 < 25000000)&&([ship status] != STATUS_DOCKED)) // within 5km { - Vector ppos = [self absolutePositionForSubentity]; - d2 = distance2(ppos, ship->position); + HPVector ppos = [self absolutePositionForSubentity]; + d2 = HPdistance2(ppos, ship->position); if (d2 < 4000000) // within 2km of the port entrance { Quaternion q1 = [station orientation]; q1 = quaternion_multiply([self orientation], q1); // - Vector v_out = vector_forward_from_quaternion(q1); - Vector r_pos = make_vector(ship->position.x - ppos.x, ship->position.y - ppos.y, ship->position.z - ppos.z); + HPVector v_out = HPvector_forward_from_quaternion(q1); + HPVector r_pos = make_HPvector(ship->position.x - ppos.x, ship->position.y - ppos.y, ship->position.z - ppos.z); if (r_pos.x||r_pos.y||r_pos.z) - r_pos = vector_normal(r_pos); + r_pos = HPvector_normal(r_pos); else r_pos.z = 1.0; // - double vdp = dot_product(v_out, r_pos); //== cos of the angle between r_pos and v_out + double vdp = HPdot_product(v_out, r_pos); //== cos of the angle between r_pos and v_out // if (vdp > 0.86) { @@ -1007,15 +1007,15 @@ MA 02110-1301, USA. for (i = 0; i < ship_count; i++) { ShipEntity *ship = (ShipEntity*)my_entities[i]; - double d2 = distance2([station position], [ship position]); + double d2 = HPdistance2([station position], [ship position]); if ((ship != station)&&(d2 < 25000000)&&([ship status] != STATUS_DOCKED)) // within 5km { - Vector ppos = [self absolutePositionForSubentity]; + HPVector ppos = [self absolutePositionForSubentity]; float time_out = -15.00; // 15 secs do { isClear = YES; - d2 = distance2(ppos, ship->position); + d2 = HPdistance2(ppos, ship->position); if (d2 < 4000000) // within 2km of the port entrance { Quaternion q1 = [station orientation]; @@ -1040,8 +1040,8 @@ MA 02110-1301, USA. } if (time_out > 0) { - Vector v1 = vector_forward_from_quaternion(orientation); - Vector spos = ship->position; + HPVector v1 = HPvector_forward_from_quaternion(orientation); + HPVector spos = ship->position; spos.x += 3000.0 * v1.x; spos.y += 3000.0 * v1.y; spos.z += 3000.0 * v1.z; [ship setPosition:spos]; // move 3km out of the way } @@ -1071,15 +1071,15 @@ MA 02110-1301, USA. port_dimensions = make_vector(bb.max.x - bb.min.x, bb.max.y - bb.min.y, bb.max.z - bb.min.z); } - Vector vk = vector_forward_from_quaternion(orientation); + HPVector vk = HPvector_forward_from_quaternion(orientation); BoundingBox stbb = [station boundingBox]; - Vector start = position; + HPVector start = position; while ((start.x > stbb.min.x)&&(start.x < stbb.max.x) && (start.y > stbb.min.y)&&(start.y < stbb.max.y) && (start.z > stbb.min.z)&&(start.z < stbb.max.z) ) { - start = vector_add(start, vector_multiply_scalar(vk, port_dimensions.z)); + start = HPvector_add(start, HPvector_multiply_scalar(vk, port_dimensions.z)); } port_corridor = start.z - position.z; diff --git a/src/Core/Entities/DustEntity.m b/src/Core/Entities/DustEntity.m index 06392bfe..4cd15ad4 100644 --- a/src/Core/Entities/DustEntity.m +++ b/src/Core/Entities/DustEntity.m @@ -163,7 +163,7 @@ enum zero_distance = 0.0; - Vector offset = [player position]; + Vector offset = HPVectorToVector([player position]); GLfloat half_scale = DUST_SCALE * 0.50; int vi; for (vi = 0; vi < DUST_N_PARTICLES; vi++) @@ -231,7 +231,8 @@ enum - (Vector) offsetPlayerPosition { - return vector_subtract([PLAYER position], make_vector(DUST_SCALE * 0.5f, DUST_SCALE * 0.5f, DUST_SCALE * 0.5f)); + // used as shader uniform, so needs to be low precision + return vector_subtract(HPVectorToVector([PLAYER position]), make_vector(DUST_SCALE * 0.5f, DUST_SCALE * 0.5f, DUST_SCALE * 0.5f)); } diff --git a/src/Core/Entities/Entity.h b/src/Core/Entities/Entity.h index 12bfb5a7..a0569bfe 100644 --- a/src/Core/Entities/Entity.h +++ b/src/Core/Entities/Entity.h @@ -108,7 +108,7 @@ enum OOScanClass GLfloat cam_zero_distance; GLfloat no_draw_distance; // 10 km initially GLfloat collision_radius; - Vector position; + HPVector position; // use high-precision vectors for global position Quaternion orientation; int zero_index; @@ -127,7 +127,7 @@ enum OOScanClass CollisionRegion *collisionRegion; // initially nil - then maintained @protected - Vector lastPosition; + HPVector lastPosition; Quaternion lastOrientation; GLfloat distanceTravelled; // set to zero initially @@ -197,12 +197,14 @@ enum OOScanClass - (ShipEntity *) parentEntity; // owner if self is subentity of owner, otherwise nil. - (ShipEntity *) rootShipEntity; // like parentEntity, but recursive. -- (void) setPosition:(Vector)posn; -- (void) setPositionX:(GLfloat)x y:(GLfloat)y z:(GLfloat)z; -- (Vector) position; +- (void) setPosition:(HPVector)posn; +- (void) setPositionX:(OOHPScalar)x y:(OOHPScalar)y z:(OOHPScalar)z; +- (HPVector) position; +// gets a low-position relative vector +- (Vector) vectorTo:(Entity *)entity; -- (Vector) absolutePositionForSubentity; -- (Vector) absolutePositionForSubentityOffset:(Vector) offset; +- (HPVector) absolutePositionForSubentity; +- (HPVector) absolutePositionForSubentityOffset:(HPVector) offset; - (double) zeroDistance; - (double) camZeroDistance; diff --git a/src/Core/Entities/Entity.m b/src/Core/Entities/Entity.m index 7e8feec1..defd8b53 100644 --- a/src/Core/Entities/Entity.m +++ b/src/Core/Entities/Entity.m @@ -73,7 +73,7 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. orientation = kIdentityQuaternion; rotMatrix = kIdentityMatrix; - position = kZeroVector; + position = kZeroHPVector; no_draw_distance = 100000.0; // 10 km @@ -114,7 +114,7 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. - (NSString *)descriptionComponents { - return [NSString stringWithFormat:@"position: %@ scanClass: %@ status: %@", VectorDescription([self position]), OOStringFromScanClass([self scanClass]), OOStringFromEntityStatus([self status])]; + return [NSString stringWithFormat:@"position: %@ scanClass: %@ status: %@", HPVectorDescription([self position]), OOStringFromScanClass([self scanClass]), OOStringFromEntityStatus([self status])]; } @@ -593,26 +593,32 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. } -- (Vector) position +- (HPVector) position { return position; } // Exposed to uniform bindings. +// so needs to remain at OpenGL precision levels - (Vector) relativePosition { - return vector_subtract([self position], [PLAYER position]); + return HPVectorToVector(HPvector_subtract([self position], [PLAYER position])); +} + +- (Vector) vectorTo:(Entity *)entity +{ + return HPVectorToVector(HPvector_subtract([entity position], [self position])); } -- (void) setPosition:(Vector) posn +- (void) setPosition:(HPVector) posn { position = posn; } -- (void) setPositionX:(GLfloat)x y:(GLfloat)y z:(GLfloat)z +- (void) setPositionX:(OOHPScalar)x y:(OOHPScalar)y z:(OOHPScalar)z { position.x = x; position.y = y; @@ -620,21 +626,21 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. } -- (Vector) absolutePositionForSubentity +- (HPVector) absolutePositionForSubentity { - return [self absolutePositionForSubentityOffset:kZeroVector]; + return [self absolutePositionForSubentityOffset:kZeroHPVector]; } -- (Vector) absolutePositionForSubentityOffset:(Vector) offset +- (HPVector) absolutePositionForSubentityOffset:(HPVector) offset { - Vector abspos = vector_add(position, OOVectorMultiplyMatrix(offset, rotMatrix)); + HPVector abspos = HPvector_add(position, OOHPVectorMultiplyMatrix(offset, rotMatrix)); Entity *last = nil; Entity *father = [self parentEntity]; while (father != nil && father != last) { - abspos = vector_add(OOVectorMultiplyMatrix(abspos, [father drawRotationMatrix]), [father position]); + abspos = HPvector_add(OOHPVectorMultiplyMatrix(abspos, [father drawRotationMatrix]), [father position]); last = father; if (![last isSubEntity]) break; father = [father owner]; @@ -818,8 +824,8 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. - (void) moveForward:(double)amount { - Vector forward = vector_multiply_scalar(vector_forward_from_quaternion(orientation), amount); - position = vector_add(position, forward); + HPVector forward = HPvector_multiply_scalar(HPvector_forward_from_quaternion(orientation), amount); + position = HPvector_add(position, forward); distanceTravelled += amount; } @@ -839,14 +845,14 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. - (OOMatrix) transformationMatrix { OOMatrix result = rotMatrix; - return OOMatrixTranslate(result, position); + return OOMatrixHPTranslate(result, position); } - (OOMatrix) drawTransformationMatrix { OOMatrix result = rotMatrix; - return OOMatrixTranslate(result, position); + return OOMatrixHPTranslate(result, position); } @@ -885,22 +891,22 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. } else { - zero_distance = distance2(PLAYER->position, position); - cam_zero_distance = distance2([PLAYER viewpointPosition], position); + zero_distance = HPdistance2(PLAYER->position, position); + cam_zero_distance = HPdistance2([PLAYER viewpointPosition], position); } } else { - zero_distance = magnitude2(position); + zero_distance = HPmagnitude2(position); cam_zero_distance = zero_distance; } if ([self status] != STATUS_COCKPIT_DISPLAY) { - position = vector_add(position, vector_multiply_scalar(velocity, delta_t)); + position = HPvector_add(position, HPvector_multiply_scalar(vectorToHPVector(velocity), delta_t)); } - hasMoved = !vector_equal(position, lastPosition); + hasMoved = !HPvector_equal(position, lastPosition); hasRotated = !quaternion_equal(orientation, lastOrientation); lastPosition = position; lastOrientation = orientation; @@ -961,7 +967,7 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. OOLog(@"dumpState.entity", @"Universal ID: %u", universalID); OOLog(@"dumpState.entity", @"Scan class: %@", OOStringFromScanClass(scanClass)); OOLog(@"dumpState.entity", @"Status: %@", OOStringFromEntityStatus([self status])); - OOLog(@"dumpState.entity", @"Position: %@", VectorDescription(position)); + OOLog(@"dumpState.entity", @"Position: %@", HPVectorDescription(position)); OOLog(@"dumpState.entity", @"Orientation: %@", QuaternionDescription(orientation)); OOLog(@"dumpState.entity", @"Distance travelled: %g", distanceTravelled); OOLog(@"dumpState.entity", @"Energy: %g of %g", energy, maxEnergy); @@ -1026,7 +1032,7 @@ static NSString * const kOOLogEntityUpdateError = @"entity.linkedList.update. { NSString *result = [self descriptionForObjDumpBasic]; - result = [result stringByAppendingFormat:@" range: %g (visible: %@)", distance([self position], [PLAYER position]), [self isVisible] ? @"yes" : @"no"]; + result = [result stringByAppendingFormat:@" range: %g (visible: %@)", HPdistance([self position], [PLAYER position]), [self isVisible] ? @"yes" : @"no"]; return result; } diff --git a/src/Core/Entities/OOExhaustPlumeEntity.h b/src/Core/Entities/OOExhaustPlumeEntity.h index 03e2dd49..3fbaf3f8 100644 --- a/src/Core/Entities/OOExhaustPlumeEntity.h +++ b/src/Core/Entities/OOExhaustPlumeEntity.h @@ -29,7 +29,7 @@ MA 02110-1301, USA. typedef struct { double timeframe; // universal time for this frame - Vector position; + HPVector position; Quaternion orientation; Vector k; // direction vectors } Frame; diff --git a/src/Core/Entities/OOExhaustPlumeEntity.m b/src/Core/Entities/OOExhaustPlumeEntity.m index c04e83ea..8f262a0e 100644 --- a/src/Core/Entities/OOExhaustPlumeEntity.m +++ b/src/Core/Entities/OOExhaustPlumeEntity.m @@ -73,7 +73,7 @@ static OOTexture *sPlumeTexture = nil; if ((self = [super init])) { [self setOwner:ship]; - Vector pos = { [definition oo_floatAtIndex:0], [definition oo_floatAtIndex:1], [definition oo_floatAtIndex:2] }; + HPVector pos = { [definition oo_floatAtIndex:0], [definition oo_floatAtIndex:1], [definition oo_floatAtIndex:2] }; [self setPosition:pos]; Vector scale = { [definition oo_floatAtIndex:3], [definition oo_floatAtIndex:4], [definition oo_floatAtIndex:5] }; _exhaustScale = scale; @@ -147,7 +147,7 @@ static OOTexture *sPlumeTexture = nil; if ((int)(ranrot_rand() % 25) < dam - 75) flare_factor = 0.0; - Vector currentPos = ship->position; + HPVector currentPos = ship->position; Vector vfwd = [ship forwardVector]; GLfloat spd = 0.5 * [ship flightSpeed]; vfwd = vector_multiply_scalar(vfwd, spd); @@ -156,7 +156,7 @@ static OOTexture *sPlumeTexture = nil; vi = master_i; vj = [ship upVector]; vk = [ship forwardVector]; - zero.position = make_vector(currentPos.x + vi.x * position.x + vj.x * position.y + vk.x * position.z, + zero.position = make_HPvector(currentPos.x + vi.x * position.x + vj.x * position.y + vk.x * position.z, currentPos.y + vi.y * position.x + vj.y * position.y + vk.y * position.z, currentPos.z + vi.z * position.x + vj.z * position.y + vk.z * position.z); @@ -451,7 +451,7 @@ GLfloat pA[6] = { 0.01, 0.0, 2.0, 4.0, 6.0, 10.0 }; // phase adjustments ShipEntity *ship = [self owner]; // Absolute position of self - Vector framePos = OOVectorMultiplyMatrix([self position], [ship drawTransformationMatrix]); + HPVector framePos = OOHPVectorMultiplyMatrix([self position], [ship drawTransformationMatrix]); Frame frame = { [UNIVERSE getTime], framePos, [ship normalOrientation], [ship upVector] }; _track[_nextFrame] = frame; @@ -496,7 +496,7 @@ GLfloat pA[6] = { 0.01, 0.0, 2.0, 4.0, 6.0, 10.0 }; // phase adjustments // interpolate double f1 = 1.0 - f0; - Vector posn; + HPVector posn; posn.x = f0 * frame_zero.position.x + f1 * frame_one.position.x; posn.y = f0 * frame_zero.position.y + f1 * frame_one.position.y; posn.z = f0 * frame_zero.position.z + f1 * frame_one.position.z; @@ -526,7 +526,7 @@ GLfloat pA[6] = { 0.01, 0.0, 2.0, 4.0, 6.0, 10.0 }; // phase adjustments _track[_nextFrame] = frame; _nextFrame = (_nextFrame + 1) % kExhaustFrameCount;*/ _nextFrame = 0; - Vector framePos = OOVectorMultiplyMatrix([self position], [[self owner] drawTransformationMatrix]); + HPVector framePos = OOHPVectorMultiplyMatrix([self position], [[self owner] drawTransformationMatrix]); uint8_t i; for (i = 0; i < kExhaustFrameCount; i++) { diff --git a/src/Core/Entities/OOFlashEffectEntity.h b/src/Core/Entities/OOFlashEffectEntity.h index 69a95442..d84728c2 100644 --- a/src/Core/Entities/OOFlashEffectEntity.h +++ b/src/Core/Entities/OOFlashEffectEntity.h @@ -36,7 +36,7 @@ MA 02110-1301, USA. } + (instancetype) explosionFlashFromEntity:(Entity *)entity; -+ (instancetype) laserFlashWithPosition:(Vector)position velocity:(Vector)vel color:(OOColor *)color; ++ (instancetype) laserFlashWithPosition:(HPVector)position velocity:(Vector)vel color:(OOColor *)color; + (void) setUpTexture; diff --git a/src/Core/Entities/OOFlashEffectEntity.m b/src/Core/Entities/OOFlashEffectEntity.m index 4d281f10..4eba13fa 100644 --- a/src/Core/Entities/OOFlashEffectEntity.m +++ b/src/Core/Entities/OOFlashEffectEntity.m @@ -44,7 +44,7 @@ static OOTexture *sFlashTexture = nil; @interface OOFlashEffectEntity (Private) // Designated initializer. -- (id) initWithPosition:(Vector)pos size:(float)size color:(OOColor *)color duration:(float)duration; +- (id) initWithPosition:(HPVector)pos size:(float)size color:(OOColor *)color duration:(float)duration; + (void) resetGraphicsState; @@ -55,7 +55,7 @@ static OOTexture *sFlashTexture = nil; @implementation OOFlashEffectEntity -- (id) initExplosionFlashWithPosition:(Vector)pos velocity:(Vector)vel size:(float)size +- (id) initExplosionFlashWithPosition:(HPVector)pos velocity:(Vector)vel size:(float)size { if ((self = [self initWithPosition:pos size:size color:[OOColor whiteColor] duration:kExplosionFlashDuration])) { @@ -66,7 +66,7 @@ static OOTexture *sFlashTexture = nil; } -- (id) initLaserFlashWithPosition:(Vector)pos velocity:(Vector)vel color:(OOColor *)color +- (id) initLaserFlashWithPosition:(HPVector)pos velocity:(Vector)vel color:(OOColor *)color { if ((self = [self initWithPosition:pos size:kLaserFlashInitialSize color:color duration:kLaserFlashDuration])) { @@ -82,13 +82,13 @@ static OOTexture *sFlashTexture = nil; } -+ (instancetype) laserFlashWithPosition:(Vector)pos velocity:(Vector)vel color:(OOColor *)color ++ (instancetype) laserFlashWithPosition:(HPVector)pos velocity:(Vector)vel color:(OOColor *)color { return [[[self alloc] initLaserFlashWithPosition:pos velocity:vel color:color] autorelease]; } -- (id) initWithPosition:(Vector)pos size:(float)size color:(OOColor *)color duration:(float)duration +- (id) initWithPosition:(HPVector)pos size:(float)size color:(OOColor *)color duration:(float)duration { if ((self = [super initWithDiameter:size])) { diff --git a/src/Core/Entities/OOLaserShotEntity.m b/src/Core/Entities/OOLaserShotEntity.m index a4e2a83e..b956f460 100644 --- a/src/Core/Entities/OOLaserShotEntity.m +++ b/src/Core/Entities/OOLaserShotEntity.m @@ -65,12 +65,12 @@ static OOTexture *sShotTexture2 = nil; if (ship == srcEntity) { // main laser offset - position = vector_add([ship position], OOVectorMultiplyMatrix(offset, [ship drawRotationMatrix])); + position = HPvector_add([ship position], vectorToHPVector(OOVectorMultiplyMatrix(offset, [ship drawRotationMatrix]))); } else { // subentity laser - position = [srcEntity absolutePositionForSubentityOffset:middle]; + position = [srcEntity absolutePositionForSubentityOffset:vectorToHPVector(middle)]; } Quaternion q = kIdentityQuaternion; @@ -162,7 +162,7 @@ static OOTexture *sShotTexture2 = nil; velocity in -[Entity update:], which is considered sufficient for NPC ships. */ - position = vector_add([ship position], OOVectorMultiplyMatrix(_offset, [ship drawRotationMatrix])); + position = HPvector_add([ship position], vectorToHPVector(OOVectorMultiplyMatrix(_offset, [ship drawRotationMatrix]))); [self setOrientation:quaternion_multiply(_relOrientation, [ship normalOrientation])]; } diff --git a/src/Core/Entities/OOLightParticleEntity.m b/src/Core/Entities/OOLightParticleEntity.m index ad3dbc4b..2ffe35d2 100644 --- a/src/Core/Entities/OOLightParticleEntity.m +++ b/src/Core/Entities/OOLightParticleEntity.m @@ -109,7 +109,7 @@ static OOTexture *sBlobTexture = nil; OO_ENTER_OPENGL(); - Entity *father = [self owner]; + /*Entity *father = [self owner]; Entity *last = nil; Vector abspos = position; @@ -121,11 +121,13 @@ static OOTexture *sBlobTexture = nil; if (![father isSubEntity]) break; father = [father owner]; - } + }*/ + HPVector abspos = [self absolutePositionForSubentity]; OOMatrix temp_matrix = OOMatrixLoadGLMatrix(GL_MODELVIEW_MATRIX); OOGL(glPopMatrix()); OOGL(glPushMatrix()); // restore zero! - GLTranslateOOVector(abspos); // move to absolute position + // HPVect: camera-relative + GLTranslateOOVector(HPVectorToVector(abspos)); // move to absolute position [self drawImmediate:immediate translucent:translucent]; diff --git a/src/Core/Entities/OOParticleSystem.h b/src/Core/Entities/OOParticleSystem.h index 14361bee..578ea489 100644 --- a/src/Core/Entities/OOParticleSystem.h +++ b/src/Core/Entities/OOParticleSystem.h @@ -56,7 +56,7 @@ enum /* Initialize particle effect with particles flying out randomly. Initiali _particleSize[] is equal to speed. */ -- (id) initWithPosition:(Vector)position +- (id) initWithPosition:(HPVector)position velocity:(Vector)velocity count:(unsigned)count minSpeed:(float)minSpeed diff --git a/src/Core/Entities/OOParticleSystem.m b/src/Core/Entities/OOParticleSystem.m index 3ed385d4..f76d45d2 100644 --- a/src/Core/Entities/OOParticleSystem.m +++ b/src/Core/Entities/OOParticleSystem.m @@ -47,7 +47,7 @@ MA 02110-1301, USA. /* Initialize shared aspects of the fragburst entities. Also stashes generated particle speeds in _particleSize[] array. */ -- (id) initWithPosition:(Vector)pos +- (id) initWithPosition:(HPVector)pos velocity:(Vector)vel count:(unsigned)count minSpeed:(float)minSpeed @@ -151,8 +151,8 @@ do { \ OOGL(glEnable(GL_BLEND)); OOGL(glBlendFunc(GL_SRC_ALPHA, GL_ONE)); - Vector viewPosition = [PLAYER viewpointPosition]; - Vector selfPosition = [self position]; + HPVector viewPosition = [PLAYER viewpointPosition]; + HPVector selfPosition = [self position]; unsigned i, count = _count; Vector *particlePosition = _particlePosition; @@ -216,7 +216,7 @@ do { \ { OOGL(glPushMatrix()); GLTranslateOOVector(particlePosition[i]); - GLMultOOMatrix(OOMatrixForBillboard(vector_add(selfPosition, vector_multiply_scalar(particlePosition[i], individuality)), viewPosition)); + GLMultOOMatrix(OOMatrixForBillboard(HPvector_add(selfPosition, vectorToHPVector(vector_multiply_scalar(particlePosition[i], individuality))), viewPosition)); glColor4fv(particleColor[i]); OOGLBEGIN(GL_QUADS); @@ -254,7 +254,7 @@ do { \ @implementation OOSmallFragmentBurstEntity: OOParticleSystem -- (id) initFragmentBurstFrom:(Vector)fragPosition velocity:(Vector)fragVelocity size:(GLfloat)size +- (id) initFragmentBurstFrom:(HPVector)fragPosition velocity:(Vector)fragVelocity size:(GLfloat)size { enum { @@ -313,7 +313,7 @@ do { \ @implementation OOBigFragmentBurstEntity: OOParticleSystem -- (id) initFragmentBurstFrom:(Vector)fragPosition velocity:(Vector)fragVelocity size:(GLfloat)size +- (id) initFragmentBurstFrom:(HPVector)fragPosition velocity:(Vector)fragVelocity size:(GLfloat)size { float minSpeed = 1.0f + size * 0.5f; float maxSpeed = minSpeed * 4.0f; diff --git a/src/Core/Entities/OOPlasmaBurstEntity.h b/src/Core/Entities/OOPlasmaBurstEntity.h index 0fc2c7f1..e9014059 100644 --- a/src/Core/Entities/OOPlasmaBurstEntity.h +++ b/src/Core/Entities/OOPlasmaBurstEntity.h @@ -28,6 +28,6 @@ MA 02110-1301, USA. @interface OOPlasmaBurstEntity: OOLightParticleEntity -- (id) initWithPosition:(Vector)position; +- (id) initWithPosition:(HPVector)position; @end diff --git a/src/Core/Entities/OOPlasmaBurstEntity.m b/src/Core/Entities/OOPlasmaBurstEntity.m index cb3d762a..bac0084d 100644 --- a/src/Core/Entities/OOPlasmaBurstEntity.m +++ b/src/Core/Entities/OOPlasmaBurstEntity.m @@ -34,7 +34,7 @@ MA 02110-1301, USA. @implementation OOPlasmaBurstEntity -- (id) initWithPosition:(Vector)inPosition +- (id) initWithPosition:(HPVector)inPosition { if ((self = [super initWithDiameter:kPlasmaBurstInitialSize])) { diff --git a/src/Core/Entities/OOPlasmaShotEntity.h b/src/Core/Entities/OOPlasmaShotEntity.h index 2dbb8cdf..80905356 100644 --- a/src/Core/Entities/OOPlasmaShotEntity.h +++ b/src/Core/Entities/OOPlasmaShotEntity.h @@ -32,7 +32,7 @@ MA 02110-1301, USA. OOTimeDelta _duration; } -- (id) initWithPosition:(Vector)position +- (id) initWithPosition:(HPVector)position velocity:(Vector)velocity energy:(float)energy duration:(OOTimeDelta)duration diff --git a/src/Core/Entities/OOPlasmaShotEntity.m b/src/Core/Entities/OOPlasmaShotEntity.m index 6f631cdd..8699c5c1 100644 --- a/src/Core/Entities/OOPlasmaShotEntity.m +++ b/src/Core/Entities/OOPlasmaShotEntity.m @@ -43,7 +43,7 @@ MA 02110-1301, USA. @implementation OOPlasmaShotEntity -- (id) initWithPosition:(Vector)inPosition +- (id) initWithPosition:(HPVector)inPosition velocity:(Vector)inVelocity energy:(float)inEnergy duration:(OOTimeDelta)duration diff --git a/src/Core/Entities/OOSparkEntity.h b/src/Core/Entities/OOSparkEntity.h index 12f7e6dd..ebf9ae0f 100644 --- a/src/Core/Entities/OOSparkEntity.h +++ b/src/Core/Entities/OOSparkEntity.h @@ -33,7 +33,7 @@ MA 02110-1301, USA. GLfloat _duration, _timeRemaining; } -- (id) initWithPosition:(Vector)position +- (id) initWithPosition:(HPVector)position velocity:(Vector)velocity duration:(OOTimeDelta)duration size:(float)size diff --git a/src/Core/Entities/OOSparkEntity.m b/src/Core/Entities/OOSparkEntity.m index 606bbeb4..5b4f1ecd 100644 --- a/src/Core/Entities/OOSparkEntity.m +++ b/src/Core/Entities/OOSparkEntity.m @@ -38,7 +38,7 @@ MA 02110-1301, USA. @implementation OOSparkEntity -- (id) initWithPosition:(Vector)pos +- (id) initWithPosition:(HPVector)pos velocity:(Vector)vel duration:(OOTimeDelta)duration size:(float)size diff --git a/src/Core/Entities/OOSunEntity.m b/src/Core/Entities/OOSunEntity.m index 2befb33e..f0a7f482 100644 --- a/src/Core/Entities/OOSunEntity.m +++ b/src/Core/Entities/OOSunEntity.m @@ -171,7 +171,7 @@ MA 02110-1301, USA. - (NSString*) descriptionComponents { - NSString *result = [NSString stringWithFormat:@"ID: %u position: %@ radius: %.3fkm", [self universalID], VectorDescription([self position]), 0.001 * [self radius]]; + NSString *result = [NSString stringWithFormat:@"ID: %u position: %@ radius: %.3fkm", [self universalID], HPVectorDescription([self position]), 0.001 * [self radius]]; if ([self goneNova]) { result = [result stringByAppendingString:@" (gone nova)"]; @@ -534,10 +534,10 @@ MA 02110-1301, USA. } -- (void) setPosition:(Vector) posn +- (void) setPosition:(HPVector) posn { [super setPosition: posn]; - [UNIVERSE setMainLightPosition: posn]; + [UNIVERSE setMainLightPosition: HPVectorToVector(posn)]; } diff --git a/src/Core/Entities/OOVisualEffectEntity.m b/src/Core/Entities/OOVisualEffectEntity.m index 1968905a..101531a8 100644 --- a/src/Core/Entities/OOVisualEffectEntity.m +++ b/src/Core/Entities/OOVisualEffectEntity.m @@ -285,7 +285,7 @@ MA 02110-1301, USA. - (BOOL) setUpOneFlasher:(NSDictionary *) subentDict { OOFlasherEntity *flasher = [OOFlasherEntity flasherWithDictionary:subentDict]; - [flasher setPosition:[subentDict oo_vectorForKey:@"position"]]; + [flasher setPosition:[subentDict oo_hpvectorForKey:@"position"]]; [self addSubEntity:flasher]; return YES; } @@ -295,7 +295,7 @@ MA 02110-1301, USA. { OOVisualEffectEntity *subentity = nil; NSString *subentKey = nil; - Vector subPosition; + HPVector subPosition; Quaternion subOrientation; subentKey = [subentDict oo_stringForKey:@"subentity_key"]; @@ -310,7 +310,7 @@ MA 02110-1301, USA. return NO; } - subPosition = [subentDict oo_vectorForKey:@"position"]; + subPosition = [subentDict oo_hpvectorForKey:@"position"]; subOrientation = [subentDict oo_quaternionForKey:@"orientation"]; [subentity setPosition:subPosition]; @@ -334,7 +334,7 @@ MA 02110-1301, USA. [subEntities addObject:sub]; [sub setOwner:self]; - double distance = magnitude([sub position]) + [sub findCollisionRadius]; + double distance = HPmagnitude([sub position]) + [sub findCollisionRadius]; if (distance > _profileRadius) { _profileRadius = distance; @@ -391,8 +391,8 @@ MA 02110-1301, USA. return; // TOO FAR AWAY } OOGL(glPushMatrix()); - - GLTranslateOOVector(position); + // HPVect: camera position + GLTranslateOOVector(HPVectorToVector(position)); GLMultOOMatrix(rotMatrix); [self drawImmediate:immediate translucent:translucent]; @@ -410,7 +410,7 @@ MA 02110-1301, USA. Entity *se = nil; foreach (se, [self subEntities]) { - [se setPosition:vector_multiply_scalar([se position], factor)]; + [se setPosition:HPvector_multiply_scalar([se position], factor)]; [se rescaleBy:factor]; } @@ -457,7 +457,7 @@ MA 02110-1301, USA. GLfloat flasher_factor = pow(factor/scaleX,1.0/3.0); foreach (se, [self subEntities]) { - Vector move = [se position]; + HPVector move = [se position]; move.x *= factor/scaleX; [se setPosition:move]; if ([se isVisualEffect]) @@ -488,7 +488,7 @@ MA 02110-1301, USA. GLfloat flasher_factor = pow(factor/scaleY,1.0/3.0); foreach (se, [self subEntities]) { - Vector move = [se position]; + HPVector move = [se position]; move.y *= factor/scaleY; [se setPosition:move]; if ([se isVisualEffect]) @@ -519,7 +519,7 @@ MA 02110-1301, USA. GLfloat flasher_factor = pow(factor/scaleZ,1.0/3.0); foreach (se, [self subEntities]) { - Vector move = [se position]; + HPVector move = [se position]; move.z *= factor/scaleZ; [se setPosition:move]; if ([se isVisualEffect]) diff --git a/src/Core/Entities/PlanetEntity.m b/src/Core/Entities/PlanetEntity.m index 499e435a..7fd6aae2 100644 --- a/src/Core/Entities/PlanetEntity.m +++ b/src/Core/Entities/PlanetEntity.m @@ -610,7 +610,7 @@ static const BaseFace kTexturedFaces[][3] = default: typeString = @"UNKNOWN"; } - return [NSString stringWithFormat:@"ID: %u position: %@ type: %@ radius: %.3fkm", [self universalID], VectorDescription([self position]), typeString, 0.001 * [self radius]]; + return [NSString stringWithFormat:@"ID: %u position: %@ type: %@ radius: %.3fkm", [self universalID], HPVectorDescription([self position]), typeString, 0.001 * [self radius]]; } @@ -651,7 +651,7 @@ static const BaseFace kTexturedFaces[][3] = #ifndef NDEBUG if ([ship reportAIMessages]) { - Vector p1 = ship->position; + HPVector p1 = ship->position; OOLog(@"planet.collide.shipHit", @"DEBUG: %@ %d collided with planet at (%.1f,%.1f,%.1f)",[ship name], [ship universalID], p1.x,p1.y,p1.z); } #endif @@ -719,7 +719,7 @@ static const BaseFace kTexturedFaces[][3] = } -- (void) setPosition:(Vector)posn +- (void) setPosition:(HPVector)posn { position = posn; [atmosphere setPosition:posn]; @@ -1160,7 +1160,7 @@ static const BaseFace kTexturedFaces[][3] = { ShipEntity *shuttle_ship; Quaternion q1; - Vector launch_pos = position; + HPVector launch_pos = position; double start_distance = collision_radius + 125.0; quaternion_set_random(&q1); diff --git a/src/Core/Entities/PlayerEntity.h b/src/Core/Entities/PlayerEntity.h index 5827a8a5..e2e4fc43 100644 --- a/src/Core/Entities/PlayerEntity.h +++ b/src/Core/Entities/PlayerEntity.h @@ -832,8 +832,8 @@ typedef enum - (NSString *)customViewDescription; - (void)resetCustomView; - (void)setCustomViewDataFromDictionary:(NSDictionary*) viewDict; -- (Vector) viewpointPosition; -- (Vector) breakPatternPosition; +- (HPVector) viewpointPosition; +- (HPVector) breakPatternPosition; - (Vector) viewpointOffset; - (Vector) viewpointOffsetAft; - (Vector) viewpointOffsetForward; diff --git a/src/Core/Entities/PlayerEntity.m b/src/Core/Entities/PlayerEntity.m index 52507d00..cbae4d94 100644 --- a/src/Core/Entities/PlayerEntity.m +++ b/src/Core/Entities/PlayerEntity.m @@ -2318,7 +2318,7 @@ static GLfloat sBaseMass = 0.0; // scanner sanity check - lose any targets further than maximum scanner range ShipEntity *primeTarget = [self primaryTarget]; - if (primeTarget && distance2([primeTarget position], [self position]) > SCANNER_MAX_RANGE2 && !autopilot_engaged) + if (primeTarget && HPdistance2([primeTarget position], [self position]) > SCANNER_MAX_RANGE2 && !autopilot_engaged) { [UNIVERSE addMessage:DESC(@"target-lost") forCount:3.0]; [self removeTarget:primeTarget]; @@ -2351,7 +2351,7 @@ static GLfloat sBaseMass = 0.0; - (void) updateMovementFlags{ - hasMoved = !vector_equal(position, lastPosition); + hasMoved = !HPvector_equal(position, lastPosition); hasRotated = !quaternion_equal(orientation, lastOrientation); lastPosition = position; lastOrientation = orientation; @@ -2596,7 +2596,7 @@ static GLfloat sBaseMass = 0.0; UPDATE_STAGE(@"applying newtonian drift"); assert(VELOCITY_CLEANUP_FULL > VELOCITY_CLEANUP_MIN); - position = vector_add(position, vector_multiply_scalar(velocity, (float)delta_t)); + position = HPvector_add(position, vectorToHPVector(vector_multiply_scalar(velocity, (float)delta_t))); GLfloat thrust_factor = 1.0; if (flightSpeed > maxFlightSpeed) @@ -3046,7 +3046,8 @@ static GLfloat sBaseMass = 0.0; - (OOMatrix) drawTransformationMatrix { OOMatrix result = playerRotMatrix; - return OOMatrixTranslate(result, position); + // HPVect: modify to use camera-relative positioning + return OOMatrixTranslate(result, HPVectorToVector(position)); } @@ -3065,13 +3066,13 @@ static GLfloat sBaseMass = 0.0; - (void) moveForward:(double) amount { distanceTravelled += (float)amount; - position = vector_add(position, vector_multiply_scalar(v_forward, (float)amount)); + position = HPvector_add(position, vectorToHPVector(vector_multiply_scalar(v_forward, (float)amount))); } -- (Vector) breakPatternPosition +- (HPVector) breakPatternPosition { - return vector_add(position,quaternion_rotate_vector(quaternion_conjugate(orientation),forwardViewOffset)); + return HPvector_add(position,vectorToHPVector(quaternion_rotate_vector(quaternion_conjugate(orientation),forwardViewOffset))); } @@ -3127,9 +3128,9 @@ static GLfloat sBaseMass = 0.0; /* TODO post 1.78: profiling suggests this gets called often enough * that it's worth caching the result per-frame - CIM */ -- (Vector) viewpointPosition +- (HPVector) viewpointPosition { - Vector viewpoint = position; + HPVector viewpoint = position; Vector offset = [self viewpointOffset]; // FIXME: this ought to be done with matrix or quaternion functions. @@ -4468,12 +4469,12 @@ static GLfloat sBaseMass = 0.0; // override ShipEntity definition to ensure that // if shields are still up, always hit the main entity and take the damage // on the shields -- (GLfloat) doesHitLine:(Vector)v0 :(Vector)v1 :(ShipEntity **)hitEntity +- (GLfloat) doesHitLine:(HPVector)v0 :(HPVector)v1 :(ShipEntity **)hitEntity { if (hitEntity) hitEntity[0] = (ShipEntity*)nil; - Vector u0 = vector_between(position, v0); // relative to origin of model / octree - Vector u1 = vector_between(position, v1); + Vector u0 = HPVectorToVector(HPvector_between(position, v0)); // relative to origin of model / octree + Vector u1 = HPVectorToVector(HPvector_between(position, v1)); Vector w0 = make_vector(dot_product(u0, v_right), dot_product(u0, v_up), dot_product(u0, v_forward)); // in ijk vectors Vector w1 = make_vector(dot_product(u1, v_right), dot_product(u1, v_up), dot_product(u1, v_forward)); GLfloat hit_distance = [octree isHitByLine:w0 :w1]; @@ -4493,10 +4494,10 @@ static GLfloat sBaseMass = 0.0; ShipEntity *se = nil; for (subEnum = [self shipSubEntityEnumerator]; (se = [subEnum nextObject]); ) { - Vector p0 = [se absolutePositionForSubentity]; + HPVector p0 = [se absolutePositionForSubentity]; Triangle ijk = [se absoluteIJKForSubentity]; - u0 = vector_between(p0, v0); - u1 = vector_between(p0, v1); + u0 = HPVectorToVector(HPvector_between(p0, v0)); + u1 = HPVectorToVector(HPvector_between(p0, v1)); w0 = resolveVectorInIJK(u0, ijk); w1 = resolveVectorInIJK(u1, ijk); @@ -4518,7 +4519,7 @@ static GLfloat sBaseMass = 0.0; - (void) takeEnergyDamage:(double)amount from:(Entity *)ent becauseOf:(Entity *)other { - Vector rel_pos; + HPVector rel_pos; double d_forward; BOOL internal_damage = NO; // base chance @@ -4540,13 +4541,13 @@ static GLfloat sBaseMass = 0.0; [[ent retain] autorelease]; [[other retain] autorelease]; - rel_pos = (ent != nil) ? [ent position] : kZeroVector; - rel_pos = vector_subtract(rel_pos, position); + rel_pos = (ent != nil) ? [ent position] : kZeroHPVector; + rel_pos = HPvector_subtract(rel_pos, position); [self doScriptEvent:OOJSID("shipBeingAttacked") withArgument:ent]; if ([ent isShip]) [(ShipEntity *)ent doScriptEvent:OOJSID("shipAttackedOther") withArgument:self]; - d_forward = dot_product(rel_pos, v_forward); + d_forward = dot_product(HPVectorToVector(rel_pos), v_forward); [self playShieldHit]; @@ -4613,7 +4614,7 @@ static GLfloat sBaseMass = 0.0; - (void) takeScrapeDamage:(double) amount from:(Entity *) ent { - Vector rel_pos; + HPVector rel_pos; double d_forward; BOOL internal_damage = NO; // base chance @@ -4627,9 +4628,10 @@ static GLfloat sBaseMass = 0.0; OOLog(@"player.ship.damage", @"Player took %.3f scrape damage from %@", amount, ent); [[ent retain] autorelease]; - rel_pos = ent ? [ent position] : kZeroVector; - rel_pos = vector_subtract(rel_pos, position); - d_forward = dot_product(rel_pos, v_forward); + rel_pos = ent ? [ent position] : kZeroHPVector; + rel_pos = HPvector_subtract(rel_pos, position); + // rel_pos is now small + d_forward = dot_product(HPVectorToVector(rel_pos), v_forward); [self playScrapeDamage]; if (d_forward >= 0) @@ -4785,7 +4787,7 @@ static GLfloat sBaseMass = 0.0; [self adjustVelocity:launchVector]; float sheight = (float)(boundingBox.max.y - boundingBox.min.y); - position = vector_subtract(position, vector_multiply_scalar(v_up, sheight)); + position = HPvector_subtract(position, vectorToHPVector(vector_multiply_scalar(v_up, sheight))); //remove escape pod [self removeEquipmentItem:@"EQ_ESCAPE_POD"]; @@ -5771,9 +5773,9 @@ static GLfloat sBaseMass = 0.0; - (void) leaveWitchspace { float d1 = (float)(SCANNER_MAX_RANGE*((Ranrot() & 255)/256.0 - 0.5)); - Vector pos = [UNIVERSE getWitchspaceExitPosition]; // no need to reset the PRNG + HPVector pos = [UNIVERSE getWitchspaceExitPosition]; // no need to reset the PRNG Quaternion q1; - Vector whpos, exitpos; + HPVector whpos, exitpos; GLfloat min_d1 = [UNIVERSE safeWitchspaceExitDistance]; quaternion_set_random(&q1); @@ -5781,8 +5783,8 @@ static GLfloat sBaseMass = 0.0; { d1 += ((d1 > 0.0)? min_d1: -min_d1); // not too close to the buoy. } - Vector v1 = vector_forward_from_quaternion(q1); - exitpos = vector_add(pos, vector_multiply_scalar(v1, d1)); // randomise exit position + HPVector v1 = HPvector_forward_from_quaternion(q1); + exitpos = HPvector_add(pos, HPvector_multiply_scalar(v1, d1)); // randomise exit position position = exitpos; [self setOrientation:[UNIVERSE getWitchspaceExitRotation]]; @@ -5799,25 +5801,25 @@ static GLfloat sBaseMass = 0.0; if (wh_arrival_time > 0) { // Player is following other ship - whpos = vector_add(exitpos, vector_multiply_scalar([self forwardVector], 1000.0f)); + whpos = HPvector_add(exitpos, vectorToHPVector(vector_multiply_scalar([self forwardVector], 1000.0f))); [wormhole setContainsPlayer:YES]; } else { // Player is the leadship - whpos = vector_add(exitpos, vector_multiply_scalar([self forwardVector], -500.0f)); + whpos = HPvector_add(exitpos, vectorToHPVector(vector_multiply_scalar([self forwardVector], -500.0f))); // so it won't contain the player by the time they exit [wormhole setExitSpeed:maxFlightSpeed*WORMHOLE_LEADER_SPEED_FACTOR]; } - Vector distance = vector_subtract(whpos, pos); - if (magnitude2(distance) < min_d1*min_d1 ) // within safety distance from the buoy? + HPVector distance = HPvector_subtract(whpos, pos); + if (HPmagnitude2(distance) < min_d1*min_d1 ) // within safety distance from the buoy? { // the wormhole is to close to the buoy. Move both player and wormhole away from it in the x-y plane. distance.z = 0; - distance = vector_multiply_scalar(vector_normal(distance), min_d1); - whpos = vector_add(whpos, distance); - position = vector_add(position, distance); + distance = HPvector_multiply_scalar(HPvector_normal(distance), min_d1); + whpos = HPvector_add(whpos, distance); + position = HPvector_add(position, distance); } [wormhole setExitPosition: whpos]; } diff --git a/src/Core/Entities/PlayerEntityLegacyScriptEngine.m b/src/Core/Entities/PlayerEntityLegacyScriptEngine.m index 327bebe7..e46df904 100644 --- a/src/Core/Entities/PlayerEntityLegacyScriptEngine.m +++ b/src/Core/Entities/PlayerEntityLegacyScriptEngine.m @@ -1520,7 +1520,7 @@ static int scriptRandomSeed = -1; // ensure proper random function yString = [tokens objectAtIndex:4]; zString = [tokens objectAtIndex:5]; - Vector posn = make_vector( [xString floatValue], [yString floatValue], [zString floatValue]); + HPVector posn = make_HPvector( [xString floatValue], [yString floatValue], [zString floatValue]); int number = [numberString intValue]; if (number < 1) @@ -1562,7 +1562,7 @@ static int scriptRandomSeed = -1; // ensure proper random function yString = [tokens objectAtIndex:4]; zString = [tokens objectAtIndex:5]; - Vector posn = make_vector( [xString floatValue], [yString floatValue], [zString floatValue]); + HPVector posn = make_HPvector( [xString floatValue], [yString floatValue], [zString floatValue]); int number = [numberString intValue]; if (number < 1) @@ -1597,7 +1597,7 @@ static int scriptRandomSeed = -1; // ensure proper random function GLfloat y = [[tokens objectAtIndex:4] floatValue]; GLfloat z = [[tokens objectAtIndex:5] floatValue]; GLfloat r = [[tokens objectAtIndex:6] floatValue]; - Vector posn = make_vector( x, y, z); + HPVector posn = make_HPvector( x, y, z); if (number < 1) { @@ -2260,14 +2260,14 @@ static int scriptRandomSeed = -1; // ensure proper random function OOLogWARN(@"script.deprecated", @"setting %@ for %@ '%@' in 'abs' inside .plists can cause compatibility issues across Oolite versions. Use coordinates relative to main system objects instead.",@"position",@"planet",planetKey); } - Vector posn = [UNIVERSE coordinatesFromCoordinateSystemString:positionString]; + HPVector posn = [UNIVERSE coordinatesFromCoordinateSystemString:positionString]; if (posn.x || posn.y || posn.z) { OOLog(kOOLogDebugAddPlanet, @"planet position (%.2f %.2f %.2f) derived from %@", posn.x, posn.y, posn.z, positionString); } else { - ScanVectorFromString(positionString, &posn); + ScanHPVectorFromString(positionString, &posn); OOLog(kOOLogDebugAddPlanet, @"planet position (%.2f %.2f %.2f) derived from %@", posn.x, posn.y, posn.z, positionString); } [planet setPosition: posn]; @@ -2310,14 +2310,14 @@ static int scriptRandomSeed = -1; // ensure proper random function { OOLogWARN(@"script.deprecated", @"setting %@ for %@ '%@' in 'abs' inside .plists can cause compatibility issues across Oolite versions. Use coordinates relative to main system objects instead.",@"position",@"moon",moonKey); } - Vector posn = [UNIVERSE coordinatesFromCoordinateSystemString:positionString]; + HPVector posn = [UNIVERSE coordinatesFromCoordinateSystemString:positionString]; if (posn.x || posn.y || posn.z) { OOLog(kOOLogDebugAddPlanet, @"moon position (%.2f %.2f %.2f) derived from %@", posn.x, posn.y, posn.z, positionString); } else { - ScanVectorFromString(positionString, &posn); + ScanHPVectorFromString(positionString, &posn); OOLog(kOOLogDebugAddPlanet, @"moon position (%.2f %.2f %.2f) derived from %@", posn.x, posn.y, posn.z, positionString); } [planet setPosition: posn]; @@ -2604,7 +2604,7 @@ static int scriptRandomSeed = -1; // ensure proper random function OOLog(kOOLogDebugProcessSceneStringAddModel, @"::::: adding model to scene:'%@'", ship); [ship setOrientation: model_q]; - [ship setPosition: model_p0]; + [ship setPosition: vectorToHPVector(model_p0)]; [UNIVERSE setMainLightPosition:(Vector){ DEMO_LIGHT_POSITION }]; // set light origin [ship setScanClass: CLASS_NO_DRAW]; [ship switchAITo: @"nullAI.plist"]; @@ -2639,7 +2639,7 @@ static int scriptRandomSeed = -1; // ensure proper random function OOLog(kOOLogDebugProcessSceneStringAddModel, @"::::: adding model to scene:'%@'", doppelganger); [doppelganger setOrientation: model_q]; - [doppelganger setPosition: model_p0]; + [doppelganger setPosition: vectorToHPVector(model_p0)]; [UNIVERSE setMainLightPosition:(Vector){ DEMO_LIGHT_POSITION }]; // set light origin [doppelganger setScanClass: CLASS_NO_DRAW]; [doppelganger switchAITo: @"nullAI.plist"]; @@ -2728,7 +2728,8 @@ static int scriptRandomSeed = -1; // ensure proper random function #endif OOLog(kOOLogDebugProcessSceneStringAddMiniPlanet, @"::::: adding %@ to scene:'%@'", i_key, doppelganger); [doppelganger setOrientation: model_q]; - [doppelganger setPosition: model_p0]; + // HPVect: mission screen coordinates are small enough that we don't need high-precision for calculations + [doppelganger setPosition: vectorToHPVector(model_p0)]; /* MKW - add rotation based on current time * - necessary to duplicate the rotation already performed in PlanetEntity.m since we reset the orientation above. */ int deltaT = floor(fmod([self clockTimeAdjusted], 86400)); diff --git a/src/Core/Entities/ShipEntity.h b/src/Core/Entities/ShipEntity.h index 6f3c7d78..01cc2c6d 100644 --- a/src/Core/Entities/ShipEntity.h +++ b/src/Core/Entities/ShipEntity.h @@ -186,7 +186,7 @@ typedef enum Vector v_forward, v_up, v_right; // unit vectors derived from the direction faced // variables which are controlled by AI - Vector destination; // for flying to/from a set point + HPVector destination; // for flying to/from a set point GLfloat desired_range; // range to which to journey/scan GLfloat desired_speed; // speed at which to travel @@ -303,7 +303,7 @@ typedef enum // AI stuff Vector jink; // x and y set factors for offsetting a pursuing ship's position - Vector coordinates; // for flying to/from a set point + HPVector coordinates; // for flying to/from a set point Vector reference; // a direction vector of magnitude 1 (* turrets *) NSUInteger _subIdx; // serialisation index - used only if this ship is a subentity @@ -376,7 +376,7 @@ typedef enum unsigned n_scanned_ships; // advanced navigation - Vector navpoints[32]; + HPVector navpoints[32]; unsigned next_navpoint_index; unsigned number_of_navpoints; @@ -490,13 +490,13 @@ typedef enum - (float) volume; // octree collision hunting -- (GLfloat)doesHitLine:(Vector)v0 :(Vector)v1; -- (GLfloat)doesHitLine:(Vector)v0 :(Vector)v1 :(ShipEntity**)hitEntity; -- (GLfloat)doesHitLine:(Vector)v0 :(Vector)v1 withPosition:(Vector)o andIJK:(Vector)i :(Vector)j :(Vector)k; // for subentities +- (GLfloat)doesHitLine:(HPVector)v0 :(HPVector)v1; +- (GLfloat)doesHitLine:(HPVector)v0 :(HPVector)v1 :(ShipEntity**)hitEntity; +- (GLfloat)doesHitLine:(HPVector)v0 :(HPVector)v1 withPosition:(HPVector)o andIJK:(Vector)i :(Vector)j :(Vector)k; // for subentities -- (BoundingBox) findBoundingBoxRelativeToPosition:(Vector)opv InVectors:(Vector)i :(Vector)j :(Vector)k; +- (BoundingBox) findBoundingBoxRelativeToPosition:(HPVector)opv InVectors:(Vector)i :(Vector)j :(Vector)k; -- (Vector)absoluteTractorPosition; +- (HPVector)absoluteTractorPosition; // beacons // definitions now in protocol /*- (NSString *) beaconCode; @@ -938,11 +938,11 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q - (GLfloat) rangeToDestination; - (double) trackDestination:(double) delta_t :(BOOL) retreat; -- (void) setCoordinate:(Vector)coord; -- (Vector) coordinates; -- (Vector) destination; -- (Vector) distance_six: (GLfloat) dist; -- (Vector) distance_twelve: (GLfloat) dist withOffset:(GLfloat)offset; +- (void) setCoordinate:(HPVector)coord; +- (HPVector) coordinates; +- (HPVector) destination; +- (HPVector) distance_six: (GLfloat) dist; +- (HPVector) distance_twelve: (GLfloat) dist withOffset:(GLfloat)offset; - (void) setEvasiveJink:(GLfloat) z; - (void) evasiveAction:(double) delta_t; @@ -1028,8 +1028,8 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q - (void) switchLightsOff; - (BOOL) lightsActive; -- (void) setDestination:(Vector) dest; -- (void) setEscortDestination:(Vector) dest; +- (void) setDestination:(HPVector) dest; +- (void) setEscortDestination:(HPVector) dest; - (BOOL) canAcceptEscort:(ShipEntity *)potentialEscort; - (BOOL) acceptAsEscort:(ShipEntity *) other_ship; diff --git a/src/Core/Entities/ShipEntity.m b/src/Core/Entities/ShipEntity.m index d760a189..e102e5ca 100644 --- a/src/Core/Entities/ShipEntity.m +++ b/src/Core/Entities/ShipEntity.m @@ -146,7 +146,7 @@ static GLfloat calcFuelChargeRate (GLfloat myMass) - (void) addSubEntity:(Entity *) subent; - (void) refreshEscortPositions; -- (Vector) coordinatesForEscortPosition:(unsigned)idx; +- (HPVector) coordinatesForEscortPosition:(unsigned)idx; - (void) addSubentityToCollisionRadius:(Entity *) subent; - (ShipEntity *) launchPodWithCrew:(NSArray *)podCrew; @@ -770,7 +770,7 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); - (BOOL) setUpOneFlasher:(NSDictionary *) subentDict { OOFlasherEntity *flasher = [OOFlasherEntity flasherWithDictionary:subentDict]; - [flasher setPosition:[subentDict oo_vectorForKey:@"position"]]; + [flasher setPosition:vectorToHPVector([subentDict oo_vectorForKey:@"position"])]; [self addSubEntity:flasher]; return YES; } @@ -780,7 +780,7 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); { ShipEntity *subentity = nil; NSString *subentKey = nil; - Vector subPosition; + HPVector subPosition; Quaternion subOrientation; subentKey = [subentDict oo_stringForKey:@"subentity_key"]; @@ -802,7 +802,7 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); return NO; } - subPosition = [subentDict oo_vectorForKey:@"position"]; + subPosition = vectorToHPVector([subentDict oo_vectorForKey:@"position"]); subOrientation = [subentDict oo_quaternionForKey:@"orientation"]; [subentity setPosition:subPosition]; @@ -991,7 +991,7 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); if ([self behaviour] == BEHAVIOUR_TRACK_AS_TURRET) subtype = @"(turret)"; else subtype = @"(subentity)"; - return [NSString stringWithFormat:@"\"%@\" position: %@ %@", [self name], VectorDescription([self position]), subtype]; + return [NSString stringWithFormat:@"\"%@\" position: %@ %@", [self name], HPVectorDescription([self position]), subtype]; } } @@ -1187,11 +1187,12 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); } -- (BoundingBox)findBoundingBoxRelativeToPosition:(Vector)opv InVectors:(Vector) _i :(Vector) _j :(Vector) _k +- (BoundingBox)findBoundingBoxRelativeToPosition:(HPVector)opv InVectors:(Vector) _i :(Vector) _j :(Vector) _k { - return [[self mesh] findBoundingBoxRelativeToPosition:opv + // HPVect: check that this conversion doesn't lose needed precision + return [[self mesh] findBoundingBoxRelativeToPosition:HPVectorToVector(opv) basis:_i :_j :_k - selfPosition:position + selfPosition:HPVectorToVector(position) selfBasis:v_right :v_up :v_forward]; } @@ -1208,22 +1209,22 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); } -- (GLfloat) doesHitLine:(Vector)v0 :(Vector)v1 +- (GLfloat) doesHitLine:(HPVector)v0 :(HPVector)v1 { - Vector u0 = vector_between(position, v0); // relative to origin of model / octree - Vector u1 = vector_between(position, v1); + Vector u0 = HPVectorToVector(HPvector_between(position, v0)); // relative to origin of model / octree + Vector u1 = HPVectorToVector(HPvector_between(position, v1)); Vector w0 = make_vector(dot_product(u0, v_right), dot_product(u0, v_up), dot_product(u0, v_forward)); // in ijk vectors Vector w1 = make_vector(dot_product(u1, v_right), dot_product(u1, v_up), dot_product(u1, v_forward)); return [octree isHitByLine:w0 :w1]; } -- (GLfloat) doesHitLine:(Vector)v0 :(Vector)v1 :(ShipEntity **)hitEntity +- (GLfloat) doesHitLine:(HPVector)v0 :(HPVector)v1 :(ShipEntity **)hitEntity { if (hitEntity) hitEntity[0] = (ShipEntity*)nil; - Vector u0 = vector_between(position, v0); // relative to origin of model / octree - Vector u1 = vector_between(position, v1); + Vector u0 = HPVectorToVector(HPvector_between(position, v0)); // relative to origin of model / octree + Vector u1 = HPVectorToVector(HPvector_between(position, v1)); Vector w0 = make_vector(dot_product(u0, v_right), dot_product(u0, v_up), dot_product(u0, v_forward)); // in ijk vectors Vector w1 = make_vector(dot_product(u1, v_right), dot_product(u1, v_up), dot_product(u1, v_forward)); GLfloat hit_distance = [octree isHitByLine:w0 :w1]; @@ -1237,10 +1238,10 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); ShipEntity *se = nil; for (subEnum = [self shipSubEntityEnumerator]; (se = [subEnum nextObject]); ) { - Vector p0 = [se absolutePositionForSubentity]; + HPVector p0 = [se absolutePositionForSubentity]; Triangle ijk = [se absoluteIJKForSubentity]; - u0 = vector_between(p0, v0); - u1 = vector_between(p0, v1); + u0 = HPVectorToVector(HPvector_between(p0, v0)); + u1 = HPVectorToVector(HPvector_between(p0, v1)); w0 = resolveVectorInIJK(u0, ijk); w1 = resolveVectorInIJK(u1, ijk); @@ -1259,10 +1260,10 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); } -- (GLfloat)doesHitLine:(Vector)v0 :(Vector)v1 withPosition:(Vector)o andIJK:(Vector)i :(Vector)j :(Vector)k +- (GLfloat)doesHitLine:(HPVector)v0 :(HPVector)v1 withPosition:(HPVector)o andIJK:(Vector)i :(Vector)j :(Vector)k { - Vector u0 = vector_between(o, v0); // relative to origin of model / octree - Vector u1 = vector_between(o, v1); + Vector u0 = HPVectorToVector(HPvector_between(o, v0)); // relative to origin of model / octree + Vector u1 = HPVectorToVector(HPvector_between(o, v1)); Vector w0 = make_vector(dot_product(u0, i), dot_product(u0, j), dot_product(u0, k)); // in ijk vectors Vector w1 = make_vector(dot_product(u1, j), dot_product(u1, j), dot_product(u1, k)); return [octree isHitByLine:w0 :w1]; @@ -1306,9 +1307,9 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); } -- (Vector)absoluteTractorPosition +- (HPVector)absoluteTractorPosition { - return vector_add(position, quaternion_rotate_vector([self normalOrientation], tractor_position)); + return HPvector_add(position, vectorToHPVector(quaternion_rotate_vector([self normalOrientation], tractor_position))); } @@ -1505,7 +1506,7 @@ static ShipEntity *doOctreesCollide(ShipEntity *prime, ShipEntity *other); while (_pendingEscortCount > 0 && ([self isThargoid] || currentEscortCount < _maxEscortCount)) { // The following line adds escort 1 in position 1, etc... up to MAX_ESCORTS. - Vector ex_pos = [self coordinatesForEscortPosition:currentEscortCount]; + HPVector ex_pos = [self coordinatesForEscortPosition:currentEscortCount]; ShipEntity *escorter = nil; @@ -1707,12 +1708,12 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) Octree *prime_octree = prime->octree; Octree *other_octree = other->octree; - Vector prime_position = [prime absolutePositionForSubentity]; + HPVector prime_position = [prime absolutePositionForSubentity]; Triangle prime_ijk = [prime absoluteIJKForSubentity]; - Vector other_position = [other absolutePositionForSubentity]; + HPVector other_position = [other absolutePositionForSubentity]; Triangle other_ijk = [other absoluteIJKForSubentity]; - Vector relative_position_of_other = resolveVectorInIJK(vector_between(prime_position, other_position), prime_ijk); + Vector relative_position_of_other = resolveVectorInIJK(HPVectorToVector(HPvector_between(prime_position, other_position)), prime_ijk); Triangle relative_ijk_of_other; relative_ijk_of_other.v[0] = resolveVectorInIJK(other_ijk.v[0], prime_ijk); relative_ijk_of_other.v[1] = resolveVectorInIJK(other_ijk.v[1], prime_ijk); @@ -1791,15 +1792,15 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) { // in update we check if close contacts have gone out of touch range (origin within our collision_radius) // here we check if something has come within that range - Vector otherPos = [otherShip position]; + HPVector otherPos = [otherShip position]; OOUniversalID otherID = [otherShip universalID]; NSString *other_key = [NSString stringWithFormat:@"%d", otherID]; if (![closeContactsInfo objectForKey:other_key] && - distance2(position, otherPos) < collision_radius * collision_radius) + HPdistance2(position, otherPos) < collision_radius * collision_radius) { // calculate position with respect to our own position and orientation - Vector dpos = vector_between(position, otherPos); + Vector dpos = HPVectorToVector(HPvector_between(position, otherPos)); Vector rpos = make_vector(dot_product(dpos, v_right), dot_product(dpos, v_up), dot_product(dpos, v_forward)); [closeContactsInfo setObject:[NSString stringWithFormat:@"%f %f %f", rpos.x, rpos.y, rpos.z] forKey: other_key]; @@ -1829,7 +1830,7 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) - (BoundingBox)findSubentityBoundingBox { - return [[self mesh] findSubentityBoundingBoxWithPosition:position rotMatrix:rotMatrix]; + return [[self mesh] findSubentityBoundingBoxWithPosition:HPVectorToVector(position) rotMatrix:rotMatrix]; } @@ -1859,7 +1860,7 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) { if (!subent) return; - double distance = magnitude([subent position]) + [subent findCollisionRadius]; + double distance = HPmagnitude([subent position]) + [subent findCollisionRadius]; if ([subent isKindOfClass:[ShipEntity class]]) // Solid subentity { if (distance > collision_radius) @@ -1979,10 +1980,10 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) ShipEntity* other = [UNIVERSE entityForUniversalID:[other_key intValue]]; if ((other != nil) && (other->isShip)) { - if (distance2(position, other->position) > collision_radius * collision_radius) // moved beyond our sphere! + if (HPdistance2(position, other->position) > collision_radius * collision_radius) // moved beyond our sphere! { // calculate position with respect to our own position and orientation - Vector dpos = vector_between(position, other->position); + Vector dpos = HPVectorToVector(HPvector_between(position, other->position)); Vector pos1 = make_vector(dot_product(dpos, v_right), dot_product(dpos, v_up), dot_product(dpos, v_forward)); Vector pos0 = {0, 0, 0}; ScanVectorFromString([closeContactsInfo objectForKey: other_key], &pos0); @@ -2062,7 +2063,7 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) if (sun != nil) { // set the ambient temperature here - double sun_zd = magnitude2(vector_between(position, [sun position])); // square of distance + double sun_zd = HPdistance2(position, [sun position]); // square of distance double sun_cr = sun->collision_radius; double alt1 = sun_cr * sun_cr / sun_zd; external_temp = SUN_TEMPERATURE * alt1; @@ -2247,9 +2248,9 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) { flightYaw = 0.0; [self applyAttitudeChanges:delta_t]; - GLfloat range2 = 0.1 * distance2(position, destination) / (collision_radius * collision_radius); + GLfloat range2 = 0.1 * HPdistance2(position, destination) / (collision_radius * collision_radius); if ((range2 > 1.0)||(velocity.z > 0.0)) range2 = 1.0; - position = vector_add(position, vector_multiply_scalar(velocity, range2 * delta_t)); + position = HPvector_add(position, vectorToHPVector(vector_multiply_scalar(velocity, range2 * delta_t))); } else { @@ -3574,13 +3575,13 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) velocity.z += moment * dv.z; // acceleration = force / mass // force proportional to distance (spring rule) - Vector dp = vector_between(position, destination); + HPVector dp = HPvector_between(position, destination); moment = delta_t * 0.5 * tf; velocity.x += moment * dp.x; velocity.y += moment * dp.y; velocity.z += moment * dp.z; // force inversely proportional to distance - GLfloat d2 = magnitude2(dp); + GLfloat d2 = HPmagnitude2(dp); moment = (d2 > 0.0)? delta_t * 5.0 * tf / d2 : 0.0; if (d2 > 0.0) { @@ -5063,7 +5064,7 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) return; } - if (distance(position, [planet position]) + [self collisionRadius] < [planet radius]) + if (HPdistance(position, [planet position]) + [self collisionRadius] < [planet radius]) { // we have landed. (completely disappeared inside planet) [self landOnPlanet:planet]; @@ -5274,12 +5275,12 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) aim = [self ballTrackLeadingTarget:delta_t atTarget:turret_target]; if (aim > -1.0) // potential target { - Vector p = vector_subtract([turret_target position], [turret_owner position]); + HPVector p = HPvector_subtract([turret_target position], [turret_owner position]); double cr = [turret_owner collisionRadius]; if (aim > .95) { - [self fireTurretCannon:magnitude(p) - cr]; + [self fireTurretCannon:HPmagnitude(p) - cr]; } return; } @@ -5302,12 +5303,12 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) aim = [self ballTrackLeadingTarget:delta_t atTarget:target]; if (aim > -1.0) { // tracking... - Vector p = vector_subtract([target position], [turret_owner position]); + HPVector p = HPvector_subtract([target position], [turret_owner position]); double cr = [turret_owner collisionRadius]; if (aim > .95) { // fire! - [self fireTurretCannon:magnitude(p) - cr]; + [self fireTurretCannon:HPmagnitude(p) - cr]; } return; } @@ -5328,22 +5329,22 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) - (void) behaviour_fly_thru_navpoints:(double) delta_t { int navpoint_plus_index = (next_navpoint_index + 1) % number_of_navpoints; - Vector d1 = navpoints[next_navpoint_index]; // head for this one - Vector d2 = navpoints[navpoint_plus_index]; // but be facing this one + HPVector d1 = navpoints[next_navpoint_index]; // head for this one + HPVector d2 = navpoints[navpoint_plus_index]; // but be facing this one - Vector rel = vector_between(d1, position); // vector from d1 to position - Vector ref = vector_between(d2, d1); // vector from d2 to d1 - ref = vector_normal(ref); + HPVector rel = HPvector_between(d1, position); // vector from d1 to position + HPVector ref = HPvector_between(d2, d1); // vector from d2 to d1 + ref = HPvector_normal(ref); - Vector xp = make_vector(ref.y * rel.z - ref.z * rel.y, ref.z * rel.x - ref.x * rel.z, ref.x * rel.y - ref.y * rel.x); + HPVector xp = make_HPvector(ref.y * rel.z - ref.z * rel.y, ref.z * rel.x - ref.x * rel.z, ref.x * rel.y - ref.y * rel.x); GLfloat v0 = 0.0; - GLfloat r0 = dot_product(rel, ref); // proportion of rel in direction ref + GLfloat r0 = HPdot_product(rel, ref); // proportion of rel in direction ref // if r0 is negative then we're the wrong side of things - GLfloat r1 = magnitude(xp); // distance of position from line + GLfloat r1 = HPmagnitude(xp); // distance of position from line BOOL in_cone = (r0 > 0.5 * r1); @@ -5352,7 +5353,7 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) else r1 *= 2.0; - GLfloat dist2 = magnitude2(rel); + GLfloat dist2 = HPmagnitude2(rel); if (dist2 < desired_range * desired_range) { @@ -5372,7 +5373,7 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) success_factor = dist2; // set destination spline point from r1 and ref - destination = make_vector(d1.x + r1 * ref.x, d1.y + r1 * ref.y, d1.z + r1 * ref.z); + destination = make_HPvector(d1.x + r1 * ref.x, d1.y + r1 * ref.y, d1.z + r1 * ref.z); // do the actual piloting!! // @@ -5589,29 +5590,29 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) #ifndef NDEBUG - (void) drawDebugStuff { - + // HPVect: imprecise here - needs camera relative if (0 && reportAIMessages) { - OODebugDrawPoint(destination, [OOColor blueColor]); - OODebugDrawColoredLine([self position], destination, [OOColor colorWithWhite:0.15 alpha:1.0]); + OODebugDrawPoint(HPVectorToVector(destination), [OOColor blueColor]); + OODebugDrawColoredLine(HPVectorToVector([self position]), HPVectorToVector(destination), [OOColor colorWithWhite:0.15 alpha:1.0]); Entity *pTarget = [self primaryTarget]; if (pTarget != nil) { - OODebugDrawPoint([pTarget position], [OOColor redColor]); - OODebugDrawColoredLine([self position], [pTarget position], [OOColor colorWithRed:0.2 green:0.0 blue:0.0 alpha:1.0]); + OODebugDrawPoint(HPVectorToVector([pTarget position]), [OOColor redColor]); + OODebugDrawColoredLine(HPVectorToVector([self position]), HPVectorToVector([pTarget position]), [OOColor colorWithRed:0.2 green:0.0 blue:0.0 alpha:1.0]); } Entity *sTarget = [self targetStation]; if (sTarget != pTarget && [sTarget isStation]) { - OODebugDrawPoint([sTarget position], [OOColor cyanColor]); + OODebugDrawPoint(HPVectorToVector([sTarget position]), [OOColor cyanColor]); } Entity *fTarget = [self foundTarget]; if (fTarget != nil && fTarget != pTarget && fTarget != sTarget) { - OODebugDrawPoint([fTarget position], [OOColor magentaColor]); + OODebugDrawPoint(HPVectorToVector([fTarget position]), [OOColor magentaColor]); } } } @@ -5631,7 +5632,7 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) if ([self status] == STATUS_ACTIVE) { - Vector abspos = position; // STATUS_ACTIVE means it is in control of its own orientation +/* Vector abspos = position; // STATUS_ACTIVE means it is in control of its own orientation Entity *last = nil; Entity *father = [self owner]; OOMatrix r_mat; @@ -5643,14 +5644,17 @@ ShipEntity* doOctreesCollide(ShipEntity* prime, ShipEntity* other) last = father; if (![last isSubEntity]) break; father = [father owner]; - } + } */ + HPVector abspos = [self absolutePositionForSubentity]; GLLoadOOMatrix([UNIVERSE viewMatrix]); - GLTranslateOOVector(abspos); + // HPVect: need to make camera-relative + GLTranslateOOVector(HPVectorToVector(abspos)); } else { - GLTranslateOOVector(position); + // HPVect: need to make camera-relative + GLTranslateOOVector(HPVectorToVector(position)); } GLMultOOMatrix(rotMatrix); @@ -5979,10 +5983,10 @@ static GLfloat scripted_color[4] = { 0.0, 0.0, 0.0, 0.0}; // to be defined by s } [previousCondition oo_setFloat:desired_range forKey:@"desired_range"]; [previousCondition oo_setFloat:desired_speed forKey:@"desired_speed"]; - [previousCondition oo_setVector:destination forKey:@"destination"]; + [previousCondition oo_setHPVector:destination forKey:@"destination"]; destination = [prox_ship position]; - destination = OOVectorInterpolate(position, [prox_ship position], 0.5); // point between us and them + destination = OOHPVectorInterpolate(position, [prox_ship position], 0.5); // point between us and them desired_range = prox_ship->collision_radius * PROXIMITY_AVOID_DISTANCE_FACTOR; @@ -6001,7 +6005,7 @@ static GLfloat scripted_color[4] = { 0.0, 0.0, 0.0, 0.0}; // to be defined by s _primaryTarget = [previousCondition objectForKey:@"primaryTarget"]; desired_range = [previousCondition oo_floatForKey:@"desired_range"]; desired_speed = [previousCondition oo_floatForKey:@"desired_speed"]; - destination = [previousCondition oo_vectorForKey:@"destination"]; + destination = [previousCondition oo_hpvectorForKey:@"destination"]; [previousCondition release]; previousCondition = nil; @@ -6180,7 +6184,7 @@ static GLfloat scripted_color[4] = { 0.0, 0.0, 0.0, 0.0}; // to be defined by s return; // check vectors - Vector vdiff = vector_between(position, other->position); + Vector vdiff = HPVectorToVector(HPvector_between(position, other->position)); GLfloat d_forward = dot_product(vdiff, v_forward); GLfloat d_up = dot_product(vdiff, v_up); GLfloat d_right = dot_product(vdiff, v_right); @@ -6198,8 +6202,8 @@ static GLfloat scripted_color[4] = { 0.0, 0.0, 0.0, 0.0}; // to be defined by s if ((prox)&&(prox != other)) { // check which subtends the greatest angle - GLfloat sa_prox = prox->collision_radius * prox->collision_radius / distance2(position, prox->position); - GLfloat sa_other = other->collision_radius * other->collision_radius / distance2(position, other->position); + GLfloat sa_prox = prox->collision_radius * prox->collision_radius / HPdistance2(position, prox->position); + GLfloat sa_other = other->collision_radius * other->collision_radius / HPdistance2(position, other->position); if (sa_prox < sa_other) return; } } @@ -6605,9 +6609,9 @@ static BOOL IsBehaviourHostile(OOBehaviour behaviour) } -static float SurfaceDistanceSqaredV(Vector reference, Entity *stellar) +static float SurfaceDistanceSqaredV(HPVector reference, Entity *stellar) { - float centerDistance = magnitude2(vector_subtract([stellar position], reference)); + float centerDistance = HPmagnitude2(HPvector_subtract([stellar position], reference)); float r = [stellar radius]; /* 1.35: empirical value used to help determine proximity when non-nested planets are close to each other @@ -6624,7 +6628,7 @@ static float SurfaceDistanceSqared(Entity *reference, Entity *ste NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) { - Vector p = [(ShipEntity*) context position]; + HPVector p = [(ShipEntity*) context position]; OOPlanetEntity* e1 = i1; OOPlanetEntity* e2 = i2; @@ -6647,7 +6651,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) */ OOPlanetEntity *planet = nil, *bestPlanet = nil; float bestRange = INFINITY; - Vector myPosition = [self position]; + HPVector myPosition = [self position]; // valgrind complains about this line here. Might be compiler/GNUstep bug? // should we go back to a traditional enumerator? - CIM @@ -6732,7 +6736,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) float cr = [nearest radius]; float cr2 = cr * cr; OOAegisStatus result = AEGIS_NONE; - float d2 = magnitude2(vector_subtract([nearest position], [self position])); + float d2 = HPmagnitude2(HPvector_subtract([nearest position], [self position])); float sd2 = SCANNER_MAX_RANGE2 * 10.0f; // check if nearing a surface @@ -6758,7 +6762,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) StationEntity *the_station = [UNIVERSE station]; if (the_station) { - sd2 = magnitude2(vector_subtract([the_station position], [self position])); + sd2 = HPmagnitude2(HPvector_subtract([the_station position], [self position])); } if (sd2 < SCANNER_MAX_RANGE2 * 4.0f) // double scanner range { @@ -6778,7 +6782,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) { // are we also close to the main planet? OOPlanetEntity *mainPlanet = [UNIVERSE planet]; - d2 = magnitude2(vector_subtract([mainPlanet position], [self position])); + d2 = HPmagnitude2(HPvector_subtract([mainPlanet position], [self position])); cr2 = [mainPlanet radius]; cr2 *= cr2; if (d2 < cr2 * 9.0f) @@ -7550,7 +7554,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) for (i = 0; i < [targets count]; i++) { Entity *e2 = [targets objectAtIndex:i]; - Vector p2 = vector_subtract([e2 position], [self position]); + Vector p2 = [self vectorTo:e2]; double ecr = [e2 collisionRadius]; double d = (magnitude(p2) - ecr) / range; // base damage within defined range, inverse-square falloff outside @@ -7605,7 +7609,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) for (i = 0; i < [targets count]; i++) { Entity *e2 = [targets objectAtIndex:i]; - Vector p2 = vector_subtract([e2 position], position); + Vector p2 = [self vectorTo:e2]; double ecr = [e2 collisionRadius]; double d = (magnitude(p2) - ecr) * 2.6; // 2.6 is a correction constant to stay in limits of the old code. double damage = (d > 0) ? weapon_damage * desired_range / (d * d) : weapon_damage; @@ -7626,7 +7630,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) ShipEntity *e2 = (ShipEntity*)[targets objectAtIndex:i]; if ([e2 isShip]) { - Vector p2 = vector_subtract([e2 position], position); + Vector p2 = [self vectorTo:e2]; double ecr = [e2 collisionRadius]; double d2 = magnitude2(p2) - ecr * ecr; while (d2 <= 0.0) @@ -7733,7 +7737,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) Entity *se = nil; foreach (se, [self subEntities]) { - [se setPosition:vector_multiply_scalar([se position], factor)]; + [se setPosition:HPvector_multiply_scalar([se position], factor)]; [se rescaleBy:factor]; } @@ -7751,7 +7755,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) if (parent != nil) { ShipEntity *this_ship = [self retain]; - Vector this_pos = [self absolutePositionForSubentity]; + HPVector this_pos = [self absolutePositionForSubentity]; // remove this ship from its parent's subentity list [parent subEntityDied:self]; @@ -7765,7 +7769,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) } } - Vector xposition = position; + HPVector xposition = position; NSUInteger i; Vector v; Quaternion q; @@ -7879,7 +7883,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) if (Ranrot() % 100 < cargo_chance) // chance of any given piece of cargo surviving decompression { ShipEntity* container = [jetsam objectAtIndex:i]; - Vector rpos = xposition; + HPVector rpos = xposition; Vector rrand = OORandomPositionInBoundingBox(boundingBox); rpos.x += rrand.x; rpos.y += rrand.y; rpos.z += rrand.z; rpos.x += (ranrot_rand() % 7) - 3; @@ -7920,7 +7924,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) ShipEntity* rock = [UNIVERSE newShipWithRole:debrisRole]; // retain count = 1 if (rock) { - Vector rpos = xposition; + HPVector rpos = xposition; int r_speed = [rock maxFlightSpeed] > 0 ? 20.0 * [rock maxFlightSpeed] : 10; int cr = (collision_radius > 10 * rock->collision_radius) ? collision_radius : 3 * rock->collision_radius; rpos.x += (ranrot_rand() % cr) - cr/2; @@ -7956,7 +7960,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) ShipEntity* rock = [UNIVERSE newShipWithRole:debrisRole]; // retain count = 1 if (rock) { - Vector rpos = xposition; + HPVector rpos = xposition; int r_speed = [rock maxFlightSpeed] > 0 ? 20.0 * [rock maxFlightSpeed] : 20; int cr = (collision_radius > 10 * rock->collision_radius) ? collision_radius : 3 * rock->collision_radius; rpos.x += (ranrot_rand() % cr) - cr/2; @@ -8006,7 +8010,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) [wreck rescaleBy: scale_factor]; Vector r1 = [octree randomPoint]; - Vector rpos = vector_add(quaternion_rotate_vector([self normalOrientation], r1), xposition); + HPVector rpos = HPvector_add(vectorToHPVector(quaternion_rotate_vector([self normalOrientation], r1)), xposition); [wreck setPosition:rpos]; [wreck setVelocity:[self velocity]]; @@ -8041,7 +8045,7 @@ NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context) ShipEntity* plate = [UNIVERSE newShipWithRole:@"alloy"]; // retain count = 1 if (plate) { - Vector rpos = xposition; + HPVector rpos = xposition; Vector rrand = OORandomPositionInBoundingBox(boundingBox); rpos.x += rrand.x; rpos.y += rrand.y; rpos.z += rrand.z; rpos.x += (ranrot_rand() % 7) - 3; @@ -8210,7 +8214,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q Vector i = vector_right_from_quaternion(q); Vector j = vector_up_from_quaternion(q); Vector k = vector_forward_from_quaternion(q); - BoundingBox arbb = [ship findBoundingBoxRelativeToPosition:kZeroVector InVectors:i :j :k]; + BoundingBox arbb = [ship findBoundingBoxRelativeToPosition:kZeroHPVector InVectors:i :j :k]; Vector result = kZeroVector; switch ([padAlign characterAtIndex:0]) { @@ -8257,7 +8261,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q - (void) becomeLargeExplosion:(double)factor { - Vector xposition = position; + HPVector xposition = position; OOCargoQuantity n_cargo = (ranrot_rand() % (likely_cargo + 1)); OOCargoQuantity cargo_to_go; @@ -8310,7 +8314,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q if (Ranrot() % 100 < cargo_chance) // 10% chance of any given piece of cargo surviving decompression { ShipEntity *container = [[cargo objectAtIndex:0] retain]; - Vector rpos = xposition; + HPVector rpos = xposition; Vector rrand = OORandomPositionInBoundingBox(boundingBox); rpos.x += rrand.x; rpos.y += rrand.y; rpos.z += rrand.z; rpos.x += (ranrot_rand() % 7) - 3; @@ -8485,7 +8489,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q { if (scan->isShip) { - distance2_scanned_ships[n_scanned_ships] = distance2(position, scan->position); + distance2_scanned_ships[n_scanned_ships] = HPdistance2(position, scan->position); if (distance2_scanned_ships[n_scanned_ships] < SCANNER_MAX_RANGE2) scanned_ships[n_scanned_ships++] = (ShipEntity*)scan; } @@ -8497,7 +8501,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q { if (scan->isShip) { - distance2_scanned_ships[n_scanned_ships] = distance2(position, scan->position); + distance2_scanned_ships[n_scanned_ships] = HPdistance2(position, scan->position); if (distance2_scanned_ships[n_scanned_ships] < SCANNER_MAX_RANGE2) scanned_ships[n_scanned_ships++] = (ShipEntity*)scan; } @@ -8825,32 +8829,32 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q } -- (Vector) destination +- (HPVector) destination { return destination; } -- (Vector) coordinates +- (HPVector) coordinates { return coordinates; } -- (void) setCoordinate:(Vector) coord // The name "setCoordinates" is already used by AI scripting. +- (void) setCoordinate:(HPVector) coord // The name "setCoordinates" is already used by AI scripting. { coordinates = coord; } -- (Vector) distance_six: (GLfloat) dist +- (HPVector) distance_six: (GLfloat) dist { - Vector six = position; + HPVector six = position; six.x -= dist * v_forward.x; six.y -= dist * v_forward.y; six.z -= dist * v_forward.z; return six; } -- (Vector) distance_twelve: (GLfloat) dist withOffset:(GLfloat)offset +- (HPVector) distance_twelve: (GLfloat) dist withOffset:(GLfloat)offset { - Vector twelve = position; + HPVector twelve = position; twelve.x += dist * v_up.x; twelve.y += dist * v_up.y; twelve.z += dist * v_up.z; twelve.x += offset * v_right.x; twelve.y += offset * v_right.y; twelve.z += offset * v_right.z; return twelve; @@ -8867,8 +8871,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q if (!target) return; - vector_to_target = target->position; - vector_to_target.x -= position.x; vector_to_target.y -= position.y; vector_to_target.z -= position.z; + vector_to_target = [self vectorTo:target]; // GLfloat range2 = magnitude2(vector_to_target); GLfloat targetRadius = 0.75 * target->collision_radius; @@ -8900,12 +8903,13 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q { Vector vector_to_target; Vector axis_to_track_by; - Vector my_position = position; // position relative to parent + HPVector my_position = [self absolutePositionForSubentity]; Vector my_aim = vector_forward_from_quaternion(orientation); Vector my_ref = reference; double aim_cos, ref_cos; Vector leading = [target velocity]; - Entity *last = nil; + +/* Entity *last = nil; Entity *father = [self parentEntity]; OOMatrix r_mat; @@ -8917,11 +8921,11 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q last = father; if (![last isSubEntity]) break; father = [father owner]; - } + }*/ if (target) { - vector_to_target = vector_subtract([target position], my_position); + vector_to_target = HPVectorToVector(HPvector_subtract([target position], my_position)); if (magnitude(vector_to_target) > weaponRange * 1.01) { return -2.0; // out of range @@ -9045,7 +9049,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q GLfloat d_forward, d_up, d_right; - Vector relPos = vector_subtract(target->position, position); + Vector relPos = [self vectorTo:target]; double range2 = magnitude2(relPos); @@ -9262,7 +9266,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q GLfloat d_forward, d_up, d_right; - Vector relPos = vector_subtract(target->position, position); + Vector relPos = [self vectorTo:target]; double range2 = magnitude2(relPos); if (range2 > SCANNER_MAX_RANGE2) @@ -9381,7 +9385,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q stick_pitch = 0.0; stick_yaw = 0.0; - relPos = vector_subtract(target->position, position); + relPos = [self vectorTo:target]; // Adjust missile course by taking into account target's velocity and missile // accuracy. Modification on original code contributed by Cmdr James. @@ -9492,7 +9496,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q reversePlayer = -1; } - relPos = vector_subtract(destination, position); + relPos = HPVectorToVector(HPvector_subtract(destination, position)); double range2 = magnitude2(relPos); double desired_range2 = desired_range*desired_range; @@ -9635,7 +9639,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q - (GLfloat) rangeToDestination { - return distance(position, destination); + return HPdistance(position, destination); } @@ -9699,16 +9703,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q - (double) rangeToPrimaryTarget { - double dist; - Vector delta; - Entity *target = [self primaryTarget]; - if (target == nil) // leave now! - return 0.0; - delta = vector_subtract(target->position, position); - dist = magnitude(delta); - dist -= target->collision_radius; - dist -= collision_radius; - return dist; + return [self rangeToSecondaryTarget:[self primaryTarget]]; } @@ -9718,7 +9713,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q Vector delta; if (target == nil) // leave now! return 0.0; - delta = vector_subtract(target->position, position); + delta = HPVectorToVector(HPvector_subtract(target->position, position)); dist = magnitude(delta); dist -= target->collision_radius; dist -= collision_radius; @@ -9736,7 +9731,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q } ShipEntity *ship_target = (ShipEntity *)target; - delta = vector_subtract(position, target->position); + delta = HPVectorToVector(HPvector_subtract(position, target->position)); return dot_product(vector_normal(delta), ship_target->v_forward); } @@ -9813,7 +9808,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q return NO; // 3/4 of the time you can't see from a lit place into a darker place } radius = target->collision_radius; - rel_pos = vector_subtract(target->position, position); + rel_pos = [self vectorTo:target]; d2 = magnitude2(rel_pos); urp = vector_normal_or_zbasis(rel_pos); @@ -10049,24 +10044,26 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q return NO; if ([[self rootShipEntity] isPlayer] && ![PLAYER weaponsOnline]) return NO; - - Vector origin = position; + + Vector vel; + HPVector origin = [self absolutePositionForSubentity]; + /* position; Entity *last = nil; Entity *father = [self parentEntity]; OOMatrix r_mat; - Vector vel; + while ((father)&&(father != last) && (father != NO_TARGET)) { r_mat = [father drawRotationMatrix]; - origin = vector_add(OOVectorMultiplyMatrix(origin, r_mat), [father position]); + origin = HPvector_add(OOHPVectorMultiplyMatrix(origin, r_mat), [father position]); last = father; if (![last isSubEntity]) break; father = [father owner]; - } + }*/ vel = vector_forward_from_quaternion(orientation); // Facing - origin = vector_add(origin, vector_multiply_scalar(vel, collision_radius + 0.5)); // Start just outside collision sphere + origin = HPvector_add(origin, vectorToHPVector(vector_multiply_scalar(vel, collision_radius + 0.5))); // Start just outside collision sphere vel = vector_multiply_scalar(vel, TURRET_SHOT_SPEED); // Shot velocity OOPlasmaShotEntity *shot = [[OOPlasmaShotEntity alloc] initWithPosition:origin @@ -10143,7 +10140,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q [shot setRange:hitAtRange]; Vector vd = vector_forward_from_quaternion([shot orientation]); - Vector flash_pos = vector_add([shot position], vector_multiply_scalar(vd, hitAtRange)); + HPVector flash_pos = HPvector_add([shot position], vectorToHPVector(vector_multiply_scalar(vd, hitAtRange))); [UNIVERSE addEntity:[OOFlashEffectEntity laserFlashWithPosition:flash_pos velocity:[victim velocity] color:laser_color]]; } } @@ -10160,7 +10157,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q victim = [parent primaryTarget]; Vector shotDirection = vector_forward_from_quaternion([shot orientation]); - Vector victimDirection = vector_normal(vector_subtract([victim position], [parent position])); + Vector victimDirection = vector_normal(HPVectorToVector(HPvector_subtract([victim position], [parent position]))); if (dot_product(shotDirection, victimDirection) > 0.995) // Within 84.26 degrees { [victim setPrimaryAggressor:parent]; @@ -10222,7 +10219,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q double range_limit2 = weaponRange*weaponRange; Vector r_pos; - r_pos = vector_normal_or_zbasis(vector_subtract(my_target->position, position)); + r_pos = vector_normal_or_zbasis([self vectorTo:my_target]); Quaternion q_laser = quaternion_rotation_between(r_pos, kBasisZVector); @@ -10265,7 +10262,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q [shot setRange:hit_at_range]; Vector vd = vector_forward_from_quaternion([shot orientation]); - Vector flash_pos = vector_add([shot position], vector_multiply_scalar(vd, hit_at_range)); + HPVector flash_pos = HPvector_add([shot position], vectorToHPVector(vector_multiply_scalar(vd, hit_at_range))); [UNIVERSE addEntity:[OOFlashEffectEntity laserFlashWithPosition:flash_pos velocity:[victim velocity] color:laser_color]]; } } @@ -10346,7 +10343,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q [shot setRange:hit_at_range]; Vector vd = vector_forward_from_quaternion([shot orientation]); - Vector flash_pos = vector_add([shot position], vector_multiply_scalar(vd, hit_at_range)); + HPVector flash_pos = HPvector_add([shot position], vectorToHPVector(vector_multiply_scalar(vd, hit_at_range))); [UNIVERSE addEntity:[OOFlashEffectEntity laserFlashWithPosition:flash_pos velocity:[victim velocity] color:laser_color]]; } } @@ -10363,7 +10360,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q * without having their target actually targeted. Though in those * circumstances they shouldn't be missing their first shot * anyway. */ - if (dot_product(vector_forward_from_quaternion([shot orientation]),vector_normal(vector_subtract([victim position],[self position]))) > 0.995) + if (dot_product(vector_forward_from_quaternion([shot orientation]),vector_normal([self vectorTo:victim])) > 0.995) { /* plausibly aimed at target. Allows reaction before attacker * actually hits. But we need to be able to distinguish in AI @@ -10430,7 +10427,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q randf() * (boundingBox.max.y - boundingBox.min.y) + boundingBox.min.y, randf() * boundingBox.max.z + boundingBox.min.z // rear section only }; - Vector origin = vector_add(position, quaternion_rotate_vector([self normalOrientation], offset)); + HPVector origin = HPvector_add(position, vectorToHPVector(quaternion_rotate_vector([self normalOrientation], offset))); float w = boundingBox.max.x - boundingBox.min.x; float h = boundingBox.max.y - boundingBox.min.y; @@ -10438,7 +10435,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q float sz = m * (1 + randf() + randf()); // half minimum dimension on average - Vector vel = vector_multiply_scalar(vector_subtract(origin, position), 2.0); + Vector vel = vector_multiply_scalar(HPVectorToVector(HPvector_subtract(origin, position)), 2.0); OOColor *color = [OOColor colorWithHue:0.08 + 0.17 * randf() saturation:1.0 brightness:1.0 alpha:1.0]; @@ -10465,7 +10462,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q - (BOOL) firePlasmaShotAtOffset:(double)offset speed:(double)speed color:(OOColor *)color direction:(OOWeaponFacing)direction { Vector vel, rt; - Vector origin = position; + HPVector origin = position; double start = collision_radius + 0.5; speed += flightSpeed; @@ -10513,13 +10510,13 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q if (vector_equal(plasmaPortOffset, kZeroVector)) { - origin = vector_add(origin, vector_multiply_scalar(vel, start)); // no WeaponOffset defined + origin = HPvector_add(origin, vectorToHPVector(vector_multiply_scalar(vel, start))); // no WeaponOffset defined } else { - origin = vector_add(origin, quaternion_rotate_vector([self normalOrientation], plasmaPortOffset)); + origin = HPvector_add(origin, vectorToHPVector(quaternion_rotate_vector([self normalOrientation], plasmaPortOffset))); } - origin = vector_add(origin, vector_multiply_scalar(rt, offset)); // With 'offset > 0' we get a twin-cannon. + origin = HPvector_add(origin, vectorToHPVector(vector_multiply_scalar(rt, offset))); // With 'offset > 0' we get a twin-cannon. vel = vector_multiply_scalar(vel, speed); @@ -10641,7 +10638,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q vel = vector_add(vel, vector_multiply_scalar(v_forward, flightSpeed + throw_speed)); Quaternion q1 = [self normalOrientation]; - Vector origin = vector_add(position, quaternion_rotate_vector(q1, start)); + HPVector origin = HPvector_add(position, vectorToHPVector(quaternion_rotate_vector(q1, start))); if (isPlayer) [missile setScanClass: CLASS_MISSILE]; @@ -10781,12 +10778,12 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q double start = collision_radius + bomb->collision_radius; Quaternion random_direction; Vector vel; - Vector rpos; + HPVector rpos; double random_roll = randf() - 0.5; // -0.5 to +0.5 double random_pitch = randf() - 0.5; // -0.5 to +0.5 quaternion_set_random(&random_direction); - rpos = vector_subtract([self position], vector_multiply_scalar(v_forward, start)); + rpos = HPvector_subtract([self position], vectorToHPVector(vector_multiply_scalar(v_forward, start))); double eject_speed = -800.0; vel = vector_multiply_scalar(v_forward, [self flightSpeed] + eject_speed); @@ -10922,7 +10919,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q Quaternion jetto_orientation = kIdentityQuaternion; Vector vel, v_eject, v_eject_normal; - Vector rpos = position; + HPVector rpos = position; double jetto_roll = 0; double jetto_pitch = 0; @@ -10945,7 +10942,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q } v_eject = quaternion_rotate_vector([self normalOrientation], start); - rpos = vector_add(rpos, v_eject); + rpos = HPvector_add(rpos, vectorToHPVector(v_eject)); v_eject = vector_normal(v_eject); v_eject_normal = v_eject; @@ -11027,7 +11024,8 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q - (BOOL) collideWithShip:(ShipEntity *)other { - Vector loc; + HPVector hploc; + Vector loc; double dam1, dam2; if (!other) @@ -11036,7 +11034,9 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q ShipEntity* otherParent = [other parentEntity]; BOOL otherIsStation = other == [UNIVERSE station]; // calculate line of centers using centres - loc = vector_normal_or_zbasis(vector_subtract([other absolutePositionForSubentity], position)); + hploc = HPvector_normal_or_zbasis(HPvector_subtract([other absolutePositionForSubentity], position)); + loc = HPVectorToVector(hploc); + if ([self canScoop:other]) { @@ -11091,7 +11091,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q if (v2b < -1.0f) return NO; else { - position = vector_subtract(position, loc); // adjust self position + position = HPvector_subtract(position, hploc); // adjust self position v = kZeroVector; // go for the 1m/s solution } } @@ -11157,12 +11157,12 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q { float t = 10.0 * [UNIVERSE getTimeDelta]; // 10 ticks - Vector pos1a = vector_add([self position], vector_multiply_scalar(loc, t * v1a)); + HPVector pos1a = HPvector_add([self position], vectorToHPVector(vector_multiply_scalar(loc, t * v1a))); [self setPosition:pos1a]; if (!otherIsStation) { - Vector pos2a = vector_add([other position], vector_multiply_scalar(loc, t * v2b)); + HPVector pos2a = HPvector_add([other position], vectorToHPVector(vector_multiply_scalar(loc, t * v2b))); [other setPosition:pos2a]; } } @@ -11218,10 +11218,10 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q if ([other isStation]) return NO; - Vector loc = vector_between(position, [other position]); + HPVector loc = HPvector_between(position, [other position]); - if (dot_product(v_forward, loc) < 0.0f) return NO; // Must be in front of us - if ([self isPlayer] && dot_product(v_up, loc) > 0.0f) return NO; // player has to scoop on underside, give more flexibility to NPCs + if (dot_product(v_forward, HPVectorToVector(loc)) < 0.0f) return NO; // Must be in front of us + if ([self isPlayer] && dot_product(v_up, HPVectorToVector(loc)) > 0.0f) return NO; // player has to scoop on underside, give more flexibility to NPCs return YES; } @@ -11964,14 +11964,14 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q } -- (void) setDestination:(Vector) dest +- (void) setDestination:(HPVector) dest { destination = dest; frustration = 0.0; // new destination => no frustration! } -- (void) setEscortDestination:(Vector) dest +- (void) setEscortDestination:(HPVector) dest { destination = dest; // don't reset frustration for escorts. } @@ -12112,7 +12112,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q } -- (Vector) coordinatesForEscortPosition:(unsigned)idx +- (HPVector) coordinatesForEscortPosition:(unsigned)idx { /* This function causes problems with Thargoids: their missiles (aka Thargons) are automatically @@ -12126,7 +12126,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q // Kludge: return the same last escort position if we have escorts above MAX_ESCORTS... idx = MIN(idx, (unsigned)(MAX_ESCORTS - 1)); - return vector_add(self->position, quaternion_rotate_vector([self normalOrientation], _escortPositions[idx])); + return HPvector_add(self->position, vectorToHPVector(quaternion_rotate_vector([self normalOrientation], _escortPositions[idx]))); } @@ -12245,7 +12245,7 @@ Vector positionOffsetForShipInRotationToAlignment(ShipEntity* ship, Quaternion q for (i = 0; i < station_count; i++) { thing = (StationEntity *)my_entities[i]; - range2 = distance2(position, thing->position); + range2 = HPdistance2(position, thing->position); if (range2 < nearest2 && (includeHostiles || ![thing isHostileTo:self])) { station = thing; @@ -12362,7 +12362,7 @@ static BOOL AuthorityPredicate(Entity *entity, void *parameter) // Select police units in scanner range if ([entity scanClass] == CLASS_POLICE && - distance2([victim position], [entity position]) < SCANNER_MAX_RANGE2) + HPdistance2([victim position], [entity position]) < SCANNER_MAX_RANGE2) { return YES; } @@ -12410,7 +12410,7 @@ static BOOL AuthorityPredicate(Entity *entity, void *parameter) if (!other_ship || !message_text) return; if (!crew && !unpilotedOverride) return; - double d2 = distance2(position, [other_ship position]); + double d2 = HPdistance2(position, [other_ship position]); if (d2 > scannerRange * scannerRange) return; // out of comms range @@ -12437,7 +12437,7 @@ static BOOL AuthorityPredicate(Entity *entity, void *parameter) [lastRadioMessage autorelease]; lastRadioMessage = [message_text retain]; - double d2 = distance2(position, [other_ship position]); + double d2 = HPdistance2(position, [other_ship position]); if (d2 > scannerRange * scannerRange) { // out of comms range @@ -12494,7 +12494,7 @@ static BOOL AuthorityPredicate(Entity *entity, void *parameter) } PlayerEntity *player = PLAYER; // make sure that the player always receives a message when in range - if (distance2(position, [player position]) < SCANNER_MAX_RANGE2) + if (HPdistance2(position, [player position]) < SCANNER_MAX_RANGE2) { [self setCommsMessageColor]; [player receiveCommsMessage:expandedMessage from:self]; @@ -12590,7 +12590,7 @@ static BOOL AuthorityPredicate(Entity *entity, void *parameter) - (BoundingBox) findBoundingBoxRelativeTo:(Entity *)other InVectors:(Vector) _i :(Vector) _j :(Vector) _k { - Vector opv = other ? other->position : position; + HPVector opv = other ? other->position : position; return [self findBoundingBoxRelativeToPosition:opv InVectors:_i :_j :_k]; } @@ -12646,8 +12646,8 @@ static BOOL AuthorityPredicate(Entity *entity, void *parameter) for (i = 0; (i < ship_count)&&(result == NO_TARGET) ; i++) { ShipEntity* ship = my_entities[i]; - Vector delta = vector_between(position, ship->position); - GLfloat d2 = magnitude2(delta); + HPVector delta = HPvector_between(position, ship->position); + GLfloat d2 = HPmagnitude2(delta); if (![ship isPlayer] || ![PLAYER isDocked]) { // player doesn't block if docked if ((k * [ship mass] > d2)&&(d2 < SCANNER_MAX_RANGE2)) // if you go off scanner from a blocker - it ceases to block @@ -12794,8 +12794,8 @@ static BOOL AuthorityPredicate(Entity *entity, void *parameter) id target = [self primaryTarget]; if (target == nil) target = @""; OOLog(@"dumpState.shipEntity", @"Target: %@", target); - OOLog(@"dumpState.shipEntity", @"Destination: %@", VectorDescription(destination)); - OOLog(@"dumpState.shipEntity", @"Other destination: %@", VectorDescription(coordinates)); + OOLog(@"dumpState.shipEntity", @"Destination: %@", HPVectorDescription(destination)); + OOLog(@"dumpState.shipEntity", @"Other destination: %@", HPVectorDescription(coordinates)); OOLog(@"dumpState.shipEntity", @"Waypoint count: %u", number_of_navpoints); OOLog(@"dumpState.shipEntity", @"Desired speed: %g", desired_speed); OOLog(@"dumpState.shipEntity", @"Thrust: %g", thrust); diff --git a/src/Core/Entities/ShipEntityAI.m b/src/Core/Entities/ShipEntityAI.m index 944e6314..5fdef428 100644 --- a/src/Core/Entities/ShipEntityAI.m +++ b/src/Core/Entities/ShipEntityAI.m @@ -361,7 +361,7 @@ ShipEntity *targEnt = [self primaryTarget]; double found_d2 = scannerRange * scannerRange; - if (targEnt && (distance2(position, [targEnt position]) < found_d2)) + if (targEnt && (HPdistance2(position, [targEnt position]) < found_d2)) { if ([targEnt isWormhole]) whole = (WormholeEntity *)targEnt; @@ -385,7 +385,7 @@ for (i = 0; i < wh_count ; i++) { WormholeEntity *wh = wormholes[i]; - double d2 = distance2(position, wh->position); + double d2 = HPdistance2(position, wh->position); if (d2 < found_d2) { whole = wh; @@ -530,14 +530,14 @@ - (void) setDestinationToCurrentLocation { // randomly add a .5m variance - destination = vector_add(position, OOVectorRandomSpatial(0.5)); + destination = HPvector_add(position, OOHPVectorRandomSpatial(0.5)); } - (void) setDestinationToJinkPosition { Vector front = vector_multiply_scalar([self forwardVector], flightSpeed / max_flight_pitch * 2); - destination = vector_add(position, vector_add(front, OOVectorRandomSpatial(100))); + destination = HPvector_add(position, vectorToHPVector(vector_add(front, OOVectorRandomSpatial(100)))); pitching_over = YES; // don't complete roll first, but immediately start with pitching. } @@ -896,7 +896,7 @@ if (!UNIVERSE) { Vector vr = vector_multiply_scalar(v_forward, maxFlightSpeed * 10.0); // 10 second flying away - coordinates = vector_add(position, vr); + coordinates = HPvector_add(position, vectorToHPVector(vr)); return; } // @@ -909,15 +909,15 @@ parameter:nil relativeToEntity:self]; - if (station && distance2([station position], position) < SCANNER_MAX_RANGE2) // there is a station in range. + if (station && HPdistance2([station position], position) < SCANNER_MAX_RANGE2) // there is a station in range. { Vector vr = vector_multiply_scalar([station rightVector], 10000); // 10km from station - coordinates = vector_add([station position], vr); + coordinates = HPvector_add([station position], vectorToHPVector(vr)); } else { Vector vr = vector_multiply_scalar(v_forward, maxFlightSpeed * 10.0); // 10 second flying away - coordinates = vector_add(position, vr); + coordinates = HPvector_add(position, vectorToHPVector(vr)); } } @@ -1028,15 +1028,15 @@ if (the_planet) { double variation = (aegis_status == AEGIS_NONE ? 0.5 : 0.2); // more random deviation when far from planet. - Vector p_pos = the_planet->position; + HPVector p_pos = the_planet->position; double p_cr = the_planet->collision_radius; // the surface - Vector p1 = vector_between(p_pos, position); - p1 = vector_normal(p1); // vector towards ship + HPVector p1 = HPvector_between(p_pos, position); + p1 = HPvector_normal(p1); // vector towards ship p1.x += variation * (randf() - variation); p1.y += variation * (randf() - variation); p1.z += variation * (randf() - variation); - p1 = vector_normal(p1); - destination = vector_add(p_pos, vector_multiply_scalar(p1, p_cr)); // on surface + p1 = HPvector_normal(p1); + destination = HPvector_add(p_pos, HPvector_multiply_scalar(p1, p_cr)); // on surface desired_range = collision_radius + 100.0; // +100m from the destination } else @@ -1052,8 +1052,8 @@ OOPlanetEntity *the_planet = [self findNearestPlanet]; if (the_planet) { - destination = vector_add([the_planet position], vector_multiply_scalar( - vector_normal(vector_subtract([the_planet position],position)),-10000.0-the_planet->collision_radius));// 10km straight up + destination = HPvector_add([the_planet position], HPvector_multiply_scalar( + HPvector_normal(HPvector_subtract([the_planet position],position)),-10000.0-the_planet->collision_radius));// 10km straight up desired_range = 50.0; } else @@ -1167,11 +1167,11 @@ Entity *the_target = [self primaryTarget]; if (the_target) { - Vector pos = the_target->position; + HPVector pos = the_target->position; Quaternion q; quaternion_set_random(&q); Vector v = vector_forward_from_quaternion(q); GLfloat d = (randf() - randf()) * the_target->collision_radius; - destination = make_vector(pos.x + d * v.x, pos.y + d * v.y, pos.z + d * v.z); + destination = make_HPvector(pos.x + d * v.x, pos.y + d * v.y, pos.z + d * v.z); } } @@ -1180,7 +1180,7 @@ { Entity *hazard = [UNIVERSE hazardOnRouteFromEntity: self toDistance: desired_range fromPoint: destination]; - if (hazard == nil || ([hazard isShip] && distance(position, [hazard position]) > scannerRange) || ([hazard isPlanet] && aegis_status == AEGIS_NONE)) + if (hazard == nil || ([hazard isShip] && HPdistance(position, [hazard position]) > scannerRange) || ([hazard isPlanet] && aegis_status == AEGIS_NONE)) [shipAI message:@"COURSE_OK"]; // Avoid going into a waypoint.plist for far away objects, it cripples the main AI a bit in its funtionality. else { @@ -1541,7 +1541,7 @@ double maxRange2 = scannerRange * scannerRange; - if (mother && mother != self && magnitude2(vector_subtract(mother->position, position)) < maxRange2) + if (mother && mother != self && HPdistance2(mother->position, position) < maxRange2) { [shipAI message:@"TARGET_FOUND"]; // no need for scanning, we still have our mother. } @@ -1797,47 +1797,47 @@ - (void) setPlanetPatrolCoordinates { // check we've arrived near the last given coordinates - Vector r_pos = vector_subtract(position, coordinates); - if (magnitude2(r_pos) < 1000000 || patrol_counter == 0) + HPVector r_pos = HPvector_subtract(position, coordinates); + if (HPmagnitude2(r_pos) < 1000000 || patrol_counter == 0) { Entity *the_sun = [UNIVERSE sun]; ShipEntity *the_station = [[self group] leader]; if(!the_station || ![the_station isStation]) the_station = [UNIVERSE station]; if ((!the_sun)||(!the_station)) return; - Vector sun_pos = the_sun->position; - Vector stn_pos = the_station->position; - Vector sun_dir = make_vector(sun_pos.x - stn_pos.x, sun_pos.y - stn_pos.y, sun_pos.z - stn_pos.z); + HPVector sun_pos = the_sun->position; + HPVector stn_pos = the_station->position; + HPVector sun_dir = HPvector_subtract(sun_pos,stn_pos); Vector vSun = make_vector(0, 0, 1); if (sun_dir.x||sun_dir.y||sun_dir.z) - vSun = vector_normal(sun_dir); + vSun = HPVectorToVector(HPvector_normal(sun_dir)); Vector v0 = [the_station forwardVector]; Vector v1 = cross_product(v0, vSun); Vector v2 = cross_product(v0, v1); switch (patrol_counter) { case 0: // first go to 5km ahead of the station - coordinates = make_vector(stn_pos.x + 5000 * v0.x, stn_pos.y + 5000 * v0.y, stn_pos.z + 5000 * v0.z); + coordinates = make_HPvector(stn_pos.x + 5000 * v0.x, stn_pos.y + 5000 * v0.y, stn_pos.z + 5000 * v0.z); desired_range = 250.0; break; case 1: // go to 25km N of the station - coordinates = make_vector(stn_pos.x + 25000 * v1.x, stn_pos.y + 25000 * v1.y, stn_pos.z + 25000 * v1.z); + coordinates = make_HPvector(stn_pos.x + 25000 * v1.x, stn_pos.y + 25000 * v1.y, stn_pos.z + 25000 * v1.z); desired_range = 250.0; break; case 2: // go to 25km E of the station - coordinates = make_vector(stn_pos.x + 25000 * v2.x, stn_pos.y + 25000 * v2.y, stn_pos.z + 25000 * v2.z); + coordinates = make_HPvector(stn_pos.x + 25000 * v2.x, stn_pos.y + 25000 * v2.y, stn_pos.z + 25000 * v2.z); desired_range = 250.0; break; case 3: // go to 25km S of the station - coordinates = make_vector(stn_pos.x - 25000 * v1.x, stn_pos.y - 25000 * v1.y, stn_pos.z - 25000 * v1.z); + coordinates = make_HPvector(stn_pos.x - 25000 * v1.x, stn_pos.y - 25000 * v1.y, stn_pos.z - 25000 * v1.z); desired_range = 250.0; break; case 4: // go to 25km W of the station - coordinates = make_vector(stn_pos.x - 25000 * v2.x, stn_pos.y - 25000 * v2.y, stn_pos.z - 25000 * v2.z); + coordinates = make_HPvector(stn_pos.x - 25000 * v2.x, stn_pos.y - 25000 * v2.y, stn_pos.z - 25000 * v2.z); desired_range = 250.0; break; default: // We should never come here - coordinates = make_vector(stn_pos.x + 5000 * v0.x, stn_pos.y + 5000 * v0.y, stn_pos.z + 5000 * v0.z); + coordinates = make_HPvector(stn_pos.x + 5000 * v0.x, stn_pos.y + 5000 * v0.y, stn_pos.z + 5000 * v0.z); desired_range = 250.0; break; } @@ -1870,9 +1870,9 @@ return; } - Vector v0 = [UNIVERSE getSunSkimStartPositionForShip:self]; + HPVector v0 = [UNIVERSE getSunSkimStartPositionForShip:self]; - if (!vector_equal(v0, kZeroVector)) + if (!HPvector_equal(v0, kZeroHPVector)) { coordinates = v0; [shipAI message:@"APPROACH_COORDINATES"]; @@ -1901,11 +1901,11 @@ { Entity *the_sun = [UNIVERSE sun]; if (the_sun == nil) return; - Vector v1 = [UNIVERSE getSunSkimEndPositionForShip:self]; - Vector vs = the_sun->position; - Vector vout = make_vector(v1.x - vs.x, v1.y - vs.y, v1.z - vs.z); + HPVector v1 = [UNIVERSE getSunSkimEndPositionForShip:self]; + HPVector vs = the_sun->position; + HPVector vout = HPvector_subtract(v1,vs); if (vout.x||vout.y||vout.z) - vout = vector_normal(vout); + vout = HPvector_normal(vout); else vout.z = 1.0; v1.x += 10000 * vout.x; v1.y += 10000 * vout.y; v1.z += 10000 * vout.z; @@ -1931,10 +1931,9 @@ [shipAI message:@"NOTHING_FOUND"]; return; } - Vector v0 = motherStation->position; - Vector rpos = make_vector(position.x - v0.x, position.y - v0.y, position.z - v0.z); double found_d2 = scannerRange * scannerRange; - if (magnitude2(rpos) > found_d2) + HPVector v0 = motherStation->position; + if (HPdistance2(v0,position) > found_d2) { [shipAI message:@"NOTHING_FOUND"]; return; @@ -2005,7 +2004,7 @@ if (oldTarget && ![oldTarget isCloaked]) { - GLfloat range2 = distance2([oldTarget position], position); + GLfloat range2 = HPdistance2([oldTarget position], position); if (range2 <= scannerRange * scannerRange && range2 <= SCANNER_MAX_RANGE2) { found = YES; @@ -2089,11 +2088,11 @@ { Entity *the_target = [self targetStation]; double bo_distance = 8000; // 8km back off - Vector v0 = position; - Vector d0 = (the_target) ? the_target->position : kZeroVector; + HPVector v0 = position; + HPVector d0 = (the_target) ? the_target->position : kZeroHPVector; v0.x += (randf() - 0.5)*collision_radius; v0.y += (randf() - 0.5)*collision_radius; v0.z += (randf() - 0.5)*collision_radius; v0.x -= d0.x; v0.y -= d0.y; v0.z -= d0.z; - v0 = vector_normal_or_fallback(v0, make_vector(0, 0, -1)); + v0 = HPvector_normal_or_fallback(v0, make_HPvector(0, 0, -1)); v0.x *= bo_distance; v0.y *= bo_distance; v0.z *= bo_distance; v0.x += d0.x; v0.y += d0.y; v0.z += d0.z; @@ -2341,7 +2340,7 @@ if ([zString hasPrefix:@"rand:"]) zString = [NSString stringWithFormat:@"%.3f", bellf([(NSString*)[[zString componentsSeparatedByString:@":"] objectAtIndex:1] intValue])]; - Vector posn = make_vector([xString floatValue], [yString floatValue], [zString floatValue]); + HPVector posn = make_HPvector([xString floatValue], [yString floatValue], [zString floatValue]); GLfloat scalar = 1.0; coordinates = [UNIVERSE coordinatesForPosition:posn withCoordinateSystem:systemString returningScalar:&scalar]; @@ -2376,7 +2375,7 @@ if (uni_entities[i]->isStation) { my_station = (StationEntity*)uni_entities[i]; - if ([my_station maxFlightSpeed] == 0 && [my_station hasNPCTraffic] && distance2(position, [my_station position]) < maxRange2) + if ([my_station maxFlightSpeed] == 0 && [my_station hasNPCTraffic] && HPdistance2(position, [my_station position]) < maxRange2) { my_entities[station_count++] = [uni_entities[i] retain]; // retained } @@ -2451,7 +2450,7 @@ relativeToEntity:self]; } - distanceToStation2 = distance2([station position], [self position]); + distanceToStation2 = HPdistance2([station position], [self position]); // Player check for being inside the aegis already exists in PlayerEntityControls. We just // check here that distance to station is less than 2.5 times scanner range to avoid problems with @@ -2490,7 +2489,7 @@ { if (dockingInstructions != nil) { - destination = [dockingInstructions oo_vectorForKey:@"destination"]; + destination = [dockingInstructions oo_hpvectorForKey:@"destination"]; desired_speed = fmin([dockingInstructions oo_floatForKey:@"speed"], maxFlightSpeed); desired_range = [dockingInstructions oo_floatForKey:@"range"]; if ([dockingInstructions objectForKey:@"station"]) @@ -2672,10 +2671,10 @@ } Vector k = ship->v_forward; GLfloat c = ship->collision_radius; - Vector o = ship->position; - navpoints[0] = make_vector(o.x - c * k.x, o.y - c * k.y, o.z - c * k.z); - navpoints[1] = make_vector(o.x + c * k.x, o.y + c * k.y, o.z + c * k.z); - navpoints[2] = make_vector(o.x + 2.0 * c * k.x, o.y + 2.0 * c * k.y, o.z + 2.0 * c * k.z); + HPVector o = ship->position; + navpoints[0] = make_HPvector(o.x - c * k.x, o.y - c * k.y, o.z - c * k.z); + navpoints[1] = make_HPvector(o.x + c * k.x, o.y + c * k.y, o.z + c * k.z); + navpoints[2] = make_HPvector(o.x + 2.0 * c * k.x, o.y + 2.0 * c * k.y, o.z + 2.0 * c * k.z); number_of_navpoints = 2; next_navpoint_index = 0; destination = navpoints[0]; diff --git a/src/Core/Entities/ShipEntityLoadRestore.m b/src/Core/Entities/ShipEntityLoadRestore.m index b582a68a..ac2f7221 100644 --- a/src/Core/Entities/ShipEntityLoadRestore.m +++ b/src/Core/Entities/ShipEntityLoadRestore.m @@ -97,9 +97,9 @@ static OOShipGroup *GroupForGroupID(NSUInteger groupID, NSMutableDictionary *con [result setObject:updatedShipInfo forKey:KEY_SHIPDATA_OVERRIDES]; if (deletes != nil) [result setObject:deletes forKey:KEY_SHIPDATA_DELETES]; - if (!vector_equal([self position], kZeroVector)) + if (!HPvector_equal([self position], kZeroHPVector)) { - [result oo_setVector:[self position] forKey:KEY_POSITION]; + [result oo_setHPVector:[self position] forKey:KEY_POSITION]; } if (!quaternion_equal([self normalOrientation], kIdentityQuaternion)) { @@ -203,7 +203,7 @@ static OOShipGroup *GroupForGroupID(NSUInteger groupID, NSMutableDictionary *con } // The following stuff is deliberately set up the same way even if using role fallback. - [ship setPosition:[dict oo_vectorForKey:KEY_POSITION]]; + [ship setPosition:[dict oo_hpvectorForKey:KEY_POSITION]]; [ship setNormalOrientation:[dict oo_quaternionForKey:KEY_ORIENTATION]]; float energyLevel = [dict oo_floatForKey:KEY_ENERGY_LEVEL defaultValue:1.0f]; diff --git a/src/Core/Entities/StationEntity.h b/src/Core/Entities/StationEntity.h index f95ea3a4..11eb1699 100644 --- a/src/Core/Entities/StationEntity.h +++ b/src/Core/Entities/StationEntity.h @@ -128,7 +128,7 @@ typedef enum - (Vector) virtualPortDimensions; - (DockEntity*) playerReservedDock; -- (Vector) beaconPosition; +- (HPVector) beaconPosition; - (float) equipmentPriceFactor; @@ -226,4 +226,4 @@ typedef enum -NSDictionary *OOMakeDockingInstructions(StationEntity *station, Vector coords, float speed, float range, NSString *ai_message, NSString *comms_message, BOOL match_rotation); +NSDictionary *OOMakeDockingInstructions(StationEntity *station, HPVector coords, float speed, float range, NSString *ai_message, NSString *comms_message, BOOL match_rotation); diff --git a/src/Core/Entities/StationEntity.m b/src/Core/Entities/StationEntity.m index 30f191f4..ad887f98 100644 --- a/src/Core/Entities/StationEntity.m +++ b/src/Core/Entities/StationEntity.m @@ -99,11 +99,11 @@ MA 02110-1301, USA. } -- (Vector) beaconPosition +- (HPVector) beaconPosition { double buoy_distance = 10000.0; // distance from station entrance Vector v_f = vector_forward_from_quaternion([self orientation]); - Vector result = vector_add([self position], vector_multiply_scalar(v_f, buoy_distance)); + HPVector result = HPvector_add([self position], vectorToHPVector(vector_multiply_scalar(v_f, buoy_distance))); return result; } @@ -458,10 +458,10 @@ MA 02110-1301, USA. } -NSDictionary *OOMakeDockingInstructions(StationEntity *station, Vector coords, float speed, float range, NSString *ai_message, NSString *comms_message, BOOL match_rotation) +NSDictionary *OOMakeDockingInstructions(StationEntity *station, HPVector coords, float speed, float range, NSString *ai_message, NSString *comms_message, BOOL match_rotation) { NSMutableDictionary *acc = [NSMutableDictionary dictionaryWithCapacity:8]; - [acc setObject:[NSString stringWithFormat:@"%.2f %.2f %.2f", coords.x, coords.y, coords.z] forKey:@"destination"]; + [acc oo_setHPVector:coords forKey:@"destination"]; [acc oo_setFloat:speed forKey:@"speed"]; [acc oo_setFloat:range forKey:@"range"]; [acc setObject:[[station weakRetain] autorelease] forKey:@"station"]; @@ -2419,7 +2419,7 @@ NSDictionary *OOMakeDockingInstructions(StationEntity *station, Vector coords, f unsigned i = 1; while ((ship = [onHoldEnum nextObject])) { - OOLog(@"dumpState.stationEntity", @"Nr %i: %@ at distance %g with role: %@", i++, [ship displayName], distance([self position], [ship position]), [ship primaryRole]); + OOLog(@"dumpState.stationEntity", @"Nr %i: %@ at distance %g with role: %@", i++, [ship displayName], HPdistance([self position], [ship position]), [ship primaryRole]); } OOLogOutdent(); } diff --git a/src/Core/Entities/WormholeEntity.h b/src/Core/Entities/WormholeEntity.h index 4b488ff5..59cc8798 100644 --- a/src/Core/Entities/WormholeEntity.h +++ b/src/Core/Entities/WormholeEntity.h @@ -78,7 +78,7 @@ typedef enum - (BOOL) suckInShip:(ShipEntity *) ship; - (void) disgorgeShips; -- (void) setExitPosition:(Vector)pos; +- (void) setExitPosition:(HPVector)pos; - (Random_Seed) origin; - (Random_Seed) destination; diff --git a/src/Core/Entities/WormholeEntity.m b/src/Core/Entities/WormholeEntity.m index 0e6d3837..925234b4 100644 --- a/src/Core/Entities/WormholeEntity.m +++ b/src/Core/Entities/WormholeEntity.m @@ -110,7 +110,7 @@ static void DrawWormholeCorona(GLfloat inner_radius, GLfloat outer_radius, int s // Since this is new for 1.75.1, we must give it a default values as we could be loading an old savegame estimated_arrival_time = [dict oo_doubleForKey:@"estimated_arrival_time" defaultValue:arrival_time]; - position = [dict oo_vectorForKey:@"position"]; + position = [dict oo_hpvectorForKey:@"position"]; _misjump = [dict oo_boolForKey:@"misjump" defaultValue:NO]; @@ -189,7 +189,7 @@ static void DrawWormholeCorona(GLfloat inner_radius, GLfloat outer_radius, int s expiry_time = arrival_time - 1.0; } position = [ship position]; - zero_distance = distance2([PLAYER position], position); + zero_distance = HPdistance2([PLAYER position], position); } return self; } @@ -275,7 +275,7 @@ static void DrawWormholeCorona(GLfloat inner_radius, GLfloat outer_radius, int s // MKW 2010.11.18 - calculate time it takes for ship to reach wormhole // This is for AI ships which get told to enter the wormhole even though they // may still be some distance from it when the player exits the system - float d = distance(position, [ship position]); + float d = HPdistance(position, [ship position]); d -= [ship collisionRadius] + [self collisionRadius]; if (d > 0.0f) { @@ -379,7 +379,7 @@ static void DrawWormholeCorona(GLfloat inner_radius, GLfloat outer_radius, int s if (hasExitPosition && (!containsPlayer || useExitXYScatter)) { - Vector shippos; + HPVector shippos; Vector exit_vector_x = vector_right_from_quaternion([UNIVERSE getWitchspaceExitRotation]); Vector exit_vector_y = vector_up_from_quaternion([UNIVERSE getWitchspaceExitRotation]); // entry wormhole has a radius of around 100m (or perhaps more) @@ -468,7 +468,7 @@ static void DrawWormholeCorona(GLfloat inner_radius, GLfloat outer_radius, int s { // ships exiting the wormhole after now are following the player // so appear behind them - position = vector_add([PLAYER position], vector_multiply_scalar([PLAYER forwardVector], -500.0f)); + position = HPvector_add([PLAYER position], vectorToHPVector(vector_multiply_scalar([PLAYER forwardVector], -500.0f))); containsPlayer = NO; } // else, the wormhole doesn't now (or never) contained the player, so @@ -482,7 +482,7 @@ static void DrawWormholeCorona(GLfloat inner_radius, GLfloat outer_radius, int s } -- (void) setExitPosition:(Vector)pos +- (void) setExitPosition:(HPVector)pos { [self setPosition: pos]; hasExitPosition = YES; @@ -793,7 +793,7 @@ static void DrawWormholeCorona(GLfloat inner_radius, GLfloat outer_radius, int s [myDict oo_setFloat:(expiry_time) forKey:@"expiry_time"]; [myDict oo_setFloat:(arrival_time) forKey:@"arrival_time"]; [myDict oo_setFloat:(estimated_arrival_time) forKey:@"estimated_arrival_time"]; - [myDict oo_setVector:position forKey:@"position"]; + [myDict oo_setHPVector:position forKey:@"position"]; [myDict oo_setBool:_misjump forKey:@"misjump"]; NSMutableArray * shipArray = [NSMutableArray arrayWithCapacity:[shipsInTransit count]]; diff --git a/src/Core/HeadUpDisplay.m b/src/Core/HeadUpDisplay.m index afcb53f1..6f9cebec 100644 --- a/src/Core/HeadUpDisplay.m +++ b/src/Core/HeadUpDisplay.m @@ -1128,7 +1128,7 @@ static void prefetchData(NSDictionary *info, struct CachedInfo *data) } ms_blip -= floor(ms_blip); - relativePosition = vector_subtract([scannedEntity position], [PLAYER position]); + relativePosition = [PLAYER vectorTo:scannedEntity]; Vector rp = relativePosition; if (act_dist > max_zoomed_range) @@ -1360,7 +1360,6 @@ static void prefetchData(NSDictionary *info, struct CachedInfo *data) alpha = compass_color[3]; // draw the compass - Vector position = [PLAYER position]; OOMatrix rotMatrix = [PLAYER rotationMatrix]; GLfloat h1 = siz.height * 0.125; @@ -1443,7 +1442,8 @@ static void prefetchData(NSDictionary *info, struct CachedInfo *data) } // translate and rotate the view - Vector relativePosition = vector_subtract([reference position], position); + + Vector relativePosition = [PLAYER vectorTo:reference]; relativePosition = OOVectorMultiplyMatrix(relativePosition, rotMatrix); relativePosition = vector_normal_or_fallback(relativePosition, kBasisZVector); @@ -2358,7 +2358,6 @@ static OOPolygonSprite *IconForMissileRole(NSString *role) // draw the direction cue OOMatrix rotMatrix; - Vector position = [PLAYER position]; rotMatrix = [PLAYER rotationMatrix]; @@ -2371,7 +2370,7 @@ static OOPolygonSprite *IconForMissileRole(NSString *role) const float visMax = 0.984807753012208f; // cos(10 degrees) // Transform the view - Vector rpn = vector_subtract([target position], position); + Vector rpn = [PLAYER vectorTo:target]; rpn = OOVectorMultiplyMatrix(rpn, rotMatrix); Vector drawPos = rpn; Vector forward = kZeroVector; @@ -2482,7 +2481,7 @@ static OOPolygonSprite *IconForMissileRole(NSString *role) siz.width = useDefined(cached.width, FPSINFO_DISPLAY_WIDTH); siz.height = useDefined(cached.height, FPSINFO_DISPLAY_HEIGHT); - Vector playerPos = [PLAYER position]; + HPVector playerPos = [PLAYER position]; NSString *positionInfo = [UNIVERSE expressPosition:playerPos inCoordinateSystem:@"pwm"]; positionInfo = [NSString stringWithFormat:@"abs %.2f %.2f %.2f / %@", playerPos.x, playerPos.y, playerPos.z, positionInfo]; @@ -2873,7 +2872,8 @@ static void hudDrawReticleOnTarget(Entity *target, PlayerEntity *player1, GLfloa Vector v1 = vector_up_from_quaternion(back_q); Vector p1; - p1 = vector_subtract([target position], [player1 viewpointPosition]); + // by definition close enough that single precision is fine + p1 = HPVectorToVector(HPvector_subtract([target position], [player1 viewpointPosition])); GLfloat rdist = magnitude(p1); GLfloat rsize = [target collisionRadius]; diff --git a/src/Core/OOBoundingBox.h b/src/Core/OOBoundingBox.h index e22b0e25..cfd7fca6 100644 --- a/src/Core/OOBoundingBox.h +++ b/src/Core/OOBoundingBox.h @@ -55,6 +55,7 @@ OOINLINE void bounding_box_get_dimensions(BoundingBox bb, GLfloat *xSize, GLfloa OOINLINE Vector OOBoundingBoxCenter(BoundingBox bb) INLINE_CONST_FUNC; Vector OORandomPositionInBoundingBox(BoundingBox bb); +HPVector OOHPRandomPositionInBoundingBox(BoundingBox bb); diff --git a/src/Core/OOCollectionExtractors.h b/src/Core/OOCollectionExtractors.h index 09f74f50..c5b0b436 100644 --- a/src/Core/OOCollectionExtractors.h +++ b/src/Core/OOCollectionExtractors.h @@ -172,6 +172,7 @@ SOFTWARE. #ifndef OOCOLLECTIONEXTRACTORS_SIMPLE - (Vector) oo_vectorForKey:(id)key defaultValue:(Vector)value; +- (HPVector) oo_hpvectorForKey:(id)key defaultValue:(HPVector)value; - (Quaternion) oo_quaternionForKey:(id)key defaultValue:(Quaternion)value; #endif @@ -215,6 +216,8 @@ SOFTWARE. #ifndef OOCOLLECTIONEXTRACTORS_SIMPLE // Default: kZeroVector - (Vector) oo_vectorForKey:(id)key; +// Default: kZeroHPVector +- (HPVector) oo_hpvectorForKey:(id)key; // Default: kIdentityQuaternion - (Quaternion) oo_quaternionForKey:(id)key; #endif @@ -327,6 +330,7 @@ SOFTWARE. - (void) oo_setBool:(BOOL)value forKey:(id)key; #ifndef OOCOLLECTIONEXTRACTORS_SIMPLE - (void) oo_setVector:(Vector)value forKey:(id)key; +- (void) oo_setHPVector:(HPVector)value forKey:(id)key; - (void) oo_setQuaternion:(Quaternion)value forKey:(id)key; #endif @@ -379,9 +383,11 @@ double OONonNegativeDoubleFromObject(id object, double defaultValue); #ifndef OOCOLLECTIONEXTRACTORS_SIMPLE // These take strings, dictionaries or arrays. Vector OOVectorFromObject(id object, Vector defaultValue); +HPVector OOHPVectorFromObject(id object, HPVector defaultValue); Quaternion OOQuaternionFromObject(id object, Quaternion defaultValue); NSDictionary *OOPropertyListFromVector(Vector value); +NSDictionary *OOPropertyListFromHPVector(HPVector value); NSDictionary *OOPropertyListFromQuaternion(Quaternion value); #endif diff --git a/src/Core/OOCollectionExtractors.m b/src/Core/OOCollectionExtractors.m index 0e718aaf..9f566dd3 100644 --- a/src/Core/OOCollectionExtractors.m +++ b/src/Core/OOCollectionExtractors.m @@ -559,6 +559,11 @@ static NSString *StringForObject(id object, NSString *defaultValue); return OOVectorFromObject([self objectForKey:key], value); } +- (HPVector) oo_hpvectorForKey:(id)key defaultValue:(HPVector)value +{ + return OOHPVectorFromObject([self objectForKey:key], value); +} + - (Quaternion) oo_quaternionForKey:(id)key defaultValue:(Quaternion)value { @@ -719,6 +724,11 @@ static NSString *StringForObject(id object, NSString *defaultValue); return [self oo_vectorForKey:key defaultValue:kZeroVector]; } +- (HPVector) oo_hpvectorForKey:(id)key +{ + return [self oo_hpvectorForKey:key defaultValue:kZeroHPVector]; +} + - (Quaternion) oo_quaternionForKey:(id)key { @@ -1119,6 +1129,10 @@ static NSString *StringForObject(id object, NSString *defaultValue); [self setObject:OOPropertyListFromVector(value) forKey:key]; } +- (void) oo_setHPVector:(HPVector)value forKey:(id)key +{ + [self setObject:OOPropertyListFromHPVector(value) forKey:key]; +} - (void) oo_setQuaternion:(Quaternion)value forKey:(id)key { @@ -1411,6 +1425,40 @@ Vector OOVectorFromObject(id object, Vector defaultValue) return result; } +HPVector OOHPVectorFromObject(id object, HPVector defaultValue) +{ + HPVector result = defaultValue; + NSDictionary *dict = nil; + + if ([object isKindOfClass:[NSString class]]) + { + // This will only write result if a valid vector is found, and will write an error message otherwise. + ScanHPVectorFromString(object, &result); + } + else if ([object isKindOfClass:[NSArray class]] && [object count] == 3) + { + result.x = [object oo_doubleAtIndex:0]; + result.y = [object oo_doubleAtIndex:1]; + result.z = [object oo_doubleAtIndex:2]; + } + else if ([object isKindOfClass:[NSDictionary class]]) + { + dict = object; + // Require at least one of the keys x, y, or z + if ([dict objectForKey:@"x"] != nil || + [dict objectForKey:@"y"] != nil || + [dict objectForKey:@"z"] != nil) + { + // Note: uses 0 for unknown components rather than components of defaultValue. + result.x = [dict oo_doubleForKey:@"x" defaultValue:0.0]; + result.y = [dict oo_doubleForKey:@"y" defaultValue:0.0]; + result.z = [dict oo_doubleForKey:@"z" defaultValue:0.0]; + } + } + + return result; +} + Quaternion OOQuaternionFromObject(id object, Quaternion defaultValue) { @@ -1459,6 +1507,15 @@ NSDictionary *OOPropertyListFromVector(Vector value) nil]; } +NSDictionary *OOPropertyListFromHPVector(HPVector value) +{ + return [NSDictionary dictionaryWithObjectsAndKeys: + [NSNumber numberWithDouble:value.x], @"x", + [NSNumber numberWithDouble:value.y], @"y", + [NSNumber numberWithDouble:value.z], @"z", + nil]; +} + NSDictionary *OOPropertyListFromQuaternion(Quaternion value) { diff --git a/src/Core/OOHPVector.h b/src/Core/OOHPVector.h new file mode 100644 index 00000000..21f9dced --- /dev/null +++ b/src/Core/OOHPVector.h @@ -0,0 +1,354 @@ +/* + +OOHPVector.h + +Mathematical framework for Oolite. +High-precision vectors for world-space coordinates + +Oolite +Copyright (C) 2004-2013 Giles C Williams and contributors + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +MA 02110-1301, USA. + +*/ + + +#ifndef INCLUDED_OOMATHS_h + #error Do not include OOHPVector.h directly; include OOMaths.h. +#else + + +#ifndef OOMATHS_EXTERNAL_VECTOR_TYPES + +typedef struct HPVector +{ + OOHPScalar x; + OOHPScalar y; + OOHPScalar z; +} HPVector; + + +typedef struct HPVector2D +{ + OOHPScalar x; + OOHPScalar y; +} HPVector2D; + +#endif + + +extern const HPVector kZeroHPVector, /* 0, 0, 0 */ + kBasisXHPVector, /* 1, 0, 0 */ + kBasisYHPVector, /* 0, 1, 0 */ + kBasisZHPVector; /* 0, 0, 1 */ + + +extern const HPVector2D kZeroHPVector2D, /* 0, 0 */ + kBasisXHPVector2D, /* 1, 0 */ + kBasisYHPVector2D; /* 0, 1 */ + + +/* Construct vector */ +OOINLINE HPVector make_HPvector(OOHPScalar vx, OOHPScalar vy, OOHPScalar vz) INLINE_CONST_FUNC; +OOINLINE HPVector2D MakeHPVector2D(OOHPScalar vx, OOHPScalar vy) INLINE_CONST_FUNC; + +OOINLINE HPVector vectorToHPVector(Vector v) INLINE_CONST_FUNC; +OOINLINE Vector HPVectorToVector(HPVector v) INLINE_CONST_FUNC; + +#if !OOMATHS_STANDALONE +/* Generate random vectors. */ +HPVector OORandomUnitHPVector(void); +HPVector OOHPVectorRandomSpatial(OOHPScalar maxLength); // Random vector uniformly distributed in radius-maxLength sphere. (Longer vectors are more common.) +HPVector OOHPVectorRandomRadial(OOHPScalar maxLength); // Random vector with uniform distribution of direction and radius in radius-maxLength sphere. (Causes clustering at centre.) +HPVector OORandomPositionInCylinder(HPVector centre1, OOHPScalar exclusion1, HPVector centre2, OOHPScalar exclusion2, OOHPScalar radius); +HPVector OORandomPositionInShell(HPVector centre, OOHPScalar inner, OOHPScalar outer); +#endif + +/* Multiply vector by scalar (in place) */ +OOINLINE void HPscale_vector(HPVector *outHPVector, OOHPScalar factor) ALWAYS_INLINE_FUNC NONNULL_FUNC; + +/* Multiply vector by scalar */ +OOINLINE HPVector HPvector_multiply_scalar(HPVector v, OOHPScalar s) INLINE_CONST_FUNC; + +/* Addition and subtraction of vectors */ +OOINLINE HPVector HPvector_add(HPVector a, HPVector b) INLINE_CONST_FUNC; +OOINLINE HPVector HPvector_subtract(HPVector a, HPVector b) INLINE_CONST_FUNC; +#define HPvector_between(a, b) HPvector_subtract(b, a) +OOINLINE HPVector HPvector_flip(HPVector v) INLINE_CONST_FUNC; + +/* HPVector linear interpolation */ +OOINLINE HPVector OOHPVectorInterpolate(HPVector a, HPVector b, OOHPScalar where) INLINE_CONST_FUNC; +OOINLINE HPVector OOHPVectorTowards(HPVector a, HPVector b, OOHPScalar where) INLINE_CONST_FUNC; + +/* Comparison of vectors */ +OOINLINE bool HPvector_equal(HPVector a, HPVector b) INLINE_CONST_FUNC; + +/* Square of magnitude of vector */ +OOINLINE OOHPScalar HPmagnitude2(HPVector vec) INLINE_CONST_FUNC; + +/* Magnitude of vector */ +OOINLINE OOHPScalar HPmagnitude(HPVector vec) INLINE_CONST_FUNC; + +/* Normalize vector */ +OOINLINE HPVector HPvector_normal(HPVector vec) INLINE_CONST_FUNC; + +/* Normalize vector, returning fallback if zero vector. */ +OOINLINE HPVector HPvector_normal_or_fallback(HPVector vec, HPVector fallback) INLINE_CONST_FUNC; +OOINLINE HPVector HPvector_normal_or_xbasis(HPVector vec) INLINE_CONST_FUNC; +OOINLINE HPVector HPvector_normal_or_ybasis(HPVector vec) INLINE_CONST_FUNC; +OOINLINE HPVector HPvector_normal_or_zbasis(HPVector vec) INLINE_CONST_FUNC; + +/* Square of distance between vectors */ +OOINLINE OOHPScalar HPdistance2(HPVector v1, HPVector v2) INLINE_CONST_FUNC; + +/* Distance between vectors */ +OOINLINE OOHPScalar HPdistance(HPVector v1, HPVector v2) INLINE_CONST_FUNC; + +/* Dot product */ +OOINLINE OOHPScalar HPdot_product (HPVector first, HPVector second) INLINE_CONST_FUNC; + +/* NORMALIZED cross product */ +OOINLINE HPVector HPcross_product(HPVector first, HPVector second) INLINE_CONST_FUNC; + +/* General cross product */ +OOINLINE HPVector HPtrue_cross_product(HPVector first, HPVector second) CONST_FUNC; + +/* Triple product */ +OOINLINE OOHPScalar HPtriple_product(HPVector first, HPVector second, HPVector third) INLINE_CONST_FUNC; + +/* Given three points on a surface, returns the normal to the surface. */ +OOINLINE HPVector HPnormal_to_surface(HPVector v1, HPVector v2, HPVector v3) CONST_FUNC; + +#if __OBJC__ +NSString *HPVectorDescription(HPVector vector); // @"(x, y, z)" +#endif + +#if OOMATHS_OPENGL_INTEGRATION +/* OpenGL conveniences. Need to be macros to work with OOMacroOpenGL. */ +#define GLVertexOOHPVector(v) do { HPVector v_ = v; glVertex3f(v_.x, v_.y, v_.z); } while (0) +#define GLTranslateOOHPVector(v) do { HPVector v_ = v; OOGL(glTranslatef(v_.x, v_.y, v_.z)); } while (0) +#endif + + +/*** Only inline definitions beyond this point ***/ + +OOINLINE HPVector make_HPvector (OOHPScalar vx, OOHPScalar vy, OOHPScalar vz) +{ + HPVector result; + result.x = vx; + result.y = vy; + result.z = vz; + return result; +} + + +OOINLINE HPVector2D MakeHPVector2D(OOHPScalar vx, OOHPScalar vy) +{ + HPVector2D result; + result.x = vx; + result.y = vy; + return result; +} + +OOINLINE HPVector vectorToHPVector(Vector v) { + HPVector result; + result.x = (OOHPScalar)v.x; + result.y = (OOHPScalar)v.y; + result.z = (OOHPScalar)v.z; + return result; +} + +OOINLINE Vector HPVectorToVector(HPVector v) { + Vector result; + result.x = (OOScalar)v.x; + result.y = (OOScalar)v.y; + result.z = (OOScalar)v.z; + return result; +} + +OOINLINE void HPscale_vector(HPVector *vec, OOHPScalar factor) +{ + /* + Clang static analyzer: reports an unintialized value here when called + from -[HeadUpDisplay rescaleByFactor:]. This is blatantly wrong, as + the array the vector comes from is fully initialized in the range being + looped over. + -- Ahruman 2012-09-14 + */ + vec->x *= factor; + vec->y *= factor; + vec->z *= factor; +} + + +OOINLINE HPVector HPvector_multiply_scalar(HPVector v, OOHPScalar s) +{ + /* + Clang static analyzer: reports a garbage value here when called from + -[OOMesh rescaleByFactor:], apparently on baseless assumption that + OOMesh._vertices points to only one vertex. + -- Ahruman 2012-09-14 + */ + HPVector r; + r.x = v.x * s; + r.y = v.y * s; + r.z = v.z * s; + return r; +} + + +OOINLINE HPVector HPvector_add(HPVector a, HPVector b) +{ + HPVector r; + r.x = a.x + b.x; + r.y = a.y + b.y; + r.z = a.z + b.z; + return r; +} + + +OOINLINE HPVector OOHPVectorInterpolate(HPVector a, HPVector b, OOHPScalar where) +{ + return make_HPvector(OOLerp(a.x, b.x, where), + OOLerp(a.y, b.y, where), + OOLerp(a.z, b.z, where)); +} + + +OOINLINE HPVector OOHPVectorTowards(HPVector a, HPVector b, OOHPScalar where) +{ + return make_HPvector(a.x + b.x * where, + a.y + b.y * where, + a.z + b.z * where); +} + + +OOINLINE HPVector HPvector_subtract(HPVector a, HPVector b) +{ + HPVector r; + r.x = a.x - b.x; + r.y = a.y - b.y; + r.z = a.z - b.z; + return r; +} + + +OOINLINE HPVector HPvector_flip(HPVector v) +{ + return HPvector_subtract(kZeroHPVector, v); +} + + +OOINLINE bool HPvector_equal(HPVector a, HPVector b) +{ + return a.x == b.x && a.y == b.y && a.z == b.z; +} + + +OOINLINE OOHPScalar HPmagnitude2(HPVector vec) +{ + return vec.x * vec.x + vec.y * vec.y + vec.z * vec.z; +} + + +OOINLINE OOHPScalar HPmagnitude(HPVector vec) +{ + return sqrt(HPmagnitude2(vec)); +} + + +OOINLINE HPVector HPvector_normal_or_fallback(HPVector vec, HPVector fallback) +{ + OOHPScalar mag2 = HPmagnitude2(vec); + if (EXPECT_NOT(mag2 == 0.0f)) return fallback; + return HPvector_multiply_scalar(vec, 1.0f / sqrt(mag2)); +} + + +OOINLINE HPVector HPvector_normal_or_xbasis(HPVector vec) +{ + return HPvector_normal_or_fallback(vec, kBasisXHPVector); +} + + +OOINLINE HPVector HPvector_normal_or_ybasis(HPVector vec) +{ + return HPvector_normal_or_fallback(vec, kBasisYHPVector); +} + + +OOINLINE HPVector HPvector_normal_or_zbasis(HPVector vec) +{ + return HPvector_normal_or_fallback(vec, kBasisZHPVector); +} + + +OOINLINE HPVector HPvector_normal(HPVector vec) +{ + return HPvector_normal_or_fallback(vec, kZeroHPVector); +} + + +OOINLINE OOHPScalar HPdistance2(HPVector v1, HPVector v2) +{ + return HPmagnitude2(HPvector_subtract(v1, v2)); +} + + +OOINLINE OOHPScalar HPdistance(HPVector v1, HPVector v2) +{ + return HPmagnitude(HPvector_subtract(v1, v2)); +} + + +OOINLINE HPVector HPtrue_cross_product(HPVector first, HPVector second) +{ + HPVector result; + result.x = (first.y * second.z) - (first.z * second.y); + result.y = (first.z * second.x) - (first.x * second.z); + result.z = (first.x * second.y) - (first.y * second.x); + return result; +} + + +OOINLINE HPVector HPcross_product(HPVector first, HPVector second) +{ + return HPvector_normal(HPtrue_cross_product(first, second)); +} + + +OOINLINE OOHPScalar HPdot_product (HPVector a, HPVector b) +{ + return (a.x * b.x) + (a.y * b.y) + (a.z * b.z); +} + + +OOINLINE OOHPScalar HPtriple_product(HPVector first, HPVector second, HPVector third) +{ + return HPdot_product(first, HPtrue_cross_product(second, third)); +} + + +OOINLINE HPVector HPnormal_to_surface(HPVector v1, HPVector v2, HPVector v3) +{ + HPVector d0, d1; + d0 = HPvector_subtract(v2, v1); + d1 = HPvector_subtract(v3, v2); + return HPcross_product(d0, d1); +} + + +#endif /* INCLUDED_OOMATHS_h */ diff --git a/src/Core/OOHPVector.m b/src/Core/OOHPVector.m new file mode 100644 index 00000000..e6aecd0c --- /dev/null +++ b/src/Core/OOHPVector.m @@ -0,0 +1,132 @@ +/* + +OOHPVector.m + +Oolite +Copyright (C) 2004-2013 Giles C Williams and contributors + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +MA 02110-1301, USA. + +*/ + +#include "OOMaths.h" + + +const HPVector kZeroHPVector = { 0.0f, 0.0f, 0.0f }; +const HPVector kBasisXHPVector = { 1.0f, 0.0f, 0.0f }; +const HPVector kBasisYHPVector = { 0.0f, 1.0f, 0.0f }; +const HPVector kBasisZHPVector = { 0.0f, 0.0f, 1.0f }; + +const HPVector2D kZeroHPVector2D = { 0.0f, 0.0f }; +const HPVector2D kBasisXHPVector2D = { 1.0f, 0.0f }; +const HPVector2D kBasisYHPVector2D = { 0.0f, 1.0f }; + +/*#if !OOMATHS_STANDALONE +const BoundingBox kZeroBoundingBox = {{ 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }}; +#endif*/ + + +#if __OBJC__ +NSString *HPVectorDescription(HPVector vector) +{ + return [NSString stringWithFormat:@"(%g, %g, %g)", vector.x, vector.y, vector.z]; +} +#endif + + +#if !OOMATHS_STANDALONE +/* This generates random vectors distrubuted evenly over the surface of the + unit sphere. It does this the simple way, by generating vectors in the + half-unit cube and rejecting those outside the half-unit sphere (and the + zero vector), then normalizing the result. (Half-unit measures are used + to avoid unnecessary multiplications of randf() values.) + + In principle, using three normally-distributed co-ordinates (and again + normalizing the result) would provide the right result without looping, but + I don't trust bellf() so I'll go with the simple approach for now. +*/ +HPVector OORandomUnitHPVector(void) +{ + HPVector v; + OOHPScalar m; + + do + { + v = make_HPvector(randf() - 0.5f, randf() - 0.5f, randf() - 0.5f); + m = HPmagnitude2(v); + } + while (m > 0.25f || m == 0.0f); // We're confining to a sphere of radius 0.5 using the sqared magnitude; 0.5 squared is 0.25. + + return HPvector_normal(v); +} + + +HPVector OOHPVectorRandomSpatial(OOHPScalar maxLength) +{ + HPVector v; + OOHPScalar m; + + do + { + v = make_HPvector(randf() - 0.5f, randf() - 0.5f, randf() - 0.5f); + m = HPmagnitude2(v); + } + while (m > 0.25f); // We're confining to a sphere of radius 0.5 using the sqared magnitude; 0.5 squared is 0.25. + + return HPvector_multiply_scalar(v, maxLength * 2.0f); // 2.0 is to compensate for the 0.5-radius sphere. +} + + +HPVector OOHPVectorRandomRadial(OOHPScalar maxLength) +{ + return HPvector_multiply_scalar(OORandomUnitHPVector(), randf() * maxLength); +} + + +HPVector OOHPRandomPositionInBoundingBox(BoundingBox bb) +{ + HPVector result; + result.x = (OOHPScalar)(bb.min.x + randf() * (bb.max.x - bb.min.x)); + result.y = (OOHPScalar)(bb.min.y + randf() * (bb.max.y - bb.min.y)); + result.z = (OOHPScalar)(bb.min.z + randf() * (bb.max.z - bb.min.z)); + return result; +} + +HPVector OORandomPositionInCylinder(HPVector centre1, OOHPScalar exclusion1, HPVector centre2, OOHPScalar exclusion2, OOHPScalar radius) +{ + OOHPScalar exc12 = exclusion1*exclusion1; + OOHPScalar exc22 = exclusion2*exclusion2; + HPVector result; + do + { + result = HPvector_add(OOHPVectorInterpolate(centre1,centre2,randf()),OOHPVectorRandomSpatial(radius)); + } + while(HPdistance2(result,centre1) -#import "OOVector.h" +#import "OOMaths.h" @interface OOJSPopulatorDefinition: OOWeakRefObject { @@ -40,7 +40,7 @@ MA 02110-1301, USA. - (JSObject *)callbackThis; - (void)setCallbackThis:(JSObject *)callbackthis; -- (void)runCallback:(Vector)location; +- (void)runCallback:(HPVector)location; @end diff --git a/src/Core/Scripting/OOJSPopulatorDefinition.m b/src/Core/Scripting/OOJSPopulatorDefinition.m index a7e2f214..a162fade 100644 --- a/src/Core/Scripting/OOJSPopulatorDefinition.m +++ b/src/Core/Scripting/OOJSPopulatorDefinition.m @@ -25,7 +25,7 @@ MA 02110-1301, USA. #import "OOJSPopulatorDefinition.h" #import "OOJavaScriptEngine.h" -#import "OOVector.h" +#import "OOMaths.h" #import "OOJSVector.h" @implementation OOJSPopulatorDefinition @@ -102,13 +102,13 @@ MA 02110-1301, USA. } -- (void)runCallback:(Vector)location +- (void)runCallback:(HPVector)location { OOJavaScriptEngine *engine = [OOJavaScriptEngine sharedEngine]; JSContext *context = OOJSAcquireContext(); jsval loc, rval = JSVAL_VOID; - VectorToJSValue(context, location, &loc); + VectorToJSValue(context, HPVectorToVector(location), &loc); OOJSScript *owner = [_owningScript retain]; // local copy needed [OOJSScript pushScript:owner]; diff --git a/src/Core/Scripting/OOJSShip.m b/src/Core/Scripting/OOJSShip.m index b4102629..a7adf90e 100644 --- a/src/Core/Scripting/OOJSShip.m +++ b/src/Core/Scripting/OOJSShip.m @@ -684,7 +684,7 @@ static JSBool ShipGetProperty(JSContext *context, JSObject *this, jsid propID, j return JS_NewNumberValue(context, [entity desiredSpeed], value); case kShip_destination: - return VectorToJSValue(context, [entity destination], value); + return VectorToJSValue(context, HPVectorToVector([entity destination]), value); case kShip_maxEscorts: return JS_NewNumberValue(context, [entity maxEscortCount], value); @@ -789,7 +789,7 @@ static JSBool ShipGetProperty(JSContext *context, JSObject *this, jsid propID, j return JS_NewNumberValue(context, [entity missileLoadTime], value); case kShip_savedCoordinates: - return VectorToJSValue(context, [entity coordinates], value); + return VectorToJSValue(context, HPVectorToVector([entity coordinates]), value); case kShip_equipment: result = [entity equipmentListForScripting]; @@ -1170,7 +1170,7 @@ static JSBool ShipSetProperty(JSContext *context, JSObject *this, jsid propID, J { // use setEscortDestination rather than setDestination as // scripted amendments shouldn't necessarily reset frustration - [entity setEscortDestination:vValue]; + [entity setEscortDestination:vectorToHPVector(vValue)]; return YES; } break; @@ -1198,7 +1198,7 @@ static JSBool ShipSetProperty(JSContext *context, JSObject *this, jsid propID, J case kShip_savedCoordinates: if (JSValueToVector(context, *value, &vValue)) { - [entity setCoordinate:vValue]; + [entity setCoordinate:vectorToHPVector(vValue)]; return YES; } break; diff --git a/src/Core/Scripting/OOJSSystem.m b/src/Core/Scripting/OOJSSystem.m index e93f86cd..0a5b4842 100644 --- a/src/Core/Scripting/OOJSSystem.m +++ b/src/Core/Scripting/OOJSSystem.m @@ -1180,7 +1180,7 @@ static JSBool SystemAddVisualEffect(JSContext *context, uintN argc, jsval *vp) OOJS_BEGIN_FULL_NATIVE(context) - result = [UNIVERSE addVisualEffectAt:where withKey:key]; + result = [UNIVERSE addVisualEffectAt:vectorToHPVector(where) withKey:key]; OOJS_END_FULL_NATIVE @@ -1258,6 +1258,7 @@ static JSBool SystemAddShipsOrGroup(JSContext *context, uintN argc, jsval *vp, B int32 count = 0; uintN consumed = 0; Vector where; + HPVector hpwhere; double radius = NSNotFound; // a negative value means id result = nil; @@ -1277,7 +1278,7 @@ static JSBool SystemAddShipsOrGroup(JSContext *context, uintN argc, jsval *vp, B if (argc < 3) { - where = [UNIVERSE getWitchspaceExitPosition]; + hpwhere = [UNIVERSE getWitchspaceExitPosition]; radius = SCANNER_MAX_RANGE; } else @@ -1296,11 +1297,12 @@ static JSBool SystemAddShipsOrGroup(JSContext *context, uintN argc, jsval *vp, B return NO; } } + hpwhere = vectorToHPVector(where); } OOJS_BEGIN_FULL_NATIVE(context) // Note: the use of witchspace-in effects (as in legacy_addShips) depends on proximity to the witchpoint. - result = [UNIVERSE addShipsAt:where withRole:role quantity:count withinRadius:radius asGroup:isGroup]; + result = [UNIVERSE addShipsAt:hpwhere withRole:role quantity:count withinRadius:radius asGroup:isGroup]; if (isGroup) { @@ -1470,8 +1472,8 @@ static NSComparisonResult CompareEntitiesByDistance(id a, id b, void *relativeTo *r = (id)relativeTo; float d1, d2; - d1 = distance2(ea->position, r->position); - d2 = distance2(eb->position, r->position); + d1 = HPdistance2(ea->position, r->position); + d2 = HPdistance2(eb->position, r->position); if (d1 < d2) return NSOrderedAscending; else if (d1 > d2) return NSOrderedDescending; diff --git a/src/Core/Scripting/OOJSVector.m b/src/Core/Scripting/OOJSVector.m index 4c1fb092..db7b8cf9 100644 --- a/src/Core/Scripting/OOJSVector.m +++ b/src/Core/Scripting/OOJSVector.m @@ -330,7 +330,7 @@ BOOL JSObjectGetVector(JSContext *context, JSObject *vectorObj, Vector *outVecto { COUNT(entityCount); Entity *entity = JS_GetPrivate(context, vectorObj); - *outVector = [entity position]; + *outVector = HPVectorToVector([entity position]); return YES; } @@ -956,7 +956,7 @@ static JSBool VectorToCoordinateSystem(JSContext *context, uintN argc, jsval *vp } OOJS_BEGIN_FULL_NATIVE(context) - result = [UNIVERSE legacyPositionFrom:thisv asCoordinateSystem:coordScheme]; + result = HPVectorToVector([UNIVERSE legacyPositionFrom:vectorToHPVector(thisv) asCoordinateSystem:coordScheme]); OOJS_END_FULL_NATIVE OOJS_RETURN_VECTOR(result); @@ -985,7 +985,7 @@ static JSBool VectorFromCoordinateSystem(JSContext *context, uintN argc, jsval * OOJS_BEGIN_FULL_NATIVE(context) NSString *arg = [NSString stringWithFormat:@"%@ %f %f %f", coordScheme, thisv.x, thisv.y, thisv.z]; - result = [UNIVERSE coordinatesFromCoordinateSystemString:arg]; + result = HPVectorToVector([UNIVERSE coordinatesFromCoordinateSystemString:arg]); OOJS_END_FULL_NATIVE OOJS_RETURN_VECTOR(result); diff --git a/src/Core/Universe.h b/src/Core/Universe.h index 552c0aa7..e0ebbf10 100644 --- a/src/Core/Universe.h +++ b/src/Core/Universe.h @@ -353,22 +353,22 @@ enum - (void) makeSunSkimmer:(ShipEntity *) ship andSetAI:(BOOL)setAI; - (void) addShipWithRole:(NSString *) desc nearRouteOneAt:(double) route_fraction; -- (Vector) coordinatesForPosition:(Vector) pos withCoordinateSystem:(NSString *) system returningScalar:(GLfloat*) my_scalar; -- (NSString *) expressPosition:(Vector) pos inCoordinateSystem:(NSString *) system; -- (Vector) legacyPositionFrom:(Vector) pos asCoordinateSystem:(NSString *) system; -- (Vector) coordinatesFromCoordinateSystemString:(NSString *) system_x_y_z; -- (BOOL) addShipWithRole:(NSString *) desc nearPosition:(Vector) pos withCoordinateSystem:(NSString *) system; -- (BOOL) addShips:(int) howMany withRole:(NSString *) desc atPosition:(Vector) pos withCoordinateSystem:(NSString *) system; -- (BOOL) addShips:(int) howMany withRole:(NSString *) desc nearPosition:(Vector) pos withCoordinateSystem:(NSString *) system; -- (BOOL) addShips:(int) howMany withRole:(NSString *) desc nearPosition:(Vector) pos withCoordinateSystem:(NSString *) system withinRadius:(GLfloat) radius; +- (HPVector) coordinatesForPosition:(HPVector) pos withCoordinateSystem:(NSString *) system returningScalar:(GLfloat*) my_scalar; +- (NSString *) expressPosition:(HPVector) pos inCoordinateSystem:(NSString *) system; +- (HPVector) legacyPositionFrom:(HPVector) pos asCoordinateSystem:(NSString *) system; +- (HPVector) coordinatesFromCoordinateSystemString:(NSString *) system_x_y_z; +- (BOOL) addShipWithRole:(NSString *) desc nearPosition:(HPVector) pos withCoordinateSystem:(NSString *) system; +- (BOOL) addShips:(int) howMany withRole:(NSString *) desc atPosition:(HPVector) pos withCoordinateSystem:(NSString *) system; +- (BOOL) addShips:(int) howMany withRole:(NSString *) desc nearPosition:(HPVector) pos withCoordinateSystem:(NSString *) system; +- (BOOL) addShips:(int) howMany withRole:(NSString *) desc nearPosition:(HPVector) pos withCoordinateSystem:(NSString *) system withinRadius:(GLfloat) radius; - (BOOL) addShips:(int) howMany withRole:(NSString *) desc intoBoundingBox:(BoundingBox) bbox; - (BOOL) spawnShip:(NSString *) shipdesc; - (void) witchspaceShipWithPrimaryRole:(NSString *)role; - (ShipEntity *) spawnShipWithRole:(NSString *) desc near:(Entity *) entity; -- (OOVisualEffectEntity *) addVisualEffectAt:(Vector)pos withKey:(NSString *)key; -- (ShipEntity *) addShipAt:(Vector)pos withRole:(NSString *)role withinRadius:(GLfloat)radius; -- (NSArray *) addShipsAt:(Vector)pos withRole:(NSString *)role quantity:(unsigned)count withinRadius:(GLfloat)radius asGroup:(BOOL)isGroup; +- (OOVisualEffectEntity *) addVisualEffectAt:(HPVector)pos withKey:(NSString *)key; +- (ShipEntity *) addShipAt:(HPVector)pos withRole:(NSString *)role withinRadius:(GLfloat)radius; +- (NSArray *) addShipsAt:(HPVector)pos withRole:(NSString *)role quantity:(unsigned)count withinRadius:(GLfloat)radius asGroup:(BOOL)isGroup; - (NSArray *) addShipsToRoute:(NSString *)route withRole:(NSString *)role quantity:(unsigned)count routeFraction:(double)routeFraction asGroup:(BOOL)isGroup; - (BOOL) roleIsPirateVictim:(NSString *)role; @@ -377,7 +377,7 @@ enum - (void) addWitchspaceJumpEffectForShip:(ShipEntity *)ship; - (GLfloat) safeWitchspaceExitDistance; -- (void) setUpBreakPattern:(Vector)pos orientation:(Quaternion)q forDocking:(BOOL)forDocking; +- (void) setUpBreakPattern:(HPVector)pos orientation:(Quaternion)q forDocking:(BOOL)forDocking; - (BOOL) witchspaceBreakPattern; - (void) setWitchspaceBreakPattern:(BOOL)newValue; @@ -454,7 +454,7 @@ enum - (void) drawUniverse; - (void) defineFrustum; -- (BOOL) viewFrustumIntersectsSphereAt:(Vector)position withRadius:(GLfloat)radius; +- (BOOL) viewFrustumIntersectsSphereAt:(HPVector)position withRadius:(GLfloat)radius; - (void) drawMessage; @@ -471,9 +471,9 @@ enum - (ShipEntity *) makeDemoShipWithRole:(NSString *)role spinning:(BOOL)spinning; -- (BOOL) isVectorClearFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(Vector) p2; -- (Entity*) hazardOnRouteFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(Vector) p2; -- (Vector) getSafeVectorFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(Vector) p2; +- (BOOL) isVectorClearFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(HPVector) p2; +- (Entity*) hazardOnRouteFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(HPVector) p2; +- (HPVector) getSafeVectorFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(HPVector) p2; - (ShipEntity *) firstShipHitByLaserFromShip:(ShipEntity *)srcEntity inDirection:(OOWeaponFacing)direction offset:(Vector)offset gettingRangeFound:(GLfloat*)range_ptr; - (Entity *) firstEntityTargetedByPlayer; @@ -641,13 +641,13 @@ enum - (NSString*) brochureDescriptionWithDictionary:(NSDictionary*) dict standardEquipment:(NSArray*) extras optionalEquipment:(NSArray*) options; -- (Vector) getWitchspaceExitPosition; -- (Vector) randomizeFromSeedAndGetWitchspaceExitPosition; -- (Vector) getWitchspaceExitPositionResettingRandomSeed:(BOOL)resetSeed; +- (HPVector) getWitchspaceExitPosition; +- (HPVector) randomizeFromSeedAndGetWitchspaceExitPosition; +- (HPVector) getWitchspaceExitPositionResettingRandomSeed:(BOOL)resetSeed; - (Quaternion) getWitchspaceExitRotation; -- (Vector) getSunSkimStartPositionForShip:(ShipEntity*) ship; -- (Vector) getSunSkimEndPositionForShip:(ShipEntity*) ship; +- (HPVector) getSunSkimStartPositionForShip:(ShipEntity*) ship; +- (HPVector) getSunSkimEndPositionForShip:(ShipEntity*) ship; - (NSArray*) listBeaconsWithCode:(NSString*) code; diff --git a/src/Core/Universe.m b/src/Core/Universe.m index d988580d..4fb3d43f 100644 --- a/src/Core/Universe.m +++ b/src/Core/Universe.m @@ -175,17 +175,17 @@ static OOComparisonResult comparePrice(id dict1, id dict2, void * context); - (void) preloadSounds; - (void) setUpSettings; - (void) setUpInitialUniverse; -- (ShipEntity *) spawnPatrolShipFrom:(Vector)startPos alongRoute:(Vector)route withOffset:(double)offset; -- (void) addWolfpackShipNear:(Vector)launchPos withGroup:(OOShipGroup *)wolfpackGroup andBounty:(unsigned)bounty; -- (Vector) fractionalPositionFrom:(Vector)point0 to:(Vector)point1 withFraction:(double)routeFraction; +//- (ShipEntity *) spawnPatrolShipFrom:(Vector)startPos alongRoute:(Vector)route withOffset:(double)offset; +//- (void) addWolfpackShipNear:(Vector)launchPos withGroup:(OOShipGroup *)wolfpackGroup andBounty:(unsigned)bounty; +- (HPVector) fractionalPositionFrom:(HPVector)point0 to:(HPVector)point1 withFraction:(double)routeFraction; - (void) resetSystemDataCache; - (void) populateSpaceFromActiveWormholes; -- (Vector) locationByCode:(NSString *)code withSun:(OOSunEntity *)sun andPlanet:(OOPlanetEntity *)planet; -- (void) populateSpaceFromHyperPoint:(Vector)h1_pos toPlanetPosition:(Vector)p1_pos andSunPosition:(Vector)s1_pos; -- (NSUInteger) scatterAsteroidsAt:(Vector)spawnPos withVelocity:(Vector)spawnVel includingRockHermit:(BOOL)spawnHermit asCinders:(BOOL)asCinders; -- (NSUInteger) scatterAsteroidsAt:(Vector)spawnPos withVelocity:(Vector)spawnVel includingRockHermit:(BOOL)spawnHermit asCinders:(BOOL)asCinders clusterSize:(NSUInteger)clusterSize; +- (HPVector) locationByCode:(NSString *)code withSun:(OOSunEntity *)sun andPlanet:(OOPlanetEntity *)planet; +//- (void) populateSpaceFromHyperPoint:(Vector)h1_pos toPlanetPosition:(Vector)p1_pos andSunPosition:(Vector)s1_pos; +//- (NSUInteger) scatterAsteroidsAt:(Vector)spawnPos withVelocity:(Vector)spawnVel includingRockHermit:(BOOL)spawnHermit asCinders:(BOOL)asCinders; +//- (NSUInteger) scatterAsteroidsAt:(Vector)spawnPos withVelocity:(Vector)spawnVel includingRockHermit:(BOOL)spawnHermit asCinders:(BOOL)asCinders clusterSize:(NSUInteger)clusterSize; - (NSString *)chooseStringForKey:(NSString *)key inDictionary:(NSDictionary *)dictionary; @@ -682,7 +682,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC if ([dockedStation maxFlightSpeed] > 0) // we are a carrier: exit near the WitchspaceExitPosition { float d1 = [self randomDistanceWithinScanner]; - Vector pos = [UNIVERSE getWitchspaceExitPosition]; // no need to reset the PRNG + HPVector pos = [UNIVERSE getWitchspaceExitPosition]; // no need to reset the PRNG Quaternion q1; quaternion_set_random(&q1); @@ -911,7 +911,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC double planet_radius = [a_planet radius]; double planet_zpos = (12.0 + (Ranrot() & 3) - (Ranrot() & 3) ) * planet_radius; // 9..15 pr (planet radii) ahead - [a_planet setPosition:(Vector){ 0, 0, planet_zpos }]; + [a_planet setPosition:(HPVector){ 0, 0, planet_zpos }]; [a_planet setEnergy:1000000.0]; if ([allPlanets count]>0) // F7 sets [UNIVERSE planet], which can lead to some trouble! TODO: track down where exactly that happens! @@ -941,7 +941,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC OOSunEntity *a_sun; OOPlanetEntity *a_planet; - Vector stationPos; + HPVector stationPos; Vector vf; @@ -1013,7 +1013,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC int posIterator=0; id dict_object; Quaternion q_sun; - Vector sunPos; + HPVector sunPos; sunDistanceModifier = [systeminfo oo_nonNegativeDoubleForKey:@"sun_distance_modifier" defaultValue:20.0]; // Any smaller than 6, the main planet can end up inside the sun @@ -1050,9 +1050,9 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC [a_planet setOrientation:q_sun]; vf = vector_right_from_quaternion(q_sun); - sunPos = vector_subtract(sunPos, vector_multiply_scalar(vf, sun_distance)); // back off from the planet by 15..25 planet radii + sunPos = HPvector_subtract(sunPos, vectorToHPVector(vector_multiply_scalar(vf, sun_distance))); // back off from the planet by 15..25 planet radii posIterator++; - } while (magnitude2(sunPos) < safeDistance && posIterator <= 10); // try 10 times before giving up + } while (HPmagnitude2(sunPos) < safeDistance && posIterator <= 10); // try 10 times before giving up if (posIterator>10) { @@ -1097,7 +1097,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } while (vf.z <= 0.0); // keep station on the correct side of the planet - stationPos = vector_subtract(stationPos, vector_multiply_scalar(vf, 2.0 * planet_radius)); + stationPos = HPvector_subtract(stationPos, vectorToHPVector(vector_multiply_scalar(vf, 2.0 * planet_radius))); defaultStationDesc = @"coriolis"; if (techlevel > 10) @@ -1308,7 +1308,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC NSArray *blocks = [populatorSettings allValues]; NSEnumerator *enumerator = [[blocks sortedArrayUsingFunction:populatorPrioritySort context:nil] objectEnumerator]; NSDictionary *populator; - Vector location; + HPVector location; int locationSeed, groupCount, rndvalue; unsigned i; RANROTSeed rndcache, rndlocal; @@ -1323,7 +1323,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC locationCode = [populator oo_stringForKey:@"location" defaultValue:@"COORDINATES"]; if ([locationCode isEqualToString:@"COORDINATES"]) { - location = [populator oo_vectorForKey:@"coordinates" defaultValue:kZeroVector]; + location = [populator oo_hpvectorForKey:@"coordinates" defaultValue:kZeroHPVector]; } else { @@ -1364,21 +1364,21 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (Vector) locationByCode:(NSString *)code withSun:(OOSunEntity *)sun andPlanet:(OOPlanetEntity *)planet +- (HPVector) locationByCode:(NSString *)code withSun:(OOSunEntity *)sun andPlanet:(OOPlanetEntity *)planet { - Vector result = kZeroVector; + HPVector result = kZeroHPVector; if ([code isEqualToString:@"WITCHPOINT"]) { - result = OOVectorRandomSpatial(SCANNER_MAX_RANGE); + result = OOHPVectorRandomSpatial(SCANNER_MAX_RANGE); } // past this point, can assume non-nil sun, planet else if ([code isEqualToString:@"LANE_WP"]) { - result = OORandomPositionInCylinder(kZeroVector,SCANNER_MAX_RANGE,[planet position],[planet radius]*3,LANE_WIDTH); + result = OORandomPositionInCylinder(kZeroHPVector,SCANNER_MAX_RANGE,[planet position],[planet radius]*3,LANE_WIDTH); } else if ([code isEqualToString:@"LANE_WS"]) { - result = OORandomPositionInCylinder(kZeroVector,SCANNER_MAX_RANGE,[sun position],[sun radius]*3,LANE_WIDTH); + result = OORandomPositionInCylinder(kZeroHPVector,SCANNER_MAX_RANGE,[sun position],[sun radius]*3,LANE_WIDTH); } else if ([code isEqualToString:@"LANE_PS"]) { @@ -1389,7 +1389,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC do { result = OORandomPositionInShell([[self station] position],[[self station] collisionRadius]*1.2,SCANNER_MAX_RANGE*2.0); - } while(distance2(result,[planet position])<[planet radius]*[planet radius]*1.5); + } while(HPdistance2(result,[planet position])<[planet radius]*[planet radius]*1.5); // loop to make sure not generated too close to the planet's surface } else if ([code isEqualToString:@"PLANET_ORBIT_LOW"]) @@ -1429,10 +1429,10 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC r = 1-r; s = 1-s; } - result = vector_add(vector_multiply_scalar([planet position],r),vector_multiply_scalar([sun position],s)); + result = HPvector_add(HPvector_multiply_scalar([planet position],r),HPvector_multiply_scalar([sun position],s)); } // make sure at least 3 radii from vertices - while(distance2(result,[sun position]) < [sun radius]*[sun radius]*9.0 || distance2(result,[planet position]) < [planet radius]*[planet radius]*9.0 || magnitude2(result) < SCANNER_MAX_RANGE2 * 9.0); + while(HPdistance2(result,[sun position]) < [sun radius]*[sun radius]*9.0 || HPdistance2(result,[planet position]) < [planet radius]*[planet radius]*9.0 || HPmagnitude2(result) < SCANNER_MAX_RANGE2 * 9.0); } /* Some more, waiting for issue #22 */ // INNER_SYSTEM @@ -1442,7 +1442,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC else { OOLog(kOOLogUniversePopulateError,@"Named populator region %@ is not implemented, falling back to WITCHPOINT",code); - result = OOVectorRandomSpatial(SCANNER_MAX_RANGE); + result = OOHPVectorRandomSpatial(SCANNER_MAX_RANGE); } return result; } @@ -1541,7 +1541,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (ShipEntity *) addShipWithRole:(NSString *)desc launchPos:(Vector)launchPos rfactor:(GLfloat)rfactor +- (ShipEntity *) addShipWithRole:(NSString *)desc launchPos:(HPVector)launchPos rfactor:(GLfloat)rfactor { if (rfactor != 0.0) { @@ -1586,13 +1586,13 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC return; } - Vector launchPos = OOVectorInterpolate([self getWitchspaceExitPosition], [theStation position], route_fraction); + HPVector launchPos = OOHPVectorInterpolate([self getWitchspaceExitPosition], [theStation position], route_fraction); [self addShipWithRole:desc launchPos:launchPos rfactor:SCANNER_MAX_RANGE]; } -- (Vector) coordinatesForPosition:(Vector) pos withCoordinateSystem:(NSString *) system returningScalar:(GLfloat*) my_scalar +- (HPVector) coordinatesForPosition:(HPVector) pos withCoordinateSystem:(NSString *) system returningScalar:(GLfloat*) my_scalar { /* the point is described using a system selected by a string consisting of a three letter code. @@ -1631,7 +1631,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC NSString* l_sys = [system lowercaseString]; if ([l_sys length] != 3) - return kZeroVector; + return kZeroHPVector; OOPlanetEntity* the_planet = [self planet]; OOSunEntity* the_sun = [self sun]; if (the_planet == nil || the_sun == nil || [l_sys isEqualToString:@"abs"]) @@ -1639,12 +1639,12 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC if (my_scalar) *my_scalar = 1.0; return pos; } - Vector w_pos = [self getWitchspaceExitPosition]; // don't reset PRNG - Vector p_pos = the_planet->position; - Vector s_pos = the_sun->position; + HPVector w_pos = [self getWitchspaceExitPosition]; // don't reset PRNG + HPVector p_pos = the_planet->position; + HPVector s_pos = the_sun->position; const char* c_sys = [l_sys UTF8String]; - Vector p0, p1, p2; + HPVector p0, p1, p2; switch (c_sys[0]) { @@ -1657,7 +1657,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC case 's': p1 = s_pos; p2 = p_pos; break; default: - return kZeroVector; + return kZeroHPVector; } break; case 'p': @@ -1669,7 +1669,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC case 's': p1 = s_pos; p2 = w_pos; break; default: - return kZeroVector; + return kZeroHPVector; } break; case 's': @@ -1681,17 +1681,17 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC case 'p': p1 = p_pos; p2 = w_pos; break; default: - return kZeroVector; + return kZeroHPVector; } break; default: - return kZeroVector; + return kZeroHPVector; } - Vector k = vector_normal_or_zbasis(vector_subtract(p1, p0)); // 'forward' - Vector v = vector_normal_or_xbasis(vector_subtract(p2, p0)); // temporary vector in plane of 'forward' and 'right' + HPVector k = HPvector_normal_or_zbasis(HPvector_subtract(p1, p0)); // 'forward' + HPVector v = HPvector_normal_or_xbasis(HPvector_subtract(p2, p0)); // temporary vector in plane of 'forward' and 'right' - Vector j = cross_product(k, v); // 'up' - Vector i = cross_product(j, k); // 'right' + HPVector j = HPcross_product(k, v); // 'up' + HPVector i = HPcross_product(j, k); // 'right' GLfloat scale = 1.0; switch (c_sys[2]) @@ -1705,7 +1705,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC break; case 'u': - scale = magnitude(vector_subtract(p1, p0)); + scale = HPmagnitude(HPvector_subtract(p1, p0)); break; case 'm': @@ -1713,13 +1713,13 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC break; default: - return kZeroVector; + return kZeroHPVector; } if (my_scalar) *my_scalar = scale; // result = p0 + ijk - Vector result = p0; // origin + HPVector result = p0; // origin result.x += scale * (pos.x * i.x + pos.y * j.x + pos.z * k.x); result.y += scale * (pos.x * i.y + pos.y * j.y + pos.z * k.y); result.z += scale * (pos.x * i.z + pos.y * j.z + pos.z * k.z); @@ -1728,30 +1728,30 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (NSString *) expressPosition:(Vector) pos inCoordinateSystem:(NSString *) system +- (NSString *) expressPosition:(HPVector) pos inCoordinateSystem:(NSString *) system { - Vector result = [self legacyPositionFrom:pos asCoordinateSystem:system]; + HPVector result = [self legacyPositionFrom:pos asCoordinateSystem:system]; return [NSString stringWithFormat:@"%@ %.2f %.2f %.2f", system, result.x, result.y, result.z]; } -- (Vector) legacyPositionFrom:(Vector) pos asCoordinateSystem:(NSString *) system +- (HPVector) legacyPositionFrom:(HPVector) pos asCoordinateSystem:(NSString *) system { NSString* l_sys = [system lowercaseString]; if ([l_sys length] != 3) - return kZeroVector; + return kZeroHPVector; OOPlanetEntity* the_planet = [self planet]; OOSunEntity* the_sun = [self sun]; if (the_planet == nil || the_sun == nil || [l_sys isEqualToString:@"abs"]) { return pos; } - Vector w_pos = [self getWitchspaceExitPosition]; // don't reset PRNG - Vector p_pos = the_planet->position; - Vector s_pos = the_sun->position; + HPVector w_pos = [self getWitchspaceExitPosition]; // don't reset PRNG + HPVector p_pos = the_planet->position; + HPVector s_pos = the_sun->position; const char* c_sys = [l_sys UTF8String]; - Vector p0, p1, p2; + HPVector p0, p1, p2; switch (c_sys[0]) { @@ -1764,7 +1764,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC case 's': p1 = s_pos; p2 = p_pos; break; default: - return kZeroVector; + return kZeroHPVector; } break; case 'p': @@ -1776,7 +1776,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC case 's': p1 = s_pos; p2 = w_pos; break; default: - return kZeroVector; + return kZeroHPVector; } break; case 's': @@ -1788,17 +1788,17 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC case 'p': p1 = p_pos; p2 = w_pos; break; default: - return kZeroVector; + return kZeroHPVector; } break; default: - return kZeroVector; + return kZeroHPVector; } - Vector k = vector_normal_or_zbasis(vector_subtract(p1, p0)); // 'z' axis in m - Vector v = vector_normal_or_xbasis(vector_subtract(p2, p0)); // temporary vector in plane of 'forward' and 'right' + HPVector k = HPvector_normal_or_zbasis(HPvector_subtract(p1, p0)); // 'z' axis in m + HPVector v = HPvector_normal_or_xbasis(HPvector_subtract(p2, p0)); // temporary vector in plane of 'forward' and 'right' - Vector j = cross_product(k, v); // 'y' axis in m - Vector i = cross_product(j, k); // 'x' axis in m + HPVector j = HPcross_product(k, v); // 'y' axis in m + HPVector i = HPcross_product(j, k); // 'x' axis in m GLfloat scale = 1.0; switch (c_sys[2]) @@ -1815,7 +1815,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } case 'u': - scale = 1.0f / magnitude(vector_subtract(p1, p0)); + scale = 1.0f / HPdistance(p1, p0); break; case 'm': @@ -1823,12 +1823,12 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC break; default: - return kZeroVector; + return kZeroHPVector; } // result = p0 + ijk - Vector r_pos = vector_subtract(pos, p0); - Vector result = make_vector(scale * (r_pos.x * i.x + r_pos.y * i.y + r_pos.z * i.z), + HPVector r_pos = HPvector_subtract(pos, p0); + HPVector result = make_HPvector(scale * (r_pos.x * i.x + r_pos.y * i.y + r_pos.z * i.z), scale * (r_pos.x * j.x + r_pos.y * j.y + r_pos.z * j.z), scale * (r_pos.x * k.x + r_pos.y * k.y + r_pos.z * k.z) ); // scale * dot_products @@ -1836,24 +1836,24 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (Vector) coordinatesFromCoordinateSystemString:(NSString *) system_x_y_z +- (HPVector) coordinatesFromCoordinateSystemString:(NSString *) system_x_y_z { NSArray* tokens = ScanTokensFromString(system_x_y_z); if ([tokens count] != 4) { // Not necessarily an error. - return make_vector(0,0,0); + return make_HPvector(0,0,0); } GLfloat dummy; - return [self coordinatesForPosition:make_vector([tokens oo_floatAtIndex:1], [tokens oo_floatAtIndex:2], [tokens oo_floatAtIndex:3]) withCoordinateSystem:[tokens oo_stringAtIndex:0] returningScalar:&dummy]; + return [self coordinatesForPosition:make_HPvector([tokens oo_floatAtIndex:1], [tokens oo_floatAtIndex:2], [tokens oo_floatAtIndex:3]) withCoordinateSystem:[tokens oo_stringAtIndex:0] returningScalar:&dummy]; } -- (BOOL) addShipWithRole:(NSString *) desc nearPosition:(Vector) pos withCoordinateSystem:(NSString *) system +- (BOOL) addShipWithRole:(NSString *) desc nearPosition:(HPVector) pos withCoordinateSystem:(NSString *) system { // initial position GLfloat scalar = 1.0; - Vector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar]; + HPVector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar]; // randomise GLfloat rfactor = scalar; if (rfactor > SCANNER_MAX_RANGE) @@ -1865,14 +1865,14 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (BOOL) addShips:(int) howMany withRole:(NSString *) desc atPosition:(Vector) pos withCoordinateSystem:(NSString *) system +- (BOOL) addShips:(int) howMany withRole:(NSString *) desc atPosition:(HPVector) pos withCoordinateSystem:(NSString *) system { // initial bounding box GLfloat scalar = 1.0; - Vector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar]; + HPVector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar]; GLfloat distance_from_center = 0.0; - Vector v_from_center, ship_pos; - Vector ship_positions[howMany]; + HPVector v_from_center, ship_pos; + HPVector ship_positions[howMany]; int i = 0; int scale_up_after = 0; int current_shell = 0; @@ -1888,7 +1888,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC BOOL safe; int limit_count = 8; - v_from_center = kZeroVector; + v_from_center = kZeroHPVector; do { do @@ -1897,9 +1897,9 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC v_from_center.y += walk_factor * (randf() - 0.5); v_from_center.z += walk_factor * (randf() - 0.5); // drunkards walk } while ((v_from_center.x == 0.0)&&(v_from_center.y == 0.0)&&(v_from_center.z == 0.0)); - v_from_center = vector_normal(v_from_center); // guaranteed non-zero + v_from_center = HPvector_normal(v_from_center); // guaranteed non-zero - ship_pos = make_vector( launchPos.x + distance_from_center * v_from_center.x, + ship_pos = make_HPvector( launchPos.x + distance_from_center * v_from_center.x, launchPos.y + distance_from_center * v_from_center.y, launchPos.z + distance_from_center * v_from_center.z); @@ -1908,7 +1908,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC int j = i - 1; while (safe && (j >= current_shell)) { - safe = (safe && (distance2(ship_pos, ship_positions[j]) > safe_distance2)); + safe = (safe && (HPdistance2(ship_pos, ship_positions[j]) > safe_distance2)); j--; } if (!safe) @@ -1945,11 +1945,11 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (BOOL) addShips:(int) howMany withRole:(NSString *) desc nearPosition:(Vector) pos withCoordinateSystem:(NSString *) system +- (BOOL) addShips:(int) howMany withRole:(NSString *) desc nearPosition:(HPVector) pos withCoordinateSystem:(NSString *) system { // initial bounding box GLfloat scalar = 1.0; - Vector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar]; + HPVector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar]; GLfloat rfactor = scalar; if (rfactor > SCANNER_MAX_RANGE) rfactor = SCANNER_MAX_RANGE; @@ -1963,11 +1963,11 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (BOOL) addShips:(int) howMany withRole:(NSString *) desc nearPosition:(Vector) pos withCoordinateSystem:(NSString *) system withinRadius:(GLfloat) radius +- (BOOL) addShips:(int) howMany withRole:(NSString *) desc nearPosition:(HPVector) pos withCoordinateSystem:(NSString *) system withinRadius:(GLfloat) radius { // initial bounding box GLfloat scalar = 1.0; - Vector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar]; + HPVector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar]; GLfloat rfactor = radius; if (rfactor < 1000) rfactor = 1000; @@ -2017,7 +2017,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } // randomise within the bounding box (biased towards the center of the box) - Vector pos = make_vector(bbox.min.x, bbox.min.y, bbox.min.z); + HPVector pos = make_HPvector(bbox.min.x, bbox.min.y, bbox.min.z); pos.x += 0.5 * (randf() + randf()) * (bbox.max.x - bbox.min.x); pos.y += 0.5 * (randf() + randf()) * (bbox.max.y - bbox.min.y); pos.z += 0.5 * (randf() + randf()) * (bbox.max.z - bbox.min.z); @@ -2040,7 +2040,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC // set any spawning characteristics NSDictionary *spawndict = [shipdict oo_dictionaryForKey:@"spawn"]; - Vector pos, rpos, spos; + HPVector pos, rpos, spos; NSString *positionString = nil; // position @@ -2057,7 +2057,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC else { // without position defined, the ship will be added on top of the witchpoint buoy. - pos = OOVectorRandomRadial(SCANNER_MAX_RANGE); + pos = OOHPVectorRandomRadial(SCANNER_MAX_RANGE); OOLogERR(@"universe.spawnShip.error", @"***** ERROR: failed to find a spawn position for ship %@.", shipdesc); } [ship setPosition:pos]; @@ -2074,15 +2074,15 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC spos = [ship position]; Quaternion q1; rpos = [self coordinatesFromCoordinateSystemString:positionString]; - rpos = vector_subtract(rpos, spos); // position relative to ship + rpos = HPvector_subtract(rpos, spos); // position relative to ship - if (!vector_equal(rpos, kZeroVector)) + if (!HPvector_equal(rpos, kZeroHPVector)) { - rpos = vector_normal(rpos); + rpos = HPvector_normal(rpos); - if (!vector_equal(rpos, vector_flip(kBasisZVector))) + if (!HPvector_equal(rpos, HPvector_flip(kBasisZHPVector))) { - q1 = quaternion_rotation_between(rpos, kBasisZVector); + q1 = quaternion_rotation_between(HPVectorToVector(rpos), kBasisZVector); } else { @@ -2164,12 +2164,12 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC if (entity == nil) return nil; ShipEntity *ship = nil; - Vector spawn_pos; + HPVector spawn_pos; Quaternion spawn_q; GLfloat offset = (randf() + randf()) * entity->collision_radius; quaternion_set_random(&spawn_q); - spawn_pos = vector_add([entity position], vector_multiply_scalar(vector_forward_from_quaternion(spawn_q), offset)); + spawn_pos = HPvector_add([entity position], vectorToHPVector(vector_multiply_scalar(vector_forward_from_quaternion(spawn_q), offset))); ship = [self addShipWithRole:desc launchPos:spawn_pos rfactor:0.0]; [ship setOrientation:spawn_q]; @@ -2178,7 +2178,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (OOVisualEffectEntity *) addVisualEffectAt:(Vector)pos withKey:(NSString *)key +- (OOVisualEffectEntity *) addVisualEffectAt:(HPVector)pos withKey:(NSString *)key { OOJS_PROFILE_ENTER @@ -2201,7 +2201,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (ShipEntity *) addShipAt:(Vector)pos withRole:(NSString *)role withinRadius:(GLfloat)radius +- (ShipEntity *) addShipAt:(HPVector)pos withRole:(NSString *)role withinRadius:(GLfloat)radius { OOJS_PROFILE_ENTER @@ -2222,7 +2222,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } else { - pos = vector_add(pos, OOVectorRandomSpatial(radius)); + pos = HPvector_add(pos, OOHPVectorRandomSpatial(radius)); } ShipEntity *ship = [self newShipWithRole:role]; // is retained @@ -2269,7 +2269,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } } - if (distance([self getWitchspaceExitPosition], pos) > SCANNER_MAX_RANGE) + if (HPdistance([self getWitchspaceExitPosition], pos) > SCANNER_MAX_RANGE) { // nothing extra to do success = [self addEntity:ship]; // STATUS_IN_FLIGHT, AI state GLOBAL - ship is retained globally @@ -2307,7 +2307,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (NSArray *) addShipsAt:(Vector)pos withRole:(NSString *)role quantity:(unsigned)count withinRadius:(GLfloat)radius asGroup:(BOOL)isGroup +- (NSArray *) addShipsAt:(HPVector)pos withRole:(NSString *)role quantity:(unsigned)count withinRadius:(GLfloat)radius asGroup:(BOOL)isGroup { OOJS_PROFILE_ENTER @@ -2344,7 +2344,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC NSMutableArray *ships = [NSMutableArray arrayWithCapacity:count]; ShipEntity *ship = nil; Entity *entity = nil; - Vector pos = kZeroVector, direction = kZeroVector, point0 = kZeroVector, point1 = kZeroVector; + HPVector pos = kZeroHPVector, direction = kZeroHPVector, point0 = kZeroHPVector, point1 = kZeroHPVector; double radius = 0; if ([route isEqualToString:@"pw"] || [route isEqualToString:@"sw"] || [route isEqualToString:@"ps"]) @@ -2382,8 +2382,8 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC radius = [entity radius]; // shorten the route by scanner range & sun radius, otherwise ships could be created inside it. - direction = vector_normal(vector_subtract(point0, point1)); - point0 = vector_subtract(point0, vector_multiply_scalar(direction, radius0 + SCANNER_MAX_RANGE * 1.1f)); + direction = HPvector_normal(HPvector_subtract(point0, point1)); + point0 = HPvector_subtract(point0, HPvector_multiply_scalar(direction, radius0 + SCANNER_MAX_RANGE * 1.1f)); } else if ([route isEqualTo:@"st"]) { @@ -2395,8 +2395,8 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC else return nil; // no route specifier? We shouldn't be here! // shorten the route by scanner range & radius, otherwise ships could be created inside the route destination. - direction = vector_normal(vector_subtract(point1, point0)); - point1 = vector_subtract(point1, vector_multiply_scalar(direction, radius + SCANNER_MAX_RANGE * 1.1f)); + direction = HPvector_normal(HPvector_subtract(point1, point0)); + point1 = HPvector_subtract(point1, HPvector_multiply_scalar(direction, radius + SCANNER_MAX_RANGE * 1.1f)); pos = [self fractionalPositionFrom:point0 to:point1 withFraction:routeFraction]; if(isGroup) @@ -2469,7 +2469,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } -- (void) setUpBreakPattern:(Vector) pos orientation:(Quaternion) q forDocking:(BOOL) forDocking +- (void) setUpBreakPattern:(HPVector) pos orientation:(Quaternion) q forDocking:(BOOL) forDocking { int i; OOBreakPatternEntity *ring = nil; @@ -2524,7 +2524,7 @@ GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOC } Vector offset = vector_multiply_scalar(v, i * BREAK_PATTERN_RING_SPACING); - [ring setPosition:vector_add(pos, offset)]; // ahead of the player + [ring setPosition:HPvector_add(pos, vectorToHPVector(offset))]; // ahead of the player [ring setOrientation:q]; [ring setVelocity:vel]; [ring setLifetime:i * BREAK_PATTERN_RING_SPACING]; @@ -3815,7 +3815,7 @@ static const OOMatrix starboard_matrix = } -- (BOOL) viewFrustumIntersectsSphereAt:(Vector)position withRadius:(GLfloat)radius +- (BOOL) viewFrustumIntersectsSphereAt:(HPVector)position withRadius:(GLfloat)radius { int p; for (p = 0; p < 6; p++) @@ -3851,7 +3851,7 @@ static const OOMatrix starboard_matrix = if (!displayGUI && wasDisplayGUI) { // reset light1 position for the shaders - if (cachedSun) [UNIVERSE setMainLightPosition:[cachedSun position]]; // the main light is the sun. + if (cachedSun) [UNIVERSE setMainLightPosition:HPVectorToVector([cachedSun position])]; // the main light is the sun. else [UNIVERSE setMainLightPosition:kZeroVector]; } wasDisplayGUI = displayGUI; @@ -3866,7 +3866,8 @@ static const OOMatrix starboard_matrix = } } - position = [player viewpointPosition]; + // HPVect: camera relative + position = HPVectorToVector([player viewpointPosition]); v_status = [player status]; [self getActiveViewMatrix:&view_matrix forwardVector:&view_dir upVector:&view_up]; @@ -3913,6 +3914,7 @@ static const OOMatrix starboard_matrix = // rotate the view OOGL(GLMultOOMatrix([player rotationMatrix])); // translate the view + // HPVect: camera-relative position OOGL(GLTranslateOOVector(vector_flip(position))); OOGL(glLightModelfv(GL_LIGHT_MODEL_AMBIENT, stars_ambient)); } @@ -3968,7 +3970,8 @@ static const OOMatrix starboard_matrix = if (EXPECT(drawthing != player)) { //translate the object - GLTranslateOOVector([drawthing position]); + // HPVect: camera relative + GLTranslateOOVector(HPVectorToVector([drawthing position])); //rotate the object GLMultOOMatrix([drawthing drawRotationMatrix]); } @@ -4029,7 +4032,8 @@ static const OOMatrix starboard_matrix = if (EXPECT(drawthing != player)) { //translate the object - GLTranslateOOVector([drawthing position]); + // HPVect: camera relative positions + GLTranslateOOVector(HPVectorToVector([drawthing position])); //rotate the object GLMultOOMatrix([drawthing drawRotationMatrix]); } @@ -4468,9 +4472,9 @@ static BOOL MaintainLinkedLists(Universe *uni) [entity wasAddedToUniverse]; // maintain sorted list (and for the scanner relative position) - Vector entity_pos = entity->position; - Vector delta = vector_between(entity_pos, PLAYER->position); - double z_distance = magnitude2(delta); + HPVector entity_pos = entity->position; + HPVector delta = HPvector_between(entity_pos, PLAYER->position); + double z_distance = HPmagnitude2(delta); entity->zero_distance = z_distance; unsigned index = n_entities; sortedEntities[index] = entity; @@ -4636,14 +4640,14 @@ static BOOL MaintainLinkedLists(Universe *uni) } -- (BOOL) isVectorClearFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(Vector) p2 +- (BOOL) isVectorClearFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(HPVector) p2 { if (!e1) return NO; - Vector f1; - Vector p1 = e1->position; - Vector v1 = p2; + HPVector f1; + HPVector p1 = e1->position; + HPVector v1 = p2; v1.x -= p1.x; v1.y -= p1.y; v1.z -= p1.z; // vector from entity to p2 double nearest = sqrt(v1.x*v1.x + v1.y*v1.y + v1.z*v1.z) - dist; // length of vector @@ -4658,27 +4662,27 @@ static BOOL MaintainLinkedLists(Universe *uni) my_entities[i] = [sortedEntities[i] retain]; // retained if (v1.x || v1.y || v1.z) - f1 = vector_normal(v1); // unit vector in direction of p2 from p1 + f1 = HPvector_normal(v1); // unit vector in direction of p2 from p1 else - f1 = make_vector(0, 0, 1); + f1 = make_HPvector(0, 0, 1); for (i = 0; i < ent_count ; i++) { Entity *e2 = my_entities[i]; if ((e2 != e1)&&([e2 canCollide])) { - Vector epos = e2->position; + HPVector epos = e2->position; epos.x -= p1.x; epos.y -= p1.y; epos.z -= p1.z; // epos now holds vector from p1 to this entities position - double d_forward = dot_product(epos,f1); // distance along f1 which is nearest to e2's position + double d_forward = HPdot_product(epos,f1); // distance along f1 which is nearest to e2's position if ((d_forward > 0)&&(d_forward < nearest)) { double cr = 1.10 * (e2->collision_radius + e1->collision_radius); // 10% safety margin - Vector p0 = e1->position; + HPVector p0 = e1->position; p0.x += d_forward * f1.x; p0.y += d_forward * f1.y; p0.z += d_forward * f1.z; // p0 holds nearest point on current course to center of incident object - Vector epos = e2->position; + HPVector epos = e2->position; p0.x -= epos.x; p0.y -= epos.y; p0.z -= epos.z; // compare with center of incident object double dist2 = p0.x * p0.x + p0.y * p0.y + p0.z * p0.z; @@ -4697,17 +4701,17 @@ static BOOL MaintainLinkedLists(Universe *uni) } -- (Entity*) hazardOnRouteFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(Vector) p2 +- (Entity*) hazardOnRouteFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(HPVector) p2 { if (!e1) return nil; - Vector f1; - Vector p1 = e1->position; - Vector v1 = p2; + HPVector f1; + HPVector p1 = e1->position; + HPVector v1 = p2; v1.x -= p1.x; v1.y -= p1.y; v1.z -= p1.z; // vector from entity to p2 - double nearest = sqrt(v1.x*v1.x + v1.y*v1.y + v1.z*v1.z) - dist; // length of vector + double nearest = HPmagnitude(v1) - dist; // length of vector if (nearest < 0.0) return nil; // within range already! @@ -4720,30 +4724,30 @@ static BOOL MaintainLinkedLists(Universe *uni) my_entities[i] = [sortedEntities[i] retain]; // retained if (v1.x || v1.y || v1.z) - f1 = vector_normal(v1); // unit vector in direction of p2 from p1 + f1 = HPvector_normal(v1); // unit vector in direction of p2 from p1 else - f1 = make_vector(0, 0, 1); + f1 = make_HPvector(0, 0, 1); for (i = 0; (i < ent_count) && (!result) ; i++) { Entity *e2 = my_entities[i]; if ((e2 != e1)&&([e2 canCollide])) { - Vector epos = e2->position; + HPVector epos = e2->position; epos.x -= p1.x; epos.y -= p1.y; epos.z -= p1.z; // epos now holds vector from p1 to this entities position - double d_forward = dot_product(epos,f1); // distance along f1 which is nearest to e2's position + double d_forward = HPdot_product(epos,f1); // distance along f1 which is nearest to e2's position if ((d_forward > 0)&&(d_forward < nearest)) { double cr = 1.10 * (e2->collision_radius + e1->collision_radius); // 10% safety margin - Vector p0 = e1->position; + HPVector p0 = e1->position; p0.x += d_forward * f1.x; p0.y += d_forward * f1.y; p0.z += d_forward * f1.z; // p0 holds nearest point on current course to center of incident object - Vector epos = e2->position; + HPVector epos = e2->position; p0.x -= epos.x; p0.y -= epos.y; p0.z -= epos.z; // compare with center of incident object - double dist2 = p0.x * p0.x + p0.y * p0.y + p0.z * p0.z; + double dist2 = HPmagnitude2(p0); if (dist2 < cr*cr) result = e2; } @@ -4755,51 +4759,51 @@ static BOOL MaintainLinkedLists(Universe *uni) } -- (Vector) getSafeVectorFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(Vector) p2 +- (HPVector) getSafeVectorFromEntity:(Entity *) e1 toDistance:(double)dist fromPoint:(HPVector) p2 { // heuristic three if (!e1) { OOLog(kOOLogParameterError, @"***** No entity set in Universe getSafeVectorFromEntity:toDistance:fromPoint:"); - return kZeroVector; + return kZeroHPVector; } - Vector f1; - Vector result = p2; + HPVector f1; + HPVector result = p2; int i; int ent_count = n_entities; Entity* my_entities[ent_count]; for (i = 0; i < ent_count; i++) my_entities[i] = [sortedEntities[i] retain]; // retained - Vector p1 = e1->position; - Vector v1 = p2; + HPVector p1 = e1->position; + HPVector v1 = p2; v1.x -= p1.x; v1.y -= p1.y; v1.z -= p1.z; // vector from entity to p2 double nearest = sqrt(v1.x*v1.x + v1.y*v1.y + v1.z*v1.z) - dist; // length of vector if (v1.x || v1.y || v1.z) - f1 = vector_normal(v1); // unit vector in direction of p2 from p1 + f1 = HPvector_normal(v1); // unit vector in direction of p2 from p1 else - f1 = make_vector(0, 0, 1); + f1 = make_HPvector(0, 0, 1); for (i = 0; i < ent_count; i++) { Entity *e2 = my_entities[i]; if ((e2 != e1)&&([e2 canCollide])) { - Vector epos = e2->position; + HPVector epos = e2->position; epos.x -= p1.x; epos.y -= p1.y; epos.z -= p1.z; - double d_forward = dot_product(epos,f1); + double d_forward = HPdot_product(epos,f1); if ((d_forward > 0)&&(d_forward < nearest)) { double cr = 1.20 * (e2->collision_radius + e1->collision_radius); // 20% safety margin - Vector p0 = e1->position; + HPVector p0 = e1->position; p0.x += d_forward * f1.x; p0.y += d_forward * f1.y; p0.z += d_forward * f1.z; // p0 holds nearest point on current course to center of incident object - Vector epos = e2->position; + HPVector epos = e2->position; p0.x -= epos.x; p0.y -= epos.y; p0.z -= epos.z; // compare with center of incident object @@ -4819,29 +4823,29 @@ static BOOL MaintainLinkedLists(Universe *uni) result.z += ((int)(Ranrot() % 1024) - 512)/512.0; // -1.0 .. +1.0 } - Vector nearest_point = p1; + HPVector nearest_point = p1; nearest_point.x += d_forward * f1.x; nearest_point.y += d_forward * f1.y; nearest_point.z += d_forward * f1.z; // nearest point now holds nearest point on line to center of incident object - Vector outward = nearest_point; + HPVector outward = nearest_point; outward.x -= result.x; outward.y -= result.y; outward.z -= result.z; if (outward.x||outward.y||outward.z) - outward = vector_normal(outward); + outward = HPvector_normal(outward); else outward.y = 1.0; // outward holds unit vector through the nearest point on the line from the center of incident object - Vector backward = p1; + HPVector backward = p1; backward.x -= result.x; backward.y -= result.y; backward.z -= result.z; if (backward.x||backward.y||backward.z) - backward = vector_normal(backward); + backward = HPvector_normal(backward); else backward.z = -1.0; // backward holds unit vector from center of the incident object to the center of the ship - Vector dd = result; + HPVector dd = result; dd.x -= p1.x; dd.y -= p1.y; dd.z -= p1.z; - double current_distance = sqrt (dd.x*dd.x + dd.y*dd.y + dd.z*dd.z); + double current_distance = HPmagnitude(dd); // sanity check current_distance if (current_distance < cr * 1.25) // 25% safety margin @@ -4871,7 +4875,7 @@ static BOOL MaintainLinkedLists(Universe *uni) ShipEntity *hit_entity = nil; ShipEntity *hit_subentity = nil; - Vector p0 = [srcEntity position]; + HPVector p0 = [srcEntity position]; Quaternion q1 = [srcEntity normalOrientation]; ShipEntity *parent = [srcEntity parentEntity]; @@ -4879,7 +4883,7 @@ static BOOL MaintainLinkedLists(Universe *uni) { // we're a subentity! BoundingBox bbox = [srcEntity boundingBox]; - Vector midfrontplane = make_vector(0.5 * (bbox.max.x + bbox.min.x), 0.5 * (bbox.max.y + bbox.min.y), bbox.max.z); + HPVector midfrontplane = make_HPvector(0.5 * (bbox.max.x + bbox.min.x), 0.5 * (bbox.max.y + bbox.min.y), bbox.max.z); p0 = [srcEntity absolutePositionForSubentityOffset:midfrontplane]; q1 = [parent orientation]; if ([parent isPlayer]) q1.w = -q1.w; @@ -4903,7 +4907,7 @@ static BOOL MaintainLinkedLists(Universe *uni) Vector u1, f1, r1; basis_vectors_from_quaternion(q1, &r1, &u1, &f1); - p0 = vector_add(p0, OOVectorMultiplyMatrix(offset, OOMatrixFromBasisVectors(r1, u1, f1))); + p0 = HPvector_add(p0, vectorToHPVector(OOVectorMultiplyMatrix(offset, OOMatrixFromBasisVectors(r1, u1, f1)))); switch (direction) { @@ -4925,7 +4929,7 @@ static BOOL MaintainLinkedLists(Universe *uni) } basis_vectors_from_quaternion(q1, &r1, NULL, &f1); - Vector p1 = vector_add(p0, vector_multiply_scalar(f1, nearest)); //endpoint + HPVector p1 = HPvector_add(p0, vectorToHPVector(vector_multiply_scalar(f1, nearest))); //endpoint for (i = 0; i < ship_count; i++) { @@ -4933,7 +4937,7 @@ static BOOL MaintainLinkedLists(Universe *uni) // check outermost bounding sphere GLfloat cr = e2->collision_radius; - Vector rpos = vector_subtract(e2->position, p0); + Vector rpos = HPVectorToVector(HPvector_subtract(e2->position, p0)); Vector v_off = make_vector(dot_product(rpos, r1), dot_product(rpos, u1), dot_product(rpos, f1)); if (v_off.z > 0.0 && v_off.z < nearest + cr && // ahead AND within range v_off.x < cr && v_off.x > -cr && v_off.y < cr && v_off.y > -cr && // AND not off to one side or another @@ -4950,7 +4954,7 @@ static BOOL MaintainLinkedLists(Universe *uni) } hit_entity = e2; nearest = hit; - p1 = vector_add(p0, vector_multiply_scalar(f1, nearest)); + p1 = HPvector_add(p0, vectorToHPVector(vector_multiply_scalar(f1, nearest))); } } } @@ -4996,7 +5000,7 @@ static BOOL MaintainLinkedLists(Universe *uni) basis_vectors_from_quaternion(q1, &r1, &u1, &f1); Vector offset = [player weaponViewOffset]; - Vector p1 = vector_add([player position], OOVectorMultiplyMatrix(offset, OOMatrixFromBasisVectors(r1, u1, f1))); + HPVector p1 = HPvector_add([player position], vectorToHPVector(OOVectorMultiplyMatrix(offset, OOMatrixFromBasisVectors(r1, u1, f1)))); // Note: deliberately tied to view direction, not weapon facing. All custom views count as forward for targeting. switch (viewDirection) @@ -5020,7 +5024,7 @@ static BOOL MaintainLinkedLists(Universe *uni) Entity *e2 = my_entities[i]; if ([e2 canCollide] && [e2 scanClass] != CLASS_NO_DRAW) { - Vector rp = vector_subtract([e2 position], p1); + Vector rp = HPVectorToVector(HPvector_subtract([e2 position], p1)); OOScalar dist2 = magnitude2(rp); if (dist2 < nearest2) { @@ -5158,13 +5162,13 @@ static BOOL MaintainLinkedLists(Universe *uni) ofEntity:(Entity *)e1 { unsigned i, found = 0; - Vector p1, p2; + HPVector p1; double distance, cr; if (predicate == NULL) predicate = YESPredicate; if (e1 != nil) p1 = e1->position; - else p1 = kZeroVector; + else p1 = kZeroHPVector; for (i = 0; i < n_entities; i++) { @@ -5174,9 +5178,8 @@ static BOOL MaintainLinkedLists(Universe *uni) if (range < 0) distance = -1; // Negative range means infinity else { - p2 = vector_subtract(e2->position, p1); cr = range + e2->collision_radius; - distance = magnitude2(p2) - cr * cr; + distance = HPdistance2(e2->position, p1) - cr * cr; } if (distance < 0) { @@ -5217,12 +5220,11 @@ static BOOL MaintainLinkedLists(Universe *uni) } -OOINLINE BOOL EntityInRange(Vector p1, Entity *e2, float range) +OOINLINE BOOL EntityInRange(HPVector p1, Entity *e2, float range) { if (range < 0) return YES; - Vector p2 = vector_subtract(e2->position, p1); float cr = range + e2->collision_radius; - return magnitude2(p2) < cr * cr; + return HPdistance2(e2->position,p1) < cr * cr; } @@ -5236,7 +5238,7 @@ OOINLINE BOOL EntityInRange(Vector p1, Entity *e2, float range) OOJS_PROFILE_ENTER unsigned i; - Vector p1; + HPVector p1; NSMutableArray *result = nil; OOJSPauseTimeLimiter(); @@ -5246,7 +5248,7 @@ OOINLINE BOOL EntityInRange(Vector p1, Entity *e2, float range) result = [NSMutableArray arrayWithCapacity:n_entities]; if (e1 != nil) p1 = [e1 position]; - else p1 = kZeroVector; + else p1 = kZeroHPVector; for (i = 0; i < n_entities; i++) { @@ -5351,19 +5353,19 @@ OOINLINE BOOL EntityInRange(Vector p1, Entity *e2, float range) relativeToEntity:(Entity *)entity { unsigned i; - Vector p1; + HPVector p1; float rangeSq = INFINITY; id result = nil; if (predicate == NULL) predicate = YESPredicate; if (entity != nil) p1 = [entity position]; - else p1 = kZeroVector; + else p1 = kZeroHPVector; for (i = 0; i < n_entities; i++) { Entity *e2 = sortedEntities[i]; - float distanceToReferenceEntitySquared = (float)distance2(p1, [e2 position]); + float distanceToReferenceEntitySquared = (float)HPdistance2(p1, [e2 position]); if (entity != e2 && distanceToReferenceEntitySquared < rangeSq && @@ -5883,7 +5885,7 @@ OOINLINE BOOL EntityInRange(Vector p1, Entity *e2, float range) [demo_ship setStatus:STATUS_COCKPIT_DISPLAY]; demo_start_z=DEMO2_VANISHING_DISTANCE * demo_ship->collision_radius; [demo_ship setPositionX:0.0f y:0.0f z:demo_start_z]; - [demo_ship setDestination: make_vector(0.0f, 0.0f, demo_start_z * 0.01f)]; // ideal position + [demo_ship setDestination: make_HPvector(0.0f, 0.0f, demo_start_z * 0.01f)]; // ideal position [demo_ship setVelocity:kZeroVector]; [demo_ship setScanClass: CLASS_NO_DRAW]; [demo_ship setRoll:M_PI/5.0]; @@ -9089,17 +9091,17 @@ static OOComparisonResult comparePrice(id dict1, id dict2, void *context) } -- (Vector) getWitchspaceExitPosition +- (HPVector) getWitchspaceExitPosition { return [self getWitchspaceExitPositionResettingRandomSeed:NO]; } -- (Vector) randomizeFromSeedAndGetWitchspaceExitPosition +- (HPVector) randomizeFromSeedAndGetWitchspaceExitPosition { return [self getWitchspaceExitPositionResettingRandomSeed:YES]; } -- (Vector) getWitchspaceExitPositionResettingRandomSeed:(BOOL)resetSeed +- (HPVector) getWitchspaceExitPositionResettingRandomSeed:(BOOL)resetSeed { if (resetSeed) { @@ -9110,7 +9112,7 @@ static OOComparisonResult comparePrice(id dict1, id dict2, void *context) gen_rnd_number(); } - return kZeroVector; + return kZeroHPVector; } @@ -9129,26 +9131,26 @@ static OOComparisonResult comparePrice(id dict1, id dict2, void *context) return q_result; } - -- (Vector) getSunSkimStartPositionForShip:(ShipEntity*) ship +// FIXME: should use vector functions +- (HPVector) getSunSkimStartPositionForShip:(ShipEntity*) ship { if (!ship) { OOLog(kOOLogParameterError, @"***** No ship set in Universe getSunSkimStartPositionForShip:"); - return kZeroVector; + return kZeroHPVector; } OOSunEntity* the_sun = [self sun]; // get vector from sun position to ship if (!the_sun) { OOLog(kOOLogInconsistentState, @"***** No sun set in Universe getSunSkimStartPositionForShip:"); - return kZeroVector; + return kZeroHPVector; } - Vector v0 = the_sun->position; - Vector v1 = ship->position; + HPVector v0 = the_sun->position; + HPVector v1 = ship->position; v1.x -= v0.x; v1.y -= v0.y; v1.z -= v0.z; // vector from sun to ship if (v1.x||v1.y||v1.z) - v1 = vector_normal(v1); + v1 = HPvector_normal(v1); else v1.z = 1.0; double radius = SUN_SKIM_RADIUS_FACTOR * the_sun->collision_radius - 250.0; // 250 m inside the skim radius @@ -9158,36 +9160,36 @@ static OOComparisonResult comparePrice(id dict1, id dict2, void *context) return v1; } - -- (Vector) getSunSkimEndPositionForShip:(ShipEntity*) ship +// FIXME: should use vector functions +- (HPVector) getSunSkimEndPositionForShip:(ShipEntity*) ship { OOSunEntity* the_sun = [self sun]; if (!ship) { OOLog(kOOLogParameterError, @"***** No ship set in Universe getSunSkimEndPositionForShip:"); - return kZeroVector; + return kZeroHPVector; } // get vector from sun position to ship if (!the_sun) { OOLog(kOOLogInconsistentState, @"***** No sun set in Universe getSunSkimEndPositionForShip:"); - return kZeroVector; + return kZeroHPVector; } - Vector v0 = the_sun->position; - Vector v1 = ship->position; + HPVector v0 = the_sun->position; + HPVector v1 = ship->position; v1.x -= v0.x; v1.y -= v0.y; v1.z -= v0.z; if (v1.x||v1.y||v1.z) - v1 = vector_normal(v1); + v1 = HPvector_normal(v1); else v1.z = 1.0; - Vector v2 = make_vector(randf()-0.5, randf()-0.5, randf()-0.5); // random vector + HPVector v2 = make_HPvector(randf()-0.5, randf()-0.5, randf()-0.5); // random vector if (v2.x||v2.y||v2.z) - v2 = vector_normal(v2); + v2 = HPvector_normal(v2); else v2.x = 1.0; - Vector v3 = cross_product(v1, v2); // random vector at 90 degrees to v1 and v2 (random Vector) + HPVector v3 = HPcross_product(v1, v2); // random vector at 90 degrees to v1 and v2 (random Vector) if (v3.x||v3.y||v3.z) - v3 = vector_normal(v3); + v3 = HPvector_normal(v3); else v3.y = 1.0; double radius = SUN_SKIM_RADIUS_FACTOR * the_sun->collision_radius - 250.0; // 250 m inside the skim radius @@ -9196,7 +9198,7 @@ static OOComparisonResult comparePrice(id dict1, id dict2, void *context) v1.x += 15000 * v3.x; v1.y += 15000 * v3.y; v1.z += 15000 * v3.z; // point 15000m at a tangent to sun from v1 v1.x -= v0.x; v1.y -= v0.y; v1.z -= v0.z; if (v1.x||v1.y||v1.z) - v1 = vector_normal(v1); + v1 = HPvector_normal(v1); else v1.z = 1.0; v1.x *= radius; v1.y *= radius; v1.z *= radius; @@ -9863,7 +9865,7 @@ Entity *gOOJSPlayerIfStale = nil; } -- (ShipEntity *) spawnPatrolShipFrom:(Vector)startPos alongRoute:(Vector)route withOffset:(double)offset +/*- (ShipEntity *) spawnPatrolShipFrom:(Vector)startPos alongRoute:(Vector)route withOffset:(double)offset { ShipEntity *hunter_ship = nil; @@ -9916,10 +9918,10 @@ Entity *gOOJSPlayerIfStale = nil; [hunter_ship release]; // addEntity retains! } return hunter_ship; -} + }*/ -- (void) addWolfpackShipNear:(Vector)launchPos withGroup:(OOShipGroup *)wolfpackGroup andBounty:(unsigned)bounty +/*- (void) addWolfpackShipNear:(Vector)launchPos withGroup:(OOShipGroup *)wolfpackGroup andBounty:(unsigned)bounty { // pirates get their custom random displacement, closer than most ships. launchPos.x += [self randomDistanceWithinScanner] * WOLFPACK_SHIPS_DISTANCE; @@ -9943,14 +9945,14 @@ Entity *gOOJSPlayerIfStale = nil; [self addEntity:pirate_ship]; // STATUS_IN_FLIGHT, AI state GLOBAL [pirate_ship release]; } -} + }*/ -- (Vector) fractionalPositionFrom:(Vector)point0 to:(Vector)point1 withFraction:(double)routeFraction +- (HPVector) fractionalPositionFrom:(HPVector)point0 to:(HPVector)point1 withFraction:(double)routeFraction { if (routeFraction == NSNotFound) routeFraction = randf(); - point1 = OOVectorInterpolate(point0, point1, routeFraction); + point1 = OOHPVectorInterpolate(point0, point1, routeFraction); point1.x += 2 * SCANNER_MAX_RANGE * (randf() - 0.5); point1.y += 2 * SCANNER_MAX_RANGE * (randf() - 0.5); @@ -10141,7 +10143,7 @@ static void PreloadOneSound(NSString *soundName) } -- (void) populateSpaceFromHyperPoint:(Vector) h1_pos toPlanetPosition:(Vector) p1_pos andSunPosition:(Vector) s1_pos +/*- (void) populateSpaceFromHyperPoint:(Vector) h1_pos toPlanetPosition:(Vector) p1_pos andSunPosition:(Vector) s1_pos { unsigned i, r, escortsWeight; unsigned totalCliques, totalRocks = 0; @@ -10217,7 +10219,7 @@ static void PreloadOneSound(NSString *soundName) while ((Ranrot() % 100) < thargoidChance && thargoid_parties < 16) thargoid_parties++; - /* + // Adjusting parties amounts. Up to 1.76.x the adjustment meant upping the number of asteroid fields. That's inconsistent with the care we've taken to keep suns, planets & main stations exactly @@ -10228,7 +10230,7 @@ static void PreloadOneSound(NSString *soundName) of Oolite's systems thus far. I provided the option of fixing both asteroid fields positions and hermit presence via the FIXED_ASTEROID_FIELDS #defined, just in case. --Kaks 20120902 - */ + // if (trading_parties + raiding_parties + hunting_parties < 10) { @@ -10580,17 +10582,17 @@ static void PreloadOneSound(NSString *soundName) clusterSize:1 + (Ranrot() % 6)]; } -} +}*/ -- (NSUInteger) scatterAsteroidsAt:(Vector)spawnPos withVelocity:(Vector)spawnVel includingRockHermit:(BOOL)spawnHermit asCinders:(BOOL)asCinders +/*- (NSUInteger) scatterAsteroidsAt:(Vector)spawnPos withVelocity:(Vector)spawnVel includingRockHermit:(BOOL)spawnHermit asCinders:(BOOL)asCinders { //NSUInteger clusterSize = 1 + (Ranrot() % 6) + (Ranrot() % 6); NSUInteger clusterSize = 1 + (Ranrot() % 11); return [self scatterAsteroidsAt:spawnPos withVelocity:spawnVel includingRockHermit:spawnHermit asCinders:asCinders clusterSize:clusterSize]; -} + }*/ -- (NSUInteger) scatterAsteroidsAt:(Vector)spawnPos withVelocity:(Vector)spawnVel includingRockHermit:(BOOL)spawnHermit asCinders:(BOOL)asCinders clusterSize:(NSUInteger)clusterSize +/*- (NSUInteger) scatterAsteroidsAt:(Vector)spawnPos withVelocity:(Vector)spawnVel includingRockHermit:(BOOL)spawnHermit asCinders:(BOOL)asCinders clusterSize:(NSUInteger)clusterSize { NSUInteger rocks = 0; // Vector launchPos; @@ -10640,7 +10642,7 @@ static void PreloadOneSound(NSString *soundName) } } return rocks; -} + }*/ - (NSString *)chooseStringForKey:(NSString *)key inDictionary:(NSDictionary *)dictionary