-- xyzspain

Lemken_Gigant = {};

function Lemken_Gigant.prerequisitesPresent(specializations)
  return true;
end;

function Lemken_Gigant:load(xmlFile)
---ls2011
self.safeMode = true
  ---ls2011 
			---emision de particulas ruedas

self.wheelParticleSystems = {};
    local psFile = getXMLString(xmlFile, "vehicle.wheelParticleSystems#file");
    if psFile ~= nil then
        local i=0;
        while true do
            local baseName = string.format("vehicle.wheelParticleSystems.wheelParticleSystem(%d)", i);
            local node = getXMLString(xmlFile, baseName.. "#node");
            if node == nil then
                break;
            end;
            node = Utils.indexToObject(self.components, node);
			self.wheelParticleSystems.node = node;
            if node ~= nil then
                local wheelParticleSystem = {};
                wheelParticleSystem.particleSystems = {};
                Utils.loadParticleSystem(xmlFile, wheelParticleSystem.particleSystems, "vehicle.wheelParticleSystems", node, false, nil, self.baseDirectory);
                table.insert(self.wheelParticleSystems, wheelParticleSystem);
            end;
            i = i+1;
        end;
    end;
	
	-------------	
		-- desplazamiento de conjuntos
	self.setHydraulicDirection = SpecializationUtil.callSpecializationsFunction("setHydraulicDirection");
	
	local hydraulicsCount = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.hydraulics#count"), 0);	
	self.hydraulics = {};	
	for i=1, hydraulicsCount do
		local hydraulicName = string.format("vehicle.hydraulics.hydraulic%d", i);		
		self.hydraulics[i] = {};		
		self.hydraulics[i].node = Utils.indexToObject(self.components, getXMLString(xmlFile, hydraulicName .. "#index"));
		self.hydraulics[i].punch = Utils.indexToObject(self.components, getXMLString(xmlFile, hydraulicName .. "#punch"));
		self.hydraulics[i].translationPunch = Utils.indexToObject(self.components, getXMLString(xmlFile, hydraulicName .. "#punchFixpoint"));
		self.hydraulics[i].fixPoint = Utils.indexToObject(self.components, getXMLString(xmlFile, hydraulicName .. "#fixpoint"));	
		local ax, ay, az;		
		if self.hydraulics[i].punch ~= nil then
			ax, ay, az = getWorldTranslation(self.hydraulics[i].punch);
		else
			ax, ay, az = getWorldTranslation(self.hydraulics[i].node);
		end;
		local bx, by, bz = getWorldTranslation(self.hydraulics[i].translationPunch);		
		self.hydraulics[i].punchDistance = Utils.vector3Length(ax-bx, ay-by, az-bz);
		self.hydraulics[i].doScale = Utils.getNoNil(getXMLBool(xmlFile, hydraulicName .. "#doScale"), false);
	end;
	-------------------
	--revoluciones tractor
		self.lowerRmp = SpecializationUtil.callSpecializationsFunction("lowerRmp");
		-- animacion
	self.anim = SpecializationUtil.callSpecializationsFunction("anim");
	self.Go = {}; 
	self.Done = {};
	self.charId = {};
	self.clipIndex = {};
	self.CheckDone = {};
	self.animParts = {}
	self.Activated = {};
	------
	self.startpoint = {};
	self.loopCheck = {};
	self.Speed = {};
	
	
	local count = getXMLInt(xmlFile, "vehicle.animParts#count");
	local part = self.animParts;
    for i=1, count do
		part[i] = {};
		local partname = string.format("vehicle.animParts.part".."%d", i);
	    local nameR = getXMLString(xmlFile, partname.."#name");
		self.charId[nameR] = Utils.indexToObject(self.components, getXMLString(xmlFile, partname.."#rootNode"));
		self.clipIndex[nameR] = getXMLString(xmlFile, partname.."#animationClip");
		self.CheckDone[nameR] = false;
		self.Activated[nameR] = false;
		-----
		self.startpoint[nameR] = Utils.getNoNil(getXMLFloat(xmlFile, partname.."#startpoint"),0.0);
		local charId = getAnimCharacterSet(self.charId[nameR]);
		local clipIndex = getAnimClipIndex(charId, self.clipIndex[nameR]);
		assignAnimTrackClip(charId , 0, clipIndex);
		setAnimTrackTime(charId, 0, self.startpoint[nameR]);
		enableAnimTrack(charId, 0);
		disableAnimTrack(charId, 0);
		self.loopCheck[nameR] = false;
		self.Speed[nameR] = 1.0;
		
		
		
	end; 	
	
	self.AllActivated = SpecializationUtil.callSpecializationsFunction("AllActivated");
	------
		--------------------------
	local translationNode1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.translation1#index"));
    if translationNode1 ~= nil then
        self.translation1 = {};
        self.translation1.node = translationNode1;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.translation1#minTrans"));
        self.translation1.minTrans = {};
        self.translation1.minTrans[1] = Utils.getNoNil(x, 0);
        self.translation1.minTrans[2] = Utils.getNoNil(y, 0);
        self.translation1.minTrans[3] = Utils.getNoNil(z, 0);

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.translation1#maxTrans"));
        self.translation1.maxTrans = {};
        self.translation1.maxTrans[1] = Utils.getNoNil(x, 0);
        self.translation1.maxTrans[2] = Utils.getNoNil(y, 0);
        self.translation1.maxTrans[3] = Utils.getNoNil(z, 0);

	    self.translation1.transTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translation1#transTime"), 2)*1000;
      
    end;
	local rotationNode1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotation1#index"));
    if rotationNode1 ~= nil then
        self.rotation1 = {};
        self.rotation1.node = rotationNode1;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotation1#minRot"));
        self.rotation1.minRot = {};
        self.rotation1.minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotation1.minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotation1.minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotation1#maxRot"));
        self.rotation1.maxRot = {};
        self.rotation1.maxRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotation1.maxRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotation1.maxRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        self.rotation1.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotation1#rotTime"), 2)*1000;
     
    end;
	 local rotationNode2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotation2#index"));
    if rotationNode2 ~= nil then
        self.rotation2 = {};
        self.rotation2.node = rotationNode2;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotation2#minRot"));
        self.rotation2.minRot = {};
        self.rotation2.minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotation2.minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotation2.minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotation2#maxRot"));
        self.rotation2.maxRot = {};
        self.rotation2.maxRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotation2.maxRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotation2.maxRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

         self.rotation2.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotation2#rotTime"), 2)*1000;
      
    end;
	    local numRotParts = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.RotParts#count"), 0);
    self.RotParts = {};
    for i=1, numRotParts do
      local partnamei = string.format("vehicle.RotParts.part" .. "%d", i);
      self.RotParts[i] = {};
      self.RotParts[i].index = Utils.indexToObject(self.components, getXMLString(xmlFile, partnamei .. "#index"));
      local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, partnamei .. "#minRot"));
      self.RotParts[i].minRot = {};
      self.RotParts[i].minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
      self.RotParts[i].minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
      self.RotParts[i].minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));
      x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, partnamei .. "#maxRot"));
      self.RotParts[i].maxRot = {};
      self.RotParts[i].maxRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
      self.RotParts[i].maxRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
      self.RotParts[i].maxRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));
      self.RotParts[i].rotTime = Utils.getNoNil(getXMLString(xmlFile,  partnamei .. "#rotSpeed"), 2)*1000;
    end;
	self.rotParts = false;
	
	 self.keys = {};
    local i=0;
    while true do
        local baseName = string.format("vehicle.keys.input(%d)", i);
        local inputName = getXMLString(xmlFile, baseName.. "#name");
        if inputName == nil then
            break;
        end;
        local inputKey = getXMLString(xmlFile, baseName.. "#key");
        if Input[inputKey] == nil then
            print("Error: invalid key '" .. inputKey .. "'  for input event '" .. inputName .. "'");
            break;
        end;
        self.keys[inputName] = Input[inputKey];
        i = i+1;
    end;
	
			-------------------------
				---- particulas
	self.groundParticleSystems = {};
    local groundParticleSystemCount = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.groundParticleSystems#count"), 0);
    for i=1, groundParticleSystemCount do
        local namei = string.format("vehicle.groundParticleSystems.part%d", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
        Utils.loadParticleSystem(xmlFile, self.groundParticleSystems, namei, nodei, false, nil, self.baseDirectory)	
		Utils.setEmittingState(self.groundParticleSystems,false)
		self.groundParticleSystemsdisableTime = 0;		
    end;
	-------------------------
	local numCuttingAreas = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.cuttingAreas#count"), 0);
    for i=1, numCuttingAreas do
        local areanamei = string.format("vehicle.cuttingAreas.cuttingArea%d", i);
        self.cuttingAreas[i].groundthreshold = Utils.getNoNil(getXMLFloat(xmlFile, areanamei .. "#groundthreshold"), 0.2);
        self.cuttingAreas[i].groundindex = Utils.indexToObject(self.components, getXMLString(xmlFile, areanamei .. "#groundindex"));
    end;
	
	
		-------------------------
    local workSound = getXMLString(xmlFile, "vehicle.workSound#file");
    if workSound ~= nil and workSound ~= "" then
        workSound = Utils.getFilename(workSound, self.baseDirectory); 
        self.workSound = createSample("workSound");
        self.workSoundEnabled = false;
        loadSample(self.workSound, workSound, false);
        self.workSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.workSound#pitchOffset"), 1);
        self.workSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.workSound#volume"), 1);
    end;

	-------------------------
		--------------
	local sound1 = getXMLString(xmlFile, "vehicle.sound1#file");
    if sound1 ~= nil and sound1 ~= "" then
        sound1 = Utils.getFilename(sound1, self.baseDirectory); 
        self.sound1 = createSample("sound1");
        self.sound1Enabled = false;
        loadSample(self.sound1, sound1, false);
        self.sound1PitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.sound1#pitchOffset"), 1);
        self.sound1Volume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.sound1#volume"), 1);
    end;
	
	----------
	local sound2 = getXMLString(xmlFile, "vehicle.sound2#file");
    if sound2 ~= nil and sound2 ~= "" then
        sound2 = Utils.getFilename(sound2, self.baseDirectory); 
        self.sound2 = createSample("sound2");
        self.sound2Enabled = false;
        loadSample(self.sound2, sound2, false);
        self.sound2PitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.sound2#pitchOffset"), 1);
        self.sound2Volume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.sound2#volume"), 1);
    end;
	
	
	 ---------flashlights
	self.FlashLightLeft = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.indexl#index"));
    self.FlashLightRight = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.indexr#index"));	 
	
    self.flashLightLeftActive = false;
    self.flashLightRightActive = false;
    self.flash = false;
    self.flashRight = false;
    self.flashLeft = false;
    self.delayOnLeft = 0;
    self.delayOffLeft = 0;
    self.delayOnRight = 0;
    self.delayOffRight = 0;
    self.delayOn = 0;
    self.delayOff = 0;
   
    turnSoundFile = Utils.getFilename("turn.wav", self.baseDirectory);
    self.turnSoundId = createSample("turnSound");
    loadSample(self.turnSoundId, turnSoundFile, false);
	
	
	------------------
		---discs amd kompaktors
		
	self.numWheelLeft = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.wheelLeft#count"), 0); 
	self.wheelLeft = {}; 
 for i=1, self.numWheelLeft do 
     local partnamei = string.format("vehicle.wheelLeft.part" .. "%d", i); 
     self.wheelLeft[i] = {}; 
     self.wheelLeft[i].index = Utils.indexToObject(self.components, getXMLString(xmlFile, partnamei.."#index")); 
   
 end;
	self.numWheelRight = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.wheelRight#count"), 0); 
	self.wheelRight = {}; 
 for i=1, self.numWheelRight do 
     local partnamei = string.format("vehicle.wheelRight.part" .. "%d", i); 
     self.wheelRight[i] = {}; 
     self.wheelRight[i].index = Utils.indexToObject(self.components, getXMLString(xmlFile, partnamei.."#index")); 
   
 end;
	----------------------------------
		---libertad bloques
	self.setJointRotLimit = SpecializationUtil.callSpecializationsFunction("setJointRotLimit");
	self.firstDo = {};
	self.arm = {};
	
	------------------------------
	 self.rundumleuchtenAnz = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.rundumleuchten#count"),0);
    self.rundumleuchtenAn = false;
    self.rundumleuchten = {};
    for i=1, self.rundumleuchtenAnz do
        local objname = string.format("vehicle.rundumleuchten.light" .. "%d",i);
        self.rundumleuchten[i] = {};
        self.rundumleuchten[i].rotNode = Utils.indexToObject(self.components, getXMLString(xmlFile, objname .. "#rotNode"));
        self.rundumleuchten[i].light = Utils.indexToObject(self.components, getXMLString(xmlFile, objname .. "#light"));
        self.rundumleuchten[i].source = Utils.indexToObject(self.components, getXMLString(xmlFile, objname .. "#lightsource"));
        self.rundumleuchten[i].speed = Utils.getNoNil(getXMLInt(xmlFile,  objname .. "#rotSpeed"), 1)/1000;
        self.rundumleuchten[i].emit = Utils.getNoNil(getXMLBool(xmlFile, objname .. "#emitLight"), true);
        if not self.rundumleuchten[i].emit and self.rundumleuchten[i].source ~= nil then
           setVisibility(self.rundumleuchten[i].source, false);
        end;
    end;
	
	-------------------------------------
	self.aiTerrainDetailChannel1 = g_currentMission.sowingChannel; 
	self.aiTerrainDetailChannel2 = g_currentMission.ploughChannel; 
	self.AIon=false;
	self.vehicleType = getXMLString(xmlFile, "vehicle#type");
	self.go=false;
	self.rotation1Max = false;
	self.openFinished=false;
	self.isLowering=false;
	self.rotParts= false;
	self.freeCultivator=false;
	self.isReadyToTransport =true;
	self.free = false;
end;
function Lemken_Gigant:delete()
	if self.workSound ~= nil then
        delete(self.workSound);
    end;
   
 if self.sound1 ~= nil then
        delete(self.sound1);
    end;
if self.sound2 ~= nil then
        delete(self.sound2);
    end;

	
end;
function Lemken_Gigant:mouseEvent(posX, posY, isDown, isUp, button)
end;

function Lemken_Gigant:keyEvent(unicode, sym, modifier, isDown)
 
---flashlights
	
	if isDown and sym == Input.KEY_KP_1 then
		self.flashLeft = not self.flashLeft;
		self.delayOnLeft = 10;
		self.flashRight = false;
		self.flash = false;
		self.flashLightRightActive = false;
	end;

	if isDown and sym == Input.KEY_KP_3 then
		self.flashRight = not self.flashRight;
		self.delayOnRight = 10;
		self.flashLeft = false;
		self.flash = false;
		self.flashLightLeftActive = false;
	end;
	if isDown and sym == Input.KEY_KP_2 then
		self.flash = not self.flash;
		self.flashRight = false;
		self.flashLeft = false;
		self.delayOn = 20;
		self.flashLightRightActive = false;
		self.flashLightLeftActive = false;
	end;
	-----------
	 
end;
function Lemken_Gigant:update(dt)
	if self.Go.Lift ~= nil and self.Done.Lift ~= false then
			self:anim("Lift", false); 
		end;
if self.attacherVehicle then

	if self: getIsActive() then 
	
		if InputBinding.hasEvent (InputBinding.IMPLEMENT_EXTRA) then 
		self.safeMode = not self.safeMode 
		end;
		----beacon----
		if InputBinding.hasEvent(InputBinding.TOGGLE_BEACON_LIGHTS) then
			self.rundumleuchtenAn = not self.rundumleuchtenAn;
			 for i=1, self.rundumleuchtenAnz do
			setVisibility(self.rundumleuchten[i].light, self.rundumleuchtenAn);
			end;
		end;
		
		if self.rundumleuchtenAn then
		 	  for i=1, self.rundumleuchtenAnz do
				
				rotate(self.rundumleuchten[i].rotNode, 0, dt*self.rundumleuchten[i].speed, 0);
			  end;
        end;
		--- flashLights

		if self.FlashLightLeft ~= nil then
				if self.flashLightLeftActive then
					setVisibility(self.FlashLightLeft, self.flashLightLeftActive);
					
			else
					setVisibility(self.FlashLightLeft, self.flashLightLeftActive);
			end;
			end;

		if self.FlashLightRight ~= nil then
				if self.FlashLightRightActive then
					setVisibility(self.FlashLightRight, self.flashLightRightActive);
			else
					setVisibility(self.FlashLightRight, self.flashLightRightActive);
			end;
			end;

		if self.flashLeft then
			if self.delayOnLeft >= -1 then
				self.delayOnLeft = self.delayOnLeft -dt;
			end;
			if not self.flashLightLeftActive then
				if self.delayOnLeft < 0 then
					self.delayOffLeft = 500;
					self.flashLightLeftActive = true;
					playSample(self.turnSoundId, 1, 0.7, 0);
				end;
			end;
			if self.delayOffLeft >= 0 then
				self.delayOffLeft = self.delayOffLeft -dt;
			end;
			if self.flashLightLeftActive then
				if self.delayOffLeft < 0 then
					self.delayOnLeft = 500;
					self.flashLightLeftActive = false;
				end;
			end;
		end;

		if self.flashRight then
			if self.delayOnRight >= 0 then
				self.delayOnRight = self.delayOnRight -dt;
			end;
			if not self.flashLightRightActive then
				if self.delayOnRight < 0 then
					self.delayOffRight = 500;
					self.flashLightRightActive = true;
					playSample(self.turnSoundId, 1, 0.7, 0);
				end;
			end;
			if self.delayOffRight >= 0 then
				self.delayOffRight = self.delayOffRight -dt;
			end;
			if self.flashLightRightActive then
				if self.delayOffRight < 0 then
					self.delayOnRight = 500;
					self.flashLightRightActive = false;
				end;
			end;
		end;

		if self.flash then
		
			if self.delayOn >= 0 then
				self.delayOn = self.delayOn -dt;
			end;
			if not self.flashLightRightActive then
				if self.delayOn < 0 then
					self.delayOff = 500;
					
					self.flashLightRightActive = true;
					self.flashLightLeftActive = true;
					playSample(self.turnSoundId, 1, 0.7, 0);
					
				end;
			end;
			if self.delayOff >= 0 then
				self.delayOff = self.delayOff -dt;
			end;
			if self.flashLightRightActive then
				if self.delayOff < 0 then
					self.delayOn = 500;
				
					self.flashLightLeftActive = false;
					self.flashLightRightActive = false;
				end;
			end;
			else
			
		end;

		if not self.flashLeft and not self.flashRight then
			if not self.flash then
				self.flashLightRightActive = false;
				self.flashLightLeftActive = false;
			end;
		end;
			
		if not self.flash and not self.flashLeft then
			if not self.flashRight then
				self.flashLightRightActive = false;
			end;
		end;

		if not self.flash and not self.flashRight then
			if not self.flashLeft then
				self.flashLightLeftActive = false;
			end;
		end;

	---particulas ruedas

	local dens = 0; local dens1; local dens2; local dens3;
		 local x,y,z = getWorldTranslation(self.wheels[1].repr);
		 local x1,y1,z1 = getWorldTranslation(self.wheels[2].repr);
		 local x2,y2,z2 = getWorldTranslation(self.wheels[3].repr);
		local id = g_currentMission.terrainDetailId;
		local xx, zz, widthX, widthZ, heightX, heightZ = Utils.getXZWidthAndHeight(id, x, z, x1, z1, x2, z2);
		dens1 = getDensityParallelogram(id, xx, zz, widthX, widthZ, heightX, heightZ, g_currentMission.cultivatorChannel, 1);
		dens2 = getDensityParallelogram(id, xx, zz, widthX, widthZ, heightX, heightZ, g_currentMission.sowingChannel, 1);
		dens3 = getDensityParallelogram(id, xx, zz, widthX, widthZ, heightX, heightZ, g_currentMission.ploughChannel, 1);
		if g_currentMission.environment.lastRainScale <= 0.1 and g_currentMission.environment.timeSinceLastRain > 30 then
			dens = dens1+dens2+dens3;
		end;
		if dens > 0 and self.lastSpeed*self.speedDisplayScale*3600 > 4 then
			
			
			for k=1, 3 do
				Utils.setEmittingState(self.wheelParticleSystems[k].particleSystems, self.wheels[k].hasGroundContact);
			end;
		else
			for i=1, table.getn(self.wheelParticleSystems) do
				Utils.setEmittingState(self.wheelParticleSystems[i].particleSystems, false);
			end;
		
		end;
		
		-----------------------------
		if self.time > self.groundParticleSystemsdisableTime then
			   Utils.setEmittingState(self.groundParticleSystems, false);
		end;
		-- self.wasToFast = false;
		self.Speed.Lift= 0.5; 
		
		
		---ai---
		if self.attacherVehicle.isAITractorActivated ~= nil then
			self.AIon = self.attacherVehicle.isAITractorActivated;
			
		end; 
		
	if self.attacherVehicle.isAITractorActivated then				
    	self.attacherVehicle.turnStage3Timeout = 0;
		
			if self.attacherVehicle.turnStage == 0 then
			self.isLowering=true;
			
			else
			self.isLowering=false;
			end;
	else
		
		if self.attacherVehicle.isAITractorActivated ~= nil then
			self.attacherVehicle.turnStage3Timeout = 35000;
		end; 	
	end;

---------ai end----	
	
	------------apertura y cierre-----------------
	
	
		if self.isReadyToTransport then
	
			if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA2) then
			self.isOpen=not self.isOpen;
			end;
		end;	
			if self.isOpen then
			 self.rotation1Max=true
			else
			self.Go.Lift=false;
			self.Done.Lift= true;
			
			end;
			
		
		
		local x, y, z = getRotation(self.rotation1.node);
			if self.isOpen then
				if x < Utils.degToRad(-41)  then	
					self.Go.Lift=true;
					self.Done.Lift= true;
					
			end;
			
			elseif x > Utils.degToRad(-1)  then
			 if not self.Go.Lift and self.go then
				---llamada a especializacion
				self:lowerRmp();
				self.go=false; --- necesaria  para revoluciones tractor
				if self.sound1Enabled then ---desactivar sound1
				stopSample(self.sound1);
				self.sound1Enabled = false;
				end;
			  end;
			end;
			
				
	
		
		if self.rotation1Max then ---activar sound1 apertura
			if not self.backupRmp then
				self.backupRmp = self.attacherVehicle.motor.minRpm;
			end; 			
			if self.attacherVehicle.motor.minRpm >= -500 then
				self.attacherVehicle.motor.minRpm = self.attacherVehicle.motor.minRpm + 500; 
			end; 
			if not self.sound1Enabled  and not self.AIon and self:getIsActiveForSound() then
				setSamplePitch(self.sound1, self.sound1PitchOffset);
				playSample(self.sound1, 0, self.sound1Volume, 0);
				self.sound1Enabled = true;
			end;
		end;		

	if (self.CheckDone["Lift"] == true) and self.Activated["Lift"] == false then
