import { SystemPriority } from '../EntityComponentSystem';
import { MotionComponent } from '../EntityComponentSystem/Components/MotionComponent';
import { TransformComponent } from '../EntityComponentSystem/Components/TransformComponent';
import { System, SystemType } from '../EntityComponentSystem/System';
import { BodyComponent } from './BodyComponent';
import { CollisionType } from './CollisionType';
import { EulerIntegrator } from './Integrator';
export class MotionSystem extends System {
    constructor(world, physics) {
        super();
        this.world = world;
        this.physics = physics;
        this.systemType = SystemType.Update;
        this.priority = SystemPriority.Higher;
        this._physicsConfigDirty = false;
        physics.$configUpdate.subscribe(() => (this._physicsConfigDirty = true));
        this.query = this.world.query([TransformComponent, MotionComponent]);
    }
    update(elapsedMs) {
        let transform;
        let motion;
        const entities = this.query.entities;
        for (let i = 0; i < entities.length; i++) {
            transform = entities[i].get(TransformComponent);
            motion = entities[i].get(MotionComponent);
            const optionalBody = entities[i].get(BodyComponent);
            if (this._physicsConfigDirty && optionalBody) {
                optionalBody.updatePhysicsConfig(this.physics.config.bodies);
            }
            if (optionalBody === null || optionalBody === void 0 ? void 0 : optionalBody.sleeping) {
                continue;
            }
            const totalAcc = motion.acc.clone();
            if ((optionalBody === null || optionalBody === void 0 ? void 0 : optionalBody.collisionType) === CollisionType.Active && (optionalBody === null || optionalBody === void 0 ? void 0 : optionalBody.useGravity)) {
                totalAcc.addEqual(this.physics.config.gravity);
            }
            optionalBody === null || optionalBody === void 0 ? void 0 : optionalBody.captureOldTransform();
            // Update transform and motion based on Euler linear algebra
            EulerIntegrator.integrate(transform, motion, totalAcc, elapsedMs);
        }
        this._physicsConfigDirty = false;
    }
}
//# sourceMappingURL=MotionSystem.js.map