@name Starflight Universal - by MrStump v1.3
@inputs [Pod Cam]:wirelink
@persist Active ViewPause Speed LockChair TurnMult
@persist Step1 Step2 Step3
@outputs [Ship Chair Driver]:entity
@persist [ShipDest CamPos1 CamPos2]:vector
interval(50)

##############################################################
############### Starflight Universal Use Guide ###############
######################### By:MrStump #########################
#                                                            #
# INSTRUCTIONS FOR USE:                                      #
# 1)Spawn a 2x2 holo sphere (shell) from Miscellaneous Props #
# 2)Place sphere in middle of your ship(do not weld yet)     #
# 3)Attach this e2 to it and follow the instructions in chat #
# 4)When finished, alter variables below to fit your ship    #
# 5)After parenting, unfreeze all props but the sphere       #
#                                                            #
# NOTES FOR ADV DUPING:                                      #
# 1)When duping, right click chair first, then hold shift    #
#   and right click the ship. This is required because the   #
#   chair is not attached to the ship in any way.            #
# 2)Parenting after you paste your dupe is recommended for   #
#   best performance.                                        #
#                                                            #
# CONTROLS:                                                  #
# WASD for Forward/StrafeLeft/Back/StrafeRight               #
# Space/Alt for Up/Down (relative to world, no the ship)     #
# Shift for speed boost                                      #
# Scroll Wheel Up/Down toggles betwene cam positions         #
#                                                            #
# HOW IT WORKS:                                              #
# The 2x2 holo sphere is used as a flight gyro. A spacebuild #
# chair is then placed into the sphere by the e2, and moved  #
# around with the sphere. This unattached nature of the      #
# chair allows for real mouseaim flight. The sphere moves    #
# the ship around it like a pivot point. Make note this e2   #
# does no parenting, use a seperate E2 for that.             #
#                                                            #
# COMMON ISSUE:                                              #
# If the ship wobbles, it is because the sphere is not       #
# strong enough to make it point correctly. You may be able  #
# to fix it by redistributing/lessening weight and moving    #
# the sphere to your ship's center, but there is only so     #
# much total mass the sphere can move. In that case, use the #
# gyropod (intergalactic) version of this E2.                #
#                                                            #
##############################################################
# WARNING: May work on larger ships, but is not recommended! #
##############################################################
##############################################################

############################################################################################
######## Editable Variables ################################################################
if(first()|dupefinished()){
    Speed       = 65             #Determines speed, 45 by default
    LockChair   = 1              #Ejects non-owner from the chair. 1 is on, 0 is off. 1 by default.
    TurnMult    = 5              #Strength of the turning code. Default is 5-8
    CamPos1     = vec(80,0,0)    #Default camera position, or selectable with scroll wheel up
    CamPos2     = vec(-600,0,60) #Secondary camera position, selectable with scrollwheel down
    #NOTE: CamPos1 and CamPos2 are relative to the position of the sphere
}
###### END Editable Variables ###############################################################
############################################################################################

###############################################################
# Editing any following code is of course allowed, but not    #
# advised unless you know WTF you are doing. Its your E2 tho  #
###############################################################

if(dupefinished()){
    Ship = entity():isWeldedTo()
    Chair = Pod["Entity",entity]
    Ship:setMass(50000)
    #Chair:freeze()
    Chair:setAng(ang(0,Ship:angles():yaw(),0))
    ShipDest = Ship:pos()
    Ship:setAlpha(0)
    entity():setAlpha(1)
    Step1 = 0
    Step2 = 0
    Step3 = 0
    Step4 = 0
    Step4 = 1
    holoCreate(1,   Ship:pos(), vec(1,1,1), Ship:angles())
    holoModel(1,    "models/hunter/misc/sphere2x2.mdl")
    holoMaterial(1, "phoenix_storms/stripes")
    holoColor(1,    vec(71,30,20))
    holoParent(1,   Ship)
}