---llamada a especializacion
	self:lowerRmp();
	self.go=true; --- necesaria  para revoluciones tractor
	if self.sound1Enabled then ---desactivar sound1
		stopSample(self.sound1);
		self.sound1Enabled = false;
	end;
	self.openFinished=true;
	
	end;


	
	if not self.Go.Lift  and self.go then
	
			
			
			if not self.backupRmp then
				self.backupRmp = self.attacherVehicle.motor.minRpm;
			end; 			
			if self.attacherVehicle.motor.minRpm >= -500 then
				self.attacherVehicle.motor.minRpm = self.attacherVehicle.motor.minRpm + 500; 
			end; 
			if not self.sound1Enabled  and not self.AIon and self:getIsActiveForSound() then  ---activar sound1 cierre
			setSamplePitch(self.sound1, self.sound1PitchOffset);
			playSample(self.sound1, 0, self.sound1Volume, 0);
			self.sound1Enabled = true;
			end;
	end;
	if (self.CheckDone["Lift"] == false) and self.Activated["Lift"] == true and self.go then
	self.openFinished=false;
	self.rotation1Max=false;
	end;	
	
	
	-----lower ---

		if self.openFinished then
				if InputBinding.hasEvent(InputBinding.LOWER_IMPLEMENT) then
				 self.isLowering = not self.isLowering;
				end;
		end;
		
	if  self.isLowering then
	 self.isReadyToTransport =false;
		self.rotParts= true;
		self.rotation2Max=true;
		if not self.sound2Enabled  and not self.AIon and self:getIsActiveForSound() then  ---activar sound2
				setSamplePitch(self.sound2, self.sound2PitchOffset);
				playSample(self.sound2, 0, self.sound2Volume, 0);
				self.sound2Enabled = true;
				end;
	else
		self.rotParts= false;
		self.rotation2Max=false;
		if not self.sound2Enabled  and not self.AIon and self:getIsActiveForSound() then  ---activar sound2
				setSamplePitch(self.sound2, self.sound2PitchOffset);
				playSample(self.sound2, 0, self.sound2Volume, 0);
				self.sound2Enabled = true;
				end;
	end;
		
	local x, y, z = getRotation(self.rotation2.node);
		
			if x <   Utils.degToRad(1)  then
			
				
				if not self.isLowering  then
				self.isReadyToTransport =true;
					if self.sound2Enabled then ---desactivar sound2
					stopSample(self.sound2);
					self.sound2Enabled = false;
					end;
				end;
			elseif x < Utils.degToRad(60)  then
				self.freeCultivator=false;
			elseif x > Utils.degToRad(82)  then
				self.freeCultivator=true;	
				if  self.isLowering  then
					if self.sound2Enabled then ---desactivar sound2
					stopSample(self.sound2);
					self.sound2Enabled = false;
					end;
				end;
			end;
            ----------areas y particulas--------------
	if self.isLowering then
				local area = 0;	
				for k, cuttingArea in pairs(self.cuttingAreas) do
					local x,y,z = getWorldTranslation(cuttingArea.groundindex);
					local terrainHeight = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, x, 0, z);
					local x1,y1,z1 = getRotation(self.wheels[2].repr);	
					if k==1 and cuttingArea.groundindex ~= nil and terrainHeight+cuttingArea.groundthreshold >= y then
						 for i=1, self.numWheelRight do 
						  setRotation(self.wheelRight[i].index,z1, y1, -x1/2);
						 end;  
					end;
					if k==2 and cuttingArea.groundindex ~= nil and terrainHeight+cuttingArea.groundthreshold >= y then
							 for i=1, self.numWheelLeft do 
								  setRotation(self.wheelLeft[i].index,z1, y1, x1/2);
							 end;  
					end;
					if (k == 1 or  k == 2 )and cuttingArea.groundindex ~= nil and terrainHeight+cuttingArea.groundthreshold >= y then
						local x,y,z = getWorldTranslation(cuttingArea.start);
						local x1,y1,z1 = getWorldTranslation(cuttingArea.width);
						local x2,y2,z2 = getWorldTranslation(cuttingArea.height);
							if self.safeMode then
							Lemken_Gigant.updateSafeArea (x, z, x1, z1, x2, z2) 
							else 
							Utils.updateCultivatorArea (x, z, x1, z1, x2, z2); 
							end;
						local pixelToQm = 2048 / 8192 * 2048 / 8192; -- 8192px are mapped to 2048m
						local qm = area*pixelToQm;
						local ha = qm/10000;
						
						if self.attacherVehicle.lastSpeed*3600 > 3  then
								if g_currentMission.environment.lastRainScale <= 0.1 and g_currentMission.environment.timeSinceLastRain > 30 then
									self.groundParticleSystemsdisableTime = self.time + 40;
									Utils.setEmittingState(self.groundParticleSystems, true)
																
								end;
								if not self.workSoundEnabled and not self.AIon and self:getIsActiveForSound() then
									setSamplePitch(self.workSound, self.workSoundPitchOffset);
									playSample(self.workSound, 0, self.workSoundVolume, 0);
									self.workSoundEnabled = true;
								end;
						elseif self.attacherVehicle.lastSpeed*3600 < 3 then
								Utils.setEmittingState(self.groundParticleSystems, false)
								 if self.workSoundEnabled then
									stopSample(self.workSound);
									self.workSoundEnabled = false;
								end;
						
						
						end;	
					end;
				end;
	else
				Utils.setEmittingState(self.groundParticleSystems, false)
							 if self.workSoundEnabled then
								stopSample(self.workSound);
								self.workSoundEnabled = false;
								end;
	end;






	
		
	end;	
