--------------------------------------------------------------------------------------
-- Engine Script for controlling audio in rear vehicles
-- RailWorks 2: Train Simulator
--------------------------------------------------------------------------------------
-- Based on original script by David Brindley
--------------------------------------------------------------------------------------

IDLERPM = 450
FULLRPM = 850

RPM_ID = 1709
RPMD_ID = 1710

function Initialise ()

	gPrevRPM = 0
	gPrevRPMDelta = 0

	Call( "BeginUpdate" )

end

function OnControlValueChange ( name, index, value )

	if Call( "*:ControlExists", name, index ) then

		Call( "*:SetControlValue", name, index, value );

	end

end

function Update ( time )

-- Get rpm values for this vehicle.
	rpm = Call( "*:GetControlValue", "RPM", 0 )
	rpm_change = Call( "*:GetControlValue", "RPMDelta", 0 )

-- If this is a player train and this vehicle is the driven one, then send
-- RPM values in both directions along train. Note the Driven control is set
-- by the simulation script, which only runs on the vehicle the player is driving.
-- Only send messages if values have changed.

	if ( Call( "GetIsPlayer" ) == 1 ) then

		if ( Call( "*:GetControlValue", "Active", 0 ) == 1 ) then
			if ( rpm ~= gPrevRPM ) then
				Call( "SendConsistMessage", RPM_ID, rpm, 1 )
				Call( "SendConsistMessage", RPM_ID, rpm, 0 )
			end
			if ( rpm_change ~= gPrevRPMDelta ) then
				Call( "SendConsistMessage", RPMD_ID, rpm_change, 1 )
				Call( "SendConsistMessage", RPMD_ID, rpm_change, 0 )
			end
		end

		gPrevRPM = rpm
		gPrevRPMDelta = rpm_change

	end

end

-- Core sim function executed if a consist message is received.

function OnConsistMessage ( msg, argument, direction )

-- If this is not the driven vehicle then update the controls for RPM values with the supplied data.

	if ( Call( "*:GetControlValue", "Active", 0 ) == 0 ) then

		if ( msg == RPM_ID ) then
			Call( "*:SetControlValue", "RPM", 0, argument )
		elseif ( msg == RPMD_ID ) then
			Call( "*:SetControlValue", "RPMDelta", 0, argument )
		end

-- Pass message along in same direction.
		Call( "SendConsistMessage", msg, argument, direction )

	end

end