if(first()){
    Ship = entity():isWeldedTo()
    
    if(Ship:model()=="models/hunter/misc/shell2x2.mdl"){
        print("STEP1) Align the sphere so the red arrow points forward and the blue arrow points up then weld sphere to your ship.")
        holoCreate(1, Ship:toWorld(vec(60,0,0)), vec(3,3,3), Ship:toWorld(ang(90,0,0)), vec(255,0,0))
        holoModel(1, "cone")
        holoCreate(2, Ship:toWorld(vec(0,0,60)), vec(3,3,3), Ship:toWorld(ang( 0,0,0)), vec(0,0,255))
        holoModel(2, "cone")
        holoParent(1, entity())
        holoParent(2, entity())
        Ship:setMass(50000)
    }
    else{
        print("SETUP ERROR: You are not attaching the E2 to the correct prop.
        It MUST be attachedto prop models/hunter/misc/shell2x2.mdl,
        which is the holo sphere found in Miscellaneous Props.")
        print("Delete this E2 and try again")
    } 
    
    Step1 = 1
    Step2 = 0
    Step3 = 0
    Step4 = 0
    
}

if(Step1){
    if(Ship:hasConstraints()>1){
        print("STEP2) Spawn a chair (spacebuild Promethius Chair recommended). DO NOT WELD OR NOCOLLID ANYTHING TO/WITH CHAIR!")
        print("STEP3) Spawn an ADV POD CONTROLLER and CAM CONTROLLER, link both to chair.")
        print("STEP4) Wirelink this E2's coresponding wirelinks to Pod controller and Cam controller")
        holoDelete(1)
        holoDelete(2)
        Step1=0
        Step2=1
        
    }
}
if(Step2){
    if(->Cam & ->Pod){
        Chair = Pod["Entity",entity]
        if(Chair:model()==""){
            print("ERROR: You forgot to link the Pod Controller to the chair! Do so now and then repaste this e2")
            Step2 = 0
        }
        else{
            print("STEP5) Use a parenting E2 to parent the rest of your ship TO THE SPHERE. That's it, you're done!")
            print("REMINDER: When you go to dupe your ship, you must remember to dupe both the chair and the ship together because the chair is unconnected to the ship")
            Step2=0
            Step3=1
            Chair:setAng(ang(0,Ship:angles():yaw(),0))
          #  Chair:freeze()
            ShipDest = Ship:pos()
            Ship:setAlpha(0)
            entity():setAlpha(1)
            
            holoCreate(1,   Ship:pos(), vec(1,1,1), Ship:angles())
            holoModel(1,    "models/hunter/misc/sphere2x2.mdl")
            holoMaterial(1, "phoenix_storms/stripes")
            holoColor(1,    vec(71,30,20))
            holoParent(1,   Ship)
        }
    }
}

if(Step3){
    Active  = Pod["Active",number]
    ShipPos = Ship:pos()
    
    if(Active) {
        W          = Pod["W",number]
        A          = Pod["A",number]
        S          = Pod["S",number]
        D          = Pod["D",number]
        Space      = Pod["Space",number]
        Shift      = Pod["Shift",number]
        Alt        = Pod["Alt",number]
        PrevWeapon = Pod["PrevWeapon",number]
        NextWeapon = Pod["NextWeapon",number]
        #Mouse1     = Pod["Mouse1",number]
        #Mouse2     = Pod["Mouse2",number]
        #R          = Pod["R",number]
        #Light      = Pod["Light",number]
        
        if($Active){
            if(LockChair){ 
                Driver = Chair:driver()
                if(Driver!=owner()){
                    Pod["Eject",number] = 1
                }
                else{
                    ShipDest = ShipPos
                    Chair:propNotSolid(1)
                    Chair:propFreeze(1)
                    Cam["Activated",number] = 1
                }
            }
            else{
                ShipDest = ShipPos
                Chair:propNotSolid(1)
                Chair:propFreeze(1)
                Cam["Activated",number] = 1
            }
            Cam["Position",vector] = Ship:toWorld(CamPos1)
            Cam["Direction",vector] = Ship:forward()
            Cam["Parent",entity] = Ship
            
            timer("ViewPause",1500)
        }
        if(clk("ViewPause")){ViewPause=1 Ship:propFreeze(0)}
        
        DriverEye = Driver:eye()
        
        Cam["Direction",vector] = DriverEye
        
        if(W)            {ShipDest += DriverEye:rotate(ang(0,  0,0))*Speed*(1+Shift*2)}
        if(S)            {ShipDest +=-DriverEye:rotate(ang(0,  0,0))*Speed*(1+Shift*2)}
        if(A)            {ShipDest += DriverEye:rotate(ang(0, 90,0)):setZ(0)*Speed*(1+Shift*2)}
        if(D)            {ShipDest += DriverEye:rotate(ang(0,-90,0)):setZ(0)*Speed*(1+Shift*2)}
        if(Space)        {ShipDest += vec(0,0, Speed)}
        if(Alt)          {ShipDest += vec(0,0,-Speed)}
        if(PrevWeapon)   {Cam["Position",vector] = Ship:toWorld(CamPos1)}
        if(NextWeapon)   {Cam["Position",vector] = Ship:toWorld(CamPos2)}
        
        Vec = ShipDest - ShipPos
       # Ship:setVel(Vec*3)
        
        if(ViewPause){ DistViewPos = Chair:toWorld(Chair:toLocalAxis(DriverEye)*5000) }
        else{ DistViewPos = Chair:toWorld(Chair:forward()*5000) }
        ANG  = -Ship:heading(DistViewPos)
      #  Ship:setAngVel( shiftR(ANG:setRoll(-Ship:angles():roll()))*8 )
    }
    elseif($Active){
        Ship:propFreeze(1)
        Pod["Eject",number] = 0
        Cam["Activated",number] = 0
        Chair:propNotSolid(0)
        Chair:setAng(ang(0,Ship:angles():yaw(),0))
        ViewPause = 0
        ShipLockon = 0
    }
    
    Chair:reposition(Ship:toWorld(-vec(0,0,30)))
}