end;
---------------------------------------

	if self.rotation1Max ~= nil then
        local x, y, z = getRotation(self.rotation1.node);
        local rot = {x,y,z};
        local newRot = Utils.getMovedLimitedValues(rot, self.rotation1.maxRot, self.rotation1.minRot, 3, self.rotation1.rotTime, dt, not self.rotation1Max);
        setRotation(self.rotation1.node, unpack(newRot));
    end;
	if self.rotation2Max ~= nil then
        local x, y, z = getRotation(self.rotation2.node);
        local rot = {x,y,z};
        local newRot = Utils.getMovedLimitedValues(rot, self.rotation2.maxRot, self.rotation2.minRot, 3, self.rotation2.rotTime, dt, not self.rotation2Max);
        setRotation(self.rotation2.node, unpack(newRot));
    end;
	
	
if self.translation1Max ~= nil then
					local x, y, z = getTranslation(self.translation1.node);
					local trans = {x,y,z};
					local newTrans = Utils.getMovedLimitedValues(trans, self.translation1.maxTrans, self.translation1.minTrans, 3, self.translation1.transTime, dt, not self.translation1Max);
					setTranslation(self.translation1.node, unpack(newTrans));
				end;


	if self.rotParts ~= nil   then
				for i=1, table.getn(self.RotParts) do
					local rot = {getRotation(self.RotParts[i].index)};
					local newRot = Utils.getMovedLimitedValues(rot, self.RotParts[i].maxRot, self.RotParts[i].minRot, 3, self.RotParts[i].rotTime, dt, not self.rotParts);
					setRotation(self.RotParts[i].index, unpack(newRot));
				end;
				end;


	--- asignacion de libertad ejes de rotacion segun condiciones de emsamblage  0 x, 2 y ,1 z 
		
		
	
	self:setJointRotLimit(self.componentJoints[11],3.8, 0, 1000,self.rotation1Max == false, 0,dt);	
	self:setJointRotLimit(self.componentJoints[9],6, 0, 1000,self.isLowering == false and self.Go.Lift==true, 0,dt);
	
	self:setJointRotLimit(self.componentJoints[12],180, 0, 1000,self.isLowering == false , 1,dt);
	self:setJointRotLimit(self.componentJoints[2],5, 0, 1000,self.freeCultivator == true, 0,dt);
	 self:setJointRotLimit(self.componentJoints[3],5, 0, 1000,self.freeCultivator == true, 2,dt);
	self:setJointRotLimit(self.componentJoints[4],5, 0, 1000,self.freeCultivator == true, 2,dt);
	 self:setJointRotLimit(self.componentJoints[5],5, 0, 1000,self.freeCultivator == true, 2,dt);
	 
	 self:setJointRotLimit(self.componentJoints[6],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[7],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[8],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[13],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[14],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[15],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[16],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[17],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[18],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[19],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[20],10, 0, 1000,self.free == true , 2,dt);
	  self:setJointRotLimit(self.componentJoints[21],10, 0, 1000,self.free == true , 2,dt);
	 
	 
	 
	 
	 
	 
	 
	 
	 
	
	-- juntas

		local joint = self.componentJoints[1];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[2];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[3];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[4];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[5];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[6];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[7];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[8];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[9];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[10];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[11];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[12];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[13];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[14];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[15];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[16];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[17];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[18];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[19];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
			local joint = self.componentJoints[20];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
				local joint = self.componentJoints[21];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
		
		
		
		self:setHydraulicDirection();


end;




function Lemken_Gigant:draw()
if self.attacherVehicle then
if self.safeMode then 
g_currentMission: addHelpButtonText ("switch to normal mode", InputBinding.IMPLEMENT_EXTRA); 
else 
g_currentMission: addHelpButtonText ("switch to safe mode", InputBinding.IMPLEMENT_EXTRA); 
end; 
	if self.rundumleuchtenAn then
			 g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".3"), self.typeDesc), InputBinding.TOGGLE_BEACON_LIGHTS); 
	else
			 g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".2"), self.typeDesc), InputBinding.TOGGLE_BEACON_LIGHTS); 
	end; 
 
	if self.isReadyToTransport then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".1"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA2);
	else
	g_currentMission:addExtraPrintText(" ");
	end;
	if self.openFinished then
	g_currentMission:addHelpButtonText(string.format(g_i18n:getText(self.vehicleType..".4"), self.typeDesc), InputBinding.LOWER_IMPLEMENT);
	else
	g_currentMission:addExtraPrintText(" ");
	end;
end;
end;
function Lemken_Gigant:onAttach()
self.translation1Max = true;
self.free = true;


end;
function Lemken_Gigant:onDetach()
	self.free = false;
	self.translation1Max = false;

    if self.deactivateOnDetach then
        Lemken_Gigant.onDeactivate(self);
    else
        Lemken_Gigant.onDeactivateSounds(self)
    end;


self.flashLightRightActive = false;
self.flashLightLeftActive = false;
setVisibility(self.FlashLightRight, false);
setVisibility(self.FlashLightLeft, false);
 self.rundumleuchtenAn = false;
    for i=1, self.rundumleuchtenAnz do
       setVisibility(self.rundumleuchten[i].light, self.rundumleuchtenAn);
	   
    end;
end;


function Lemken_Gigant:onLeave()

    if self.deactivateOnLeave then
        Lemken_Gigant.onDeactivate(self);
    else
        Lemken_Gigant.onDeactivateSounds(self)
    end;

end;

function Lemken_Gigant:onDeactivate()

    Lemken_Gigant.onDeactivateSounds(self)
   

end;

function Lemken_Gigant:onDeactivateSounds()
 if self.workSoundEnabled then
        stopSample(self.workSound);
        self.workSoundEnabled = false;
    end;
   
	 if self.sound1Enabled then
        stopSample(self.sound1);
        self.sound1Enabled = false;
    end;
	 if self.sound2Enabled then
        stopSample(self.sound2);
        self.sound2Enabled = false;
    end;
			
end;
function Lemken_Gigant:lowerRmp()
	if self.backupRmp and self.attacherVehicle then
		if self.attacherVehicle.motor.minRpm <= self.backupRmp then
			self.attacherVehicle.motor.minRpm = self.attacherVehicle.motor.minRpm -100; 
		else
			self.attacherVehicle.motor.minRpm = self.backupRmp; 
			self.backupRmp = nil; 			
		end; 	
	end; 
end;
Lemken_Gigant.updateSafeArea = function(l_18_0, l_18_1, l_18_2, l_18_3, l_18_4, l_18_5)
  local cultiId = g_currentMission.cultivatorChannel
  local sowingId = g_currentMission.sowingChannel
  local detailId = g_currentMission.terrainDetailId
  local ploughId = g_currentMission.ploughChannel
  local sprayId = g_currentMission.sprayChannel
  local x, z, widthX, widthZ, heightX, heightZ = Utils.getXZWidthAndHeight(detailId, l_18_0, l_18_1, l_18_2, l_18_3, l_18_4, l_18_5)
  Utils.updateDestroyCommonArea(l_18_0, l_18_1, l_18_2, l_18_3, l_18_4, l_18_5)
  setDensityMaskedParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, cultiId, 1, detailId, sowingId, 1, 1)
  setDensityMaskedParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, cultiId, 1, detailId, ploughId, 1, 1)
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, sowingId, 1, 0)
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, ploughId, 1, 0)
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, sprayId, 1, 0)
end;

function Lemken_Gigant:setJointRotLimit(nodei, up, down, speed, value, axle, dt)

	if not self.firstDo[nodei] then
		self.firstDo[nodei] = true;
		self.arm[nodei] = {0}; 
	end; 
	x, y, z = getRotation(nodei);
	rot = {x,y,z};	
	newRotLimit = {}; 
	newRotLimit[nodei] = {0,0,0};
	newRotLimit[nodei] = Utils.getMovedLimitedValues(self.arm[nodei], {down}, {up}, 1, speed * 2, dt, value);
	if math.abs(newRotLimit[nodei][1] - self.arm[nodei][1]) > 0.001 then
		local joint = nodei;
		setJointRotationLimit(joint.jointIndex, axle, true, Utils.degToRad(-newRotLimit[nodei][1]), Utils.degToRad(newRotLimit[nodei][1]));
	end;
	self.arm[nodei] = newRotLimit[nodei];			
end;
function Lemken_Gigant:setHydraulicDirection()
	for i=1, table.getn(self.hydraulics) do
		local ax, ay, az = getWorldTranslation(self.hydraulics[i].node);
		local bx, by, bz = getWorldTranslation(self.hydraulics[i].fixPoint);
		local x, y, z = worldDirectionToLocal(getParent(self.hydraulics[i].node), bx-ax, by-ay, bz-az);
		
		setDirection(self.hydraulics[i].node, x, y, z, 0, 1, 0);
		local distance = Utils.vector3Length(ax-bx, ay-by, az-bz);
		if self.hydraulics[i].doScale then
			local xScale, yScale, zScale = getScale(self.hydraulics[i].node);
			local newScale = yScale * (distance / self.hydraulics[i].punchDistance);
			setScale(self.hydraulics[i].node, 1, 1, newScale);
		else
			if self.hydraulics[i].punch ~= nil then
				setTranslation(self.hydraulics[i].punch, 0, 0, distance-self.hydraulics[i].punchDistance);
			end;
		end;
	
	end;
end;
function Lemken_Gigant:anim(varName, loopCheck)	
	-- print("ANIMATION");
	
	self.Activated[varName] = true;
	local loopCheck = self.loopCheck[varName];
	local speed = Utils.getNoNil(self.Speed[varName],1);
	 
	if self.Go[varName] == true and self.Done[varName] ~= false then
		local charId = getAnimCharacterSet(self.charId[varName]);
		local clipIndex = getAnimClipIndex(charId, self.clipIndex[varName]);
		assignAnimTrackClip(charId , 0, clipIndex);
		setAnimTrackLoopState(charId, 0, loopCheck);
		setAnimTrackSpeedScale(charId, 0, speed);
		enableAnimTrack(charId, 0);
		if getAnimTrackTime(charId, 0) >= getAnimClipDuration(charId, clipIndex) and loopCheck == false then
			disableAnimTrack(charId, 0);	
			self.Done[varName] = false;	
			self.CheckDone[varName] = true;	
			self.Activated[varName] = false;
		
			---final animacion hacia delante
		end; 
	elseif self.Go[varName] == false and self.Done[varName] ~= false then
		local charId = getAnimCharacterSet(self.charId[varName]);
		local clipIndex = getAnimClipIndex(charId, self.clipIndex[varName]);
		if loopCheck == true then
			disableAnimTrack(charId, 0);
			self.Done[varName] = false;	
		end; 	
		assignAnimTrackClip(charId , 0, clipIndex);
		setAnimTrackLoopState(charId, 0, loopCheck);
		setAnimTrackSpeedScale(charId, 0, -speed);
		enableAnimTrack(charId, 0);
		if getAnimTrackTime(charId, 0) <= 0 then
			disableAnimTrack(charId, 0);
			self.Done[varName] = false;	
			self.CheckDone[varName] = false;
			self.Activated[varName] = true;
			---final animacion hacia atras
		
		end;
	end;
end; 


function Lemken_Gigant:AllActivated()
	
	if (self.CheckDone["Lift"] == true) and not self.Activated["Lift"]  then
		return true;
	else
		return false;
	end;
	
	
end;
function Lemken_Gigant:getSaveAttributesAndNodes(nodeIdent)
if (self.CheckDone["Lift"] == true) and self.Activated["Lift"] == false then
					
	Lift = "true";	
else		
	Lift = "false";	
end;		
		

	-- 'name="'..tostring(name)..'" name="'..tonumber(name)..'"';
	 local attributes = 'Lift="'..tostring(Lift)..'"';
	
	return attributes, nil;
end;


function Lemken_Gigant:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
    local Lift = getXMLString(xmlFile, key.."#Lift");
	
	if Lift == "true" and not resetVehicles then
		self.Go.Lift = not self.Go.Lift ; 
		self.Done.Lift = true; 
		self.Speed.Lift = 15.0; 
		self.isOpen=not self.isOpen;
		self.rotation1Max=not self.rotation1Max;
	end; 
	
    return BaseMission.VEHICLE_LOAD_OK;
end;
function key_convert(key)
    if key ~= nil then 
	    local keyname = "";
	    if key > 32 and key < 123 then
	    	keyname = string.upper(string.char(key));
	    elseif key > 255 and key < 266 then
	    	keyname = "NUM "..string.char(key-208);
	    else 
	    	keyname = "";
	    end;
	    return(keyname);
	  end;
end;