Hi fellow wiki editors!

To help newly registered users get more familiar with the wiki (and maybe older users too) there is now a {{Welcome to the wiki}} template. Have a look at it and feel free to add it to new users discussion pages (and perhaps your own).

I have tried to keep the template short, but meaningful. /Johan G

Difference between revisions of "Crash and stress damage system"

From FlightGear wiki
Jump to: navigation, search
(How to install the current system on an aircraft: Updated to new version.)
(How to install the current system on an aircraft: Updated for better performance.)
Line 24: Line 24:
 
#
 
#
 
#
 
#
# Version 0.16
+
# Version 0.18
 
#
 
#
 
# License:
 
# License:
Line 169: Line 169:
 
    }
 
    }
  
    var prop = me.fdm.wingsFailureID;
+
    me.prop = me.fdm.wingsFailureID;
    var actuator_wings = set_unserviceable_cascading(prop, modes);
+
    me.actuator_wings = set_unserviceable_cascading(me.prop, modes);
    FailureMgr.add_failure_mode(prop, "Main wings", actuator_wings);
+
    FailureMgr.add_failure_mode(me.prop, "Main wings", me.actuator_wings);
 
},
 
},
 
# set the stresslimit for the main wings
 
# set the stresslimit for the main wings
 
setStressLimit: func (stressLimit = nil) {
 
setStressLimit: func (stressLimit = nil) {
 
if (stressLimit != nil) {
 
if (stressLimit != nil) {
var wingloadMax = stressLimit['wingloadMaxLbs'];
+
me.wingloadMax = stressLimit['wingloadMaxLbs'];
var wingloadMin = stressLimit['wingloadMinLbs'];
+
me.wingloadMin = stressLimit['wingloadMinLbs'];
var maxG = stressLimit['maxG'];
+
me.maxG = stressLimit['maxG'];
var minG = stressLimit['minG'];
+
me.minG = stressLimit['minG'];
var weight = stressLimit['weightLbs'];
+
me.weight = stressLimit['weightLbs'];
if(wingloadMax != nil) {
+
if(me.wingloadMax != nil) {
me.wingLoadLimitUpper = wingloadMax;
+
me.wingLoadLimitUpper = me.wingloadMax;
} elsif (maxG != nil and weight != nil) {
+
} elsif (me.maxG != nil and me.weight != nil) {
me.wingLoadLimitUpper = maxG * weight;
+
me.wingLoadLimitUpper = me.maxG * me.weight;
 
}
 
}
  
if(wingloadMin != nil) {
+
if(me.wingloadMin != nil) {
me.wingLoadLimitLower = wingloadMin;
+
me.wingLoadLimitLower = me.wingloadMin;
} elsif (minG != nil and weight != nil) {
+
} elsif (me.minG != nil and me.weight != nil) {
me.wingLoadLimitLower = minG * weight;
+
me.wingLoadLimitLower = me.minG * me.weight;
 
} elsif (me.wingLoadLimitUpper != nil) {
 
} elsif (me.wingLoadLimitUpper != nil) {
 
me.wingLoadLimitLower = -me.wingLoadLimitUpper * 0.4;#estimate for when lower is not specified
 
me.wingLoadLimitLower = -me.wingLoadLimitUpper * 0.4;#estimate for when lower is not specified
Line 201: Line 201:
 
# repair the aircaft
 
# repair the aircaft
 
repair: func () {
 
repair: func () {
var failure_modes = FailureMgr._failmgr.failure_modes;
+
me.failure_modes = FailureMgr._failmgr.failure_modes;
var mode_list = keys(failure_modes);
+
me.mode_list = keys(me.failure_modes);
  
foreach(var failure_mode_id; mode_list) {
+
foreach(var failure_mode_id; me.mode_list) {
 
FailureMgr.set_failure_level(failure_mode_id, 0);
 
FailureMgr.set_failure_level(failure_mode_id, 0);
 
}
 
}
Line 228: Line 228:
 
},
 
},
 
_identifyGears: func (gears) {
 
_identifyGears: func (gears) {
var contacts = props.globals.getNode("/gear").getChildren("gear");
+
me.contacts = props.globals.getNode("/gear").getChildren("gear");
  
foreach(var contact; contacts) {
+
foreach(var contact; me.contacts) {
var index = contact.getIndex();
+
me.index = contact.getIndex();
var isGear = me._contains(gears, index);
+
me.isGear = me._contains(gears, me.index);
var wow = contact.getChild("wow");
+
me.wow = contact.getChild("wow");
if (isGear == TRUE) {
+
if (me.isGear == TRUE) {
append(me.wowGear, wow);
+
append(me.wowGear, me.wow);
 
} else {
 
} else {
append(me.wowStructure, wow);
+
append(me.wowStructure, me.wow);
 
}
 
}
 
}
 
}
Line 275: Line 275:
 
return FALSE;
 
return FALSE;
 
}
 
}
var time = me.fdm.input.simTime.getValue();
+
me.time = me.fdm.input.simTime.getValue();
if (time != nil and time > 1) {
+
if (me.time != nil and me.time > 1) {
 
return TRUE;
 
return TRUE;
 
}
 
}
Line 282: Line 282:
 
},
 
},
 
_calcGroundSpeed: func () {
 
_calcGroundSpeed: func () {
   var realSpeed = me.fdm.getSpeedRelGround();
+
   me.realSpeed = me.fdm.getSpeedRelGround();
  
   return realSpeed;
+
   return me.realSpeed;
 
},
 
},
 
_impactDamage: func () {
 
_impactDamage: func () {
    var lat = me.input.lat.getValue();
+
    me.lat = me.input.lat.getValue();
var lon = me.input.lon.getValue();
+
me.lon = me.input.lon.getValue();
var info = geodinfo(lat, lon);
+
me.info = geodinfo(me.lat, me.lon);
var solid = info == nil?TRUE:(info[1] == nil?TRUE:info[1].solid);
+
me.solid = me.info == nil?TRUE:(me.info[1] == nil?TRUE:me.info[1].solid);
var speed = me._calcGroundSpeed();
+
me.speed = me._calcGroundSpeed();
  
 
if (me.exploded == FALSE) {
 
if (me.exploded == FALSE) {
var failure_modes = FailureMgr._failmgr.failure_modes;
+
me.failure_modes = FailureMgr._failmgr.failure_modes;
    var mode_list = keys(failure_modes);
+
    me.mode_list = keys(me.failure_modes);
    var probability = (speed * speed) / 40000.0;# 200kt will fail everything, 0kt will fail nothing.
+
    me.probability = (me.speed * me.speed) / 40000.0;# 200kt will fail everything, 0kt will fail nothing.
 
     
 
     
    var hitStr = "something";
+
    me.hitStr = "something";
    if(info != nil and info[1] != nil) {
+
    if(me.info != nil and me.info[1] != nil) {
    hitStr = info[1].names == nil?"something":info[1].names[0];
+
    me.hitStr = me.info[1].names == nil?"something":me.info[1].names[0];
    foreach(infoStr; info[1].names) {
+
    foreach(infoStr; me.info[1].names) {
 
    if(find('_', infoStr) == -1) {
 
    if(find('_', infoStr) == -1) {
    hitStr = infoStr;
+
    me.hitStr = infoStr;
 
    break;
 
    break;
 
    }
 
    }
Line 309: Line 309:
 
}
 
}
 
    # test for explosion
 
    # test for explosion
    if(probability > 0.766 and me.fdm.input.fuel.getValue() > 2500) {
+
    if(me.probability > 0.766 and me.fdm.input.fuel.getValue() > 2500) {
 
    # 175kt+ and fuel in tanks will explode the aircraft on impact.
 
    # 175kt+ and fuel in tanks will explode the aircraft on impact.
 
    me.input.simCrashed.setBoolValue(TRUE);
 
    me.input.simCrashed.setBoolValue(TRUE);
    me._explodeBegin("Aircraft hit "~hitStr~".");
+
    me._explodeBegin("Aircraft hit "~me.hitStr~".");
 
    return;
 
    return;
 
    }
 
    }
  
    foreach(var failure_mode_id; mode_list) {
+
    foreach(var failure_mode_id; me.mode_list) {
    if(rand() < probability) {
+
    if(rand() < me.probability) {
 
      FailureMgr.set_failure_level(failure_mode_id, 1);
 
      FailureMgr.set_failure_level(failure_mode_id, 1);
 
      }
 
      }
 
    }
 
    }
  
var str = "Aircraft hit "~hitStr~".";
+
me.str = "Aircraft hit "~me.hitStr~".";
me._output(str);
+
me._output(me.str);
} elsif (solid == TRUE) {
+
} elsif (me.solid == TRUE) {
 
# The aircraft is burning and will ignite the ground
 
# The aircraft is burning and will ignite the ground
 
if(me.input.wildfire.getValue() == TRUE) {
 
if(me.input.wildfire.getValue() == TRUE) {
var pos= geo.Coord.new().set_latlon(lat, lon);
+
me.pos= geo.Coord.new().set_latlon(me.lat, me.lon);
wildfire.ignite(pos, 1);
+
wildfire.ignite(me.pos, 1);
 
}
 
}
 
}
 
}
if(solid == TRUE) {
+
if(me.solid == TRUE) {
me._impactSoundBegin(speed);
+
me._impactSoundBegin(me.speed);
 
} else {
 
} else {
me._impactSoundWaterBegin(speed);
+
me._impactSoundWaterBegin(me.speed);
 
}
 
}
 
},
 
},
Line 358: Line 358:
 
me.input.explodeOn.setBoolValue(TRUE);
 
me.input.explodeOn.setBoolValue(TRUE);
 
me.exploded = TRUE;
 
me.exploded = TRUE;
var failure_modes = FailureMgr._failmgr.failure_modes;
+
me.failure_modes = FailureMgr._failmgr.failure_modes;
    var mode_list = keys(failure_modes);
+
    me.mode_list = keys(me.failure_modes);
  
    foreach(var failure_mode_id; mode_list) {
+
    foreach(var failure_mode_id; me.mode_list) {
 
       FailureMgr.set_failure_level(failure_mode_id, 1);
 
       FailureMgr.set_failure_level(failure_mode_id, 1);
 
    }
 
    }
Line 386: Line 386:
 
},
 
},
 
_output: func (str, override = FALSE) {
 
_output: func (str, override = FALSE) {
var time = me.fdm.input.simTime.getValue();
+
me.time = me.fdm.input.simTime.getValue();
if (override == TRUE or (time - me.lastMessageTime) > 3) {
+
if (override == TRUE or (me.time - me.lastMessageTime) > 3) {
me.lastMessageTime = time;
+
me.lastMessageTime = me.time;
 
print(str);
 
print(str);
 
screen.log.write(str, 0.7098, 0.5372, 0.0);# solarized yellow
 
screen.log.write(str, 0.7098, 0.5372, 0.0);# solarized yellow
Line 399: Line 399:
 
_testWaterImpact: func () {
 
_testWaterImpact: func () {
 
if(me.input.altAgl.getValue() < 0) {
 
if(me.input.altAgl.getValue() < 0) {
var lat = me.input.lat.getValue();
+
me.lat = me.input.lat.getValue();
var lon = me.input.lon.getValue();
+
me.lon = me.input.lon.getValue();
var info = geodinfo(lat, lon);
+
me.info = geodinfo(me.lat, me.lon);
var solid = info==nil?TRUE:(info[1] == nil?TRUE:info[1].solid);
+
me.solid = me.info==nil?TRUE:(me.info[1] == nil?TRUE:me.info[1].solid);
if(solid == FALSE) {
+
if(me.solid == FALSE) {
 
me._impactDamage();
 
me._impactDamage();
 
}
 
}
Line 410: Line 410:
 
_testStress: func () {
 
_testStress: func () {
 
if (me._isRunning() == TRUE and me.wingsAttached == TRUE) {
 
if (me._isRunning() == TRUE and me.wingsAttached == TRUE) {
var gForce = me.fdm.input.Nz.getValue() == nil?1:me.fdm.input.Nz.getValue();
+
me.gForce = me.fdm.input.Nz.getValue() == nil?1:me.fdm.input.Nz.getValue();
var weight = me.fdm.input.weight.getValue();
+
me.weight = me.fdm.input.weight.getValue();
var wingload = gForce * weight;
+
me.wingload = me.gForce * me.weight;
  
var broken = FALSE;
+
me.broken = FALSE;
  
if(wingload < 0) {
+
if(me.wingload < 0) {
broken = me._testWingload(-wingload, -me.wingLoadLimitLower);
+
me.broken = me._testWingload(-me.wingload, -me.wingLoadLimitLower);
if(broken == TRUE) {
+
if(me.broken == TRUE) {
 
me._stressDamage("negative");
 
me._stressDamage("negative");
 
}
 
}
 
} else {
 
} else {
broken = me._testWingload(wingload, me.wingLoadLimitUpper);
+
me.broken = me._testWingload(me.wingload, me.wingLoadLimitUpper);
if(broken == TRUE) {
+
if(me.broken == TRUE) {
 
me._stressDamage("positive");
 
me._stressDamage("positive");
 
}
 
}
Line 433: Line 433:
 
}
 
}
 
},
 
},
_testWingload: func (wingload, wingLoadLimit) {
+
_testWingload: func (wingloadCurr, wingLoadLimit) {
if (wingload > (wingLoadLimit * 0.5)) {
+
if (wingloadCurr > (wingLoadLimit * 0.5)) {
 
#me.input.trembleOn.setValue(1);
 
#me.input.trembleOn.setValue(1);
var tremble_max = math.sqrt((wingload - (wingLoadLimit * 0.5)) / (wingLoadLimit * 0.5));
+
me.tremble_max = math.sqrt((wingloadCurr - (wingLoadLimit * 0.5)) / (wingLoadLimit * 0.5));
 
#me.input.trembleMax.setDoubleValue(1);
 
#me.input.trembleMax.setDoubleValue(1);
  
if (wingload > (wingLoadLimit * 0.75)) {
+
if (wingloadCurr > (wingLoadLimit * 0.75)) {
  
#tremble_max = math.sqrt((wingload - (wingLoadLimit * 0.5)) / (wingLoadLimit * 0.5));
+
#me.tremble_max = math.sqrt((wingloadCurr - (wingLoadLimit * 0.5)) / (wingLoadLimit * 0.5));
me.input.creakVol.setDoubleValue(tremble_max);
+
me.input.creakVol.setDoubleValue(me.tremble_max);
 
me.input.creakOn.setBoolValue(TRUE);
 
me.input.creakOn.setBoolValue(TRUE);
  
if (wingload > (wingLoadLimit * 0.90)) {
+
if (wingloadCurr > (wingLoadLimit * 0.90)) {
 
me.input.crackOn.setBoolValue(TRUE);
 
me.input.crackOn.setBoolValue(TRUE);
me.input.crackVol.setDoubleValue(tremble_max);
+
me.input.crackVol.setDoubleValue(me.tremble_max);
if (wingload > wingLoadLimit) {
+
if (wingloadCurr > wingLoadLimit) {
 
me.input.crackVol.setDoubleValue(1);
 
me.input.crackVol.setDoubleValue(1);
 
me.input.creakVol.setDoubleValue(1);
 
me.input.creakVol.setDoubleValue(1);
Line 492: Line 492:
 
},
 
},
 
fps2kt: func (fps) {
 
fps2kt: func (fps) {
return fps * 0.5924838;
+
return fps * FPS2KT;
 
},
 
},
 
getSpeedRelGround: func () {
 
getSpeedRelGround: func () {
Line 506: Line 506:
 
fuel:      "fdm/jsbsim/propulsion/total-fuel-lbs",
 
fuel:      "fdm/jsbsim/propulsion/total-fuel-lbs",
 
simTime:    "fdm/jsbsim/simulation/sim-time-sec",
 
simTime:    "fdm/jsbsim/simulation/sim-time-sec",
vgFps:     "fdm/jsbsim/velocities/vg-fps",
+
northFps:   "velocities/speed-north-fps",
downFps:    "fdm/jsbsim/velocities/v-down-fps",
+
eastFps:    "velocities/speed-east-fps",
 +
downFps:    "velocities/speed-down-fps",
 
Nz:        "fdm/jsbsim/accelerations/Nz",
 
Nz:        "fdm/jsbsim/accelerations/Nz",
 
},
 
},
 
getSpeedRelGround: func () {
 
getSpeedRelGround: func () {
var horzSpeed = me.fps2kt(me.input.vgFps.getValue());
+
me.northSpeed = me.input.northFps.getValue();
  var vertSpeed = me.fps2kt(me.input.downFps.getValue());
+
me.eastSpeed  = me.input.eastFps.getValue();
   var realSpeed = math.sqrt((horzSpeed * horzSpeed) + (vertSpeed * vertSpeed));
+
me.horzSpeed  = math.sqrt((me.eastSpeed * me.eastSpeed) + (me.northSpeed * me.northSpeed));
 +
  me.vertSpeed  = me.input.downFps.getValue();
 +
   me.realSpeed = me.fps2kt(math.sqrt((me.horzSpeed * me.horzSpeed) + (me.vertSpeed * me.vertSpeed)));
  
   return realSpeed;
+
   return me.realSpeed;
 
},
 
},
 
wingsFailureID: "fdm/jsbsim/structural/wings",
 
wingsFailureID: "fdm/jsbsim/structural/wings",
Line 526: Line 529:
 
fuel:      "consumables/fuel/total-fuel-lbs",
 
fuel:      "consumables/fuel/total-fuel-lbs",
 
simTime:    "sim/time/elapsed-sec",
 
simTime:    "sim/time/elapsed-sec",
vgFps:     "velocities/groundspeed-kt",
+
northFps:   "velocities/speed-north-fps",
 +
eastFps:    "velocities/speed-east-fps",
 
downFps:    "velocities/speed-down-fps",
 
downFps:    "velocities/speed-down-fps",
 
Nz:        "accelerations/n-z-cg-fps_sec",
 
Nz:        "accelerations/n-z-cg-fps_sec",
 
},
 
},
 
getSpeedRelGround: func () {
 
getSpeedRelGround: func () {
var horzSpeed = me.input.vgFps.getValue();
+
me.northSpeed = me.input.northFps.getValue();
  var vertSpeed = me.fps2kt(me.input.downFps.getValue());
+
me.eastSpeed  = me.input.eastFps.getValue();
   var realSpeed = math.sqrt((horzSpeed * horzSpeed) + (vertSpeed * vertSpeed));
+
me.horzSpeed  = math.sqrt((me.eastSpeed * me.eastSpeed) + (me.northSpeed * me.northSpeed));
 +
  me.vertSpeed  = me.input.downFps.getValue();
 +
   me.realSpeed = me.fps2kt(math.sqrt((me.horzSpeed * me.horzSpeed) + (me.vertSpeed * me.vertSpeed)));
  
   return realSpeed;
+
   return me.realSpeed;
 
},
 
},
 
wingsFailureID: "structural/wings",
 
wingsFailureID: "structural/wings",
Line 553: Line 559:
 
# example uses:
 
# example uses:
 
#
 
#
# var crashCode = CrashAndStress.new([0,1,2];  
+
# var crashCode = CrashAndStress.new([0,1,2]);  
 
#
 
#
 
# var crashCode = CrashAndStress.new([0,1,2], {"weightLbs":30000, "maxG": 12});
 
# var crashCode = CrashAndStress.new([0,1,2], {"weightLbs":30000, "maxG": 12});

Revision as of 01:43, 23 September 2017

Inspired and developed from the crash system in the MiG-15 by Slavutinsky Victor, this system is meant to become generic and usable for all aircraft by adding just a few lines. For now you have to add a file with code though.

Features so far

  • Impact, crash and explosion detection.
  • Tied into the new 3.5+ failure manager.
  • Over-G detection for wing stress.
  • Sounds.

Planned features

Feel free to suggest some in the forum topic linked to at the end of this article.

Background

The crash system in the Mig15 also have detection of flying into trees and buildings. That detection is based on random calculation of the chance of hitting something, meaning it will hit trees or building that is not seen in the 3D rendered landscape. I decided that could be confusing for many users, and also it had a big performance hit, therefore that is not a feature present in this system.

How to install the current system on an aircraft

Copy this code into your aircraft's Nasal folder as crash-and-stress.nas file:

#
# A Flightgear crash and stress damage system.
#
# Inspired and developed from the crash system in Mig15 by Slavutinsky Victor. And by Hvengel's formula for wingload stress.
#
# Authors: Slavutinsky Victor, Nikolai V. Chr. (Necolatis)
#
#
# Version 0.18
#
# License:
#   GPL 2.0


var TRUE = 1;
var FALSE = 0;

var CrashAndStress = {
	# pattern singleton
	_instance: nil,
	# Get the instance
	new: func (gears, stressLimit = nil, wingsFailureModes = nil) {

		var m = nil;
		if(me._instance == nil) {
			me._instance = {};
			me._instance["parents"] = [CrashAndStress];

			m = me._instance;

			m.inService = FALSE;
			m.repairing = FALSE;

			m.exploded = FALSE;

			m.wingsAttached = TRUE;
			m.wingLoadLimitUpper = nil;
			m.wingLoadLimitLower = nil;
			m._looptimer = maketimer(0, m, m._loop);

			m.repairTimer = maketimer(10.0, m, CrashAndStress._finishRepair);
			m.repairTimer.singleShot = 1;

			m.soundWaterTimer = maketimer(3, m, CrashAndStress._impactSoundWaterEnd);
			m.soundWaterTimer.singleShot = 1;

			m.soundTimer = maketimer(3, m, CrashAndStress._impactSoundEnd);
			m.soundTimer.singleShot = 1;

			m.explodeTimer = maketimer(3, m, CrashAndStress._explodeEnd);
			m.explodeTimer.singleShot = 1;

			m.stressTimer = maketimer(3, m, CrashAndStress._stressDamageEnd);
			m.stressTimer.singleShot = 1;

			m.input = {
			#	trembleOn:  "damage/g-tremble-on",
			#	trembleMax: "damage/g-tremble-max",				
				replay:     "sim/replay/replay-state",
				lat:        "position/latitude-deg",
				lon:        "position/longitude-deg",
				alt:        "position/altitude-ft",
				altAgl:     "position/altitude-agl-ft",
				elev:       "position/ground-elev-ft",
	  			crackOn:    "damage/sounds/crack-on",
				creakOn:    "damage/sounds/creaking-on",
				crackVol:   "damage/sounds/crack-volume",
				creakVol:   "damage/sounds/creaking-volume",
				wCrashOn:   "damage/sounds/water-crash-on",
				crashOn:    "damage/sounds/crash-on",
				detachOn:   "damage/sounds/detach-on",
				explodeOn:  "damage/sounds/explode-on",
				simCrashed: "sim/crashed",
				wildfire:   "environment/wildfire/fire-on-crash",
			};
			foreach(var ident; keys(m.input)) {
			    m.input[ident] = props.globals.getNode(m.input[ident], 1);
			}

			m.fdm = nil;

			if(getprop("sim/flight-model") == "jsb") {
				m.fdm = jsbSimProp;
			} elsif(getprop("sim/flight-model") == "yasim") {
				m.fdm = yaSimProp;
			} else {
				return nil;
			}
			m.fdm.convert();
			
			m.wowStructure = [];
			m.wowGear = [];

			m.lastMessageTime = 0;

			m._initProperties();
			m._identifyGears(gears);
			m.setStressLimit(stressLimit);
			m.setWingsFailureModes(wingsFailureModes);

			m._startImpactListeners();
		} else {
			m = me._instance;
		}

		return m;
	},
	# start the system
	start: func () {
		me.inService = TRUE;
	},
	# stop the system
	stop: func () {
		me.inService = FALSE;
	},
	# return TRUE if in progress
	isStarted: func () {
		return me.inService;
	},
	# accepts a vector with failure mode IDs, they will fail when wings break off.
	setWingsFailureModes: func (modes) {
		if(modes == nil) {
			modes = [];
		}

		##
	    # Returns an actuator object that will set the serviceable property at
	    # the given node to zero when the level of failure is > 0.
	    # it will also fail additionally failure modes.

	    var set_unserviceable_cascading = func(path, casc_paths) {

	        var prop = path ~ "/serviceable";

	        if (props.globals.getNode(prop) == nil) {
	            props.globals.initNode(prop, TRUE, "BOOL");
	        } else {
	        	props.globals.getNode(prop).setBoolValue(TRUE);#in case this gets initialized empty from a recorder signal or MP alias.
	        }

	        return {
	            parents: [FailureMgr.FailureActuator],
	            mode_paths: casc_paths,
	            set_failure_level: func(level) {
	                setprop(prop, level > 0 ? 0 : 1);
	                foreach(var mode_path ; me.mode_paths) {
	                    FailureMgr.set_failure_level(mode_path, level);
	                }
	            },
	            get_failure_level: func { getprop(prop) ? 0 : 1 }
	        }
	    }

	    me.prop = me.fdm.wingsFailureID;
	    me.actuator_wings = set_unserviceable_cascading(me.prop, modes);
	    FailureMgr.add_failure_mode(me.prop, "Main wings", me.actuator_wings);
	},
	# set the stresslimit for the main wings
	setStressLimit: func (stressLimit = nil) {
		if (stressLimit != nil) {
			me.wingloadMax = stressLimit['wingloadMaxLbs'];
			me.wingloadMin = stressLimit['wingloadMinLbs'];
			me.maxG = stressLimit['maxG'];
			me.minG = stressLimit['minG'];
			me.weight = stressLimit['weightLbs'];
			if(me.wingloadMax != nil) {
				me.wingLoadLimitUpper = me.wingloadMax;
			} elsif (me.maxG != nil and me.weight != nil) {
				me.wingLoadLimitUpper = me.maxG * me.weight;
			}

			if(me.wingloadMin != nil) {
				me.wingLoadLimitLower = me.wingloadMin;
			} elsif (me.minG != nil and me.weight != nil) {
				me.wingLoadLimitLower = me.minG * me.weight;
			} elsif (me.wingLoadLimitUpper != nil) {
				me.wingLoadLimitLower = -me.wingLoadLimitUpper * 0.4;#estimate for when lower is not specified
			}
			me._looptimer.start();
		} else {
			me._looptimer.stop();
		}
	},
	# repair the aircaft
	repair: func () {
		me.failure_modes = FailureMgr._failmgr.failure_modes;
		me.mode_list = keys(me.failure_modes);

		foreach(var failure_mode_id; me.mode_list) {
			FailureMgr.set_failure_level(failure_mode_id, 0);
		}
		me.wingsAttached = TRUE;
		me.exploded = FALSE;
		me.lastMessageTime = 0;
		me.repairing = TRUE;
		me.input.simCrashed.setBoolValue(FALSE);
		me.repairTimer.restart(10.0);
	},
	_finishRepair: func () {
		me.repairing = FALSE;
	},
	_initProperties: func () {
		me.input.crackOn.setBoolValue(FALSE);
		me.input.creakOn.setBoolValue(FALSE);
		me.input.crackVol.setDoubleValue(0.0);
		me.input.creakVol.setDoubleValue(0.0);
		me.input.wCrashOn.setBoolValue(FALSE);
		me.input.crashOn.setBoolValue(FALSE);
		me.input.detachOn.setBoolValue(FALSE);
		me.input.explodeOn.setBoolValue(FALSE);
	},
	_identifyGears: func (gears) {
		me.contacts = props.globals.getNode("/gear").getChildren("gear");

		foreach(var contact; me.contacts) {
			me.index = contact.getIndex();
			me.isGear = me._contains(gears, me.index);
			me.wow = contact.getChild("wow");
			if (me.isGear == TRUE) {
				append(me.wowGear, me.wow);
			} else {
				append(me.wowStructure, me.wow);
			}
		}
	},	
	_isStructureInContact: func () {
		foreach(var structure; me.wowStructure) {
			if (structure.getBoolValue() == TRUE) {
				return TRUE;
			}
		}
		return FALSE;
	},
	_isGearInContact: func () {
		foreach(var gear; me.wowGear) {
			if (gear.getBoolValue() == TRUE) {
				return TRUE;
			}
		}
		return FALSE;
	},
	_contains: func (vector, content) {
		foreach(var vari; vector) {
			if (vari == content) {
				return TRUE;
			}
		}
		return FALSE;
	},
	_startImpactListeners: func () {
		ImpactStructureListener.crash = me;
		foreach(var structure; me.wowStructure) {
			setlistener(structure, func {call(ImpactStructureListener.run, nil, ImpactStructureListener, ImpactStructureListener)},0,0);
		}
	},
	_isRunning: func () {
		if (me.inService == FALSE or me.input.replay.getBoolValue() == TRUE or me.repairing == TRUE) {
			return FALSE;
		}
		me.time = me.fdm.input.simTime.getValue();
		if (me.time != nil and me.time > 1) {
			return TRUE;
		}
		return FALSE;
	},
	_calcGroundSpeed: func () {
  		me.realSpeed = me.fdm.getSpeedRelGround();

  		return me.realSpeed;
	},
	_impactDamage: func () {
	    me.lat = me.input.lat.getValue();
		me.lon = me.input.lon.getValue();
		me.info = geodinfo(me.lat, me.lon);
		me.solid = me.info == nil?TRUE:(me.info[1] == nil?TRUE:me.info[1].solid);
		me.speed = me._calcGroundSpeed();

		if (me.exploded == FALSE) {
			me.failure_modes = FailureMgr._failmgr.failure_modes;
		    me.mode_list = keys(me.failure_modes);
		    me.probability = (me.speed * me.speed) / 40000.0;# 200kt will fail everything, 0kt will fail nothing.
		    
		    me.hitStr = "something";
		    if(me.info != nil and me.info[1] != nil) {
			    me.hitStr = me.info[1].names == nil?"something":me.info[1].names[0];
			    foreach(infoStr; me.info[1].names) {
			    	if(find('_', infoStr) == -1) {
			    		me.hitStr = infoStr;
			    		break;
			    	}
			    }
			}
		    # test for explosion
		    if(me.probability > 0.766 and me.fdm.input.fuel.getValue() > 2500) {
		    	# 175kt+ and fuel in tanks will explode the aircraft on impact.
		    	me.input.simCrashed.setBoolValue(TRUE);
		    	me._explodeBegin("Aircraft hit "~me.hitStr~".");
		    	return;
		    }

		    foreach(var failure_mode_id; me.mode_list) {
		    	if(rand() < me.probability) {
		      		FailureMgr.set_failure_level(failure_mode_id, 1);
		      	}
		    }

			me.str = "Aircraft hit "~me.hitStr~".";
			me._output(me.str);
		} elsif (me.solid == TRUE) {
			# The aircraft is burning and will ignite the ground
			if(me.input.wildfire.getValue() == TRUE) {
				me.pos= geo.Coord.new().set_latlon(me.lat, me.lon);
				wildfire.ignite(me.pos, 1);
			}
		}
		if(me.solid == TRUE) {
			me._impactSoundBegin(me.speed);
		} else {
			me._impactSoundWaterBegin(me.speed);
		}
	},
	_impactSoundWaterBegin: func (speed) {
		if (speed > 5) {#check if sound already running?
			me.input.wCrashOn.setBoolValue(TRUE);
			me.soundWaterTimer.restart(3);
		}
	},
	_impactSoundWaterEnd: func	() {
		me.input.wCrashOn.setBoolValue(FALSE);
	},
	_impactSoundBegin: func (speed) {
		if (speed > 5) {
			me.input.crashOn.setBoolValue(TRUE);
			me.soundTimer.restart(3);
		}
	},
	_impactSoundEnd: func () {
		me.input.crashOn.setBoolValue(FALSE);
	},
	_explodeBegin: func(str) {
		me.input.explodeOn.setBoolValue(TRUE);
		me.exploded = TRUE;
		me.failure_modes = FailureMgr._failmgr.failure_modes;
	    me.mode_list = keys(me.failure_modes);

	    foreach(var failure_mode_id; me.mode_list) {
      		FailureMgr.set_failure_level(failure_mode_id, 1);
	    }

	    me._output(str~" and exploded.", TRUE);
		
		me.explodeTimer.restart(3);
	},
	_explodeEnd: func () {
		me.input.explodeOn.setBoolValue(FALSE);
	},
	_stressDamage: func (str) {
		me._output("Aircraft damaged: Wings broke off, due to "~str~" G forces.");
		me.input.detachOn.setBoolValue(TRUE);
		
  		FailureMgr.set_failure_level(me.fdm.wingsFailureID, 1);

		me.wingsAttached = FALSE;

		me.stressTimer.restart(3);
	},
	_stressDamageEnd: func () {
		me.input.detachOn.setBoolValue(FALSE);
	},
	_output: func (str, override = FALSE) {
		me.time = me.fdm.input.simTime.getValue();
		if (override == TRUE or (me.time - me.lastMessageTime) > 3) {
			me.lastMessageTime = me.time;
			print(str);
			screen.log.write(str, 0.7098, 0.5372, 0.0);# solarized yellow
		}
	},
	_loop: func () {
		me._testStress();
		me._testWaterImpact();
	},
	_testWaterImpact: func () {
		if(me.input.altAgl.getValue() < 0) {
			me.lat = me.input.lat.getValue();
			me.lon = me.input.lon.getValue();
			me.info = geodinfo(me.lat, me.lon);
			me.solid = me.info==nil?TRUE:(me.info[1] == nil?TRUE:me.info[1].solid);
			if(me.solid == FALSE) {
				me._impactDamage();
			}
		}
	},
	_testStress: func () {
		if (me._isRunning() == TRUE and me.wingsAttached == TRUE) {
			me.gForce = me.fdm.input.Nz.getValue() == nil?1:me.fdm.input.Nz.getValue();
			me.weight = me.fdm.input.weight.getValue();
			me.wingload = me.gForce * me.weight;

			me.broken = FALSE;

			if(me.wingload < 0) {
				me.broken = me._testWingload(-me.wingload, -me.wingLoadLimitLower);
				if(me.broken == TRUE) {
					me._stressDamage("negative");
				}
			} else {
				me.broken = me._testWingload(me.wingload, me.wingLoadLimitUpper);
				if(me.broken == TRUE) {
					me._stressDamage("positive");
				}
			}
		} else {
			me.input.crackOn.setBoolValue(FALSE);
			me.input.creakOn.setBoolValue(FALSE);
			#me.input.trembleOn.setValue(0);
		}
	},
	_testWingload: func (wingloadCurr, wingLoadLimit) {
		if (wingloadCurr > (wingLoadLimit * 0.5)) {
			#me.input.trembleOn.setValue(1);
			me.tremble_max = math.sqrt((wingloadCurr - (wingLoadLimit * 0.5)) / (wingLoadLimit * 0.5));
			#me.input.trembleMax.setDoubleValue(1);

			if (wingloadCurr > (wingLoadLimit * 0.75)) {

				#me.tremble_max = math.sqrt((wingloadCurr - (wingLoadLimit * 0.5)) / (wingLoadLimit * 0.5));
				me.input.creakVol.setDoubleValue(me.tremble_max);
				me.input.creakOn.setBoolValue(TRUE);

				if (wingloadCurr > (wingLoadLimit * 0.90)) {
					me.input.crackOn.setBoolValue(TRUE);
					me.input.crackVol.setDoubleValue(me.tremble_max);
					if (wingloadCurr > wingLoadLimit) {
						me.input.crackVol.setDoubleValue(1);
						me.input.creakVol.setDoubleValue(1);
						#me.input.trembleMax.setDoubleValue(1);
						return TRUE;
					}
				} else {
					me.input.crackOn.setBoolValue(FALSE);
				}
			} else {
				me.input.creakOn.setBoolValue(FALSE);
			}
		} else {
			me.input.crackOn.setBoolValue(FALSE);
			me.input.creakOn.setBoolValue(FALSE);
			#me.input.trembleOn.setValue(0);
		}
		return FALSE;
	},
};


var ImpactStructureListener = {
	crash: nil,
	run: func () {
		if (crash._isRunning() == TRUE) {
			var wow = crash._isStructureInContact();
			if (wow == TRUE) {
				crash._impactDamage();
			}
		}
	},
};


# static class
var fdmProperties = {
	input: {},
	convert: func () {
		foreach(var ident; keys(me.input)) {
		    me.input[ident] = props.globals.getNode(me.input[ident], 1);
		}
	},
	fps2kt: func (fps) {
		return fps * FPS2KT;
	},
	getSpeedRelGround: func () {
		return 0;
	},
	wingsFailureID: nil,
};

var jsbSimProp = {
	parents: [fdmProperties],
	input: {
				weight:     "fdm/jsbsim/inertia/weight-lbs",
				fuel:       "fdm/jsbsim/propulsion/total-fuel-lbs",
				simTime:    "fdm/jsbsim/simulation/sim-time-sec",
				northFps:   "velocities/speed-north-fps",
				eastFps:    "velocities/speed-east-fps",
				downFps:    "velocities/speed-down-fps",
				Nz:         "fdm/jsbsim/accelerations/Nz",
	},
	getSpeedRelGround: func () {
		me.northSpeed = me.input.northFps.getValue();
		me.eastSpeed  = me.input.eastFps.getValue();
		me.horzSpeed  = math.sqrt((me.eastSpeed * me.eastSpeed) + (me.northSpeed * me.northSpeed));
  		me.vertSpeed  = me.input.downFps.getValue();
  		me.realSpeed  = me.fps2kt(math.sqrt((me.horzSpeed * me.horzSpeed) + (me.vertSpeed * me.vertSpeed)));

  		return me.realSpeed;
	},
	wingsFailureID: "fdm/jsbsim/structural/wings",
};

var yaSimProp = {
	parents: [fdmProperties],
	input: {
				weight:     "yasim/gross-weight-lbs",
				fuel:       "consumables/fuel/total-fuel-lbs",
				simTime:    "sim/time/elapsed-sec",
				northFps:   "velocities/speed-north-fps",
				eastFps:    "velocities/speed-east-fps",
				downFps:    "velocities/speed-down-fps",
				Nz:         "accelerations/n-z-cg-fps_sec",
	},
	getSpeedRelGround: func () {
		me.northSpeed = me.input.northFps.getValue();
		me.eastSpeed  = me.input.eastFps.getValue();
		me.horzSpeed  = math.sqrt((me.eastSpeed * me.eastSpeed) + (me.northSpeed * me.northSpeed));
  		me.vertSpeed  = me.input.downFps.getValue();
  		me.realSpeed  = me.fps2kt(math.sqrt((me.horzSpeed * me.horzSpeed) + (me.vertSpeed * me.vertSpeed)));

  		return me.realSpeed;
	},
	wingsFailureID: "structural/wings",
};


# TODO:
#
# Loss of inertia if impacting/sliding? Or should the jsb groundcontacts take care of that alone?
# If gears hit something at too high speed the gears should be damaged?
# Make property to control if system active, or method enough?
# Explosion depending on bumpiness and speed when sliding?
# Tie in with damage from Bombable?
# Use galvedro's UpdateLoop framework when it gets merged


# example uses:
#
# var crashCode = CrashAndStress.new([0,1,2]); 
#
# var crashCode = CrashAndStress.new([0,1,2], {"weightLbs":30000, "maxG": 12});
#
# var crashCode = CrashAndStress.new([0,1,2,3], {"weightLbs":20000, "maxG": 11, "minG": -5});
#
# var crashCode = CrashAndStress.new([0,1,2], {"wingloadMaxLbs": 90000, "wingloadMinLbs": -45000}, ["controls/flight/aileron", "controls/flight/elevator", "controls/flight/flaps"]);
#
# var crashCode = CrashAndStress.new([0,1,2], {"wingloadMaxLbs":90000}, ["controls/flight/aileron", "controls/flight/elevator", "controls/flight/flaps"]);
#
# Gears parameter must be defined.
# Stress parameter is optional. If minimum wing stress is not defined it will be set to -40% of max wingload stress if that is defined.
# The last optional parameter is a list of failure mode IDs that shall fail when wings detach. They must be defined in the FailureMgr.
#
#
# Remember to add sounds and to add the sound properties as custom signals to the replay recorder.


# example use:
var crashCode = nil;
var crash_start = func {
	removelistener(lsnr);
	crashCode = CrashAndStress.new([0,1,2], {"weightLbs":30000, "maxG": 12}, ["controls/flight/aileron", "controls/flight/elevator"]);
	crashCode.start();
}

var lsnr = setlistener("sim/signals/fdm-initialized", crash_start);

# test:
var repair = func {
	crashCode.repair();
};

Notice that you should edit the line underneath # example use to fit your aircraft requirements.

In your aircraft-set.xml file under nasal tags add

<crash>
  <file>Aircraft/[aircraft name here]/Nasal/crash-and-stress.nas</file>
</crash>

Add this to your sounds file, remember to replace JA37, with your aircraft folder name:

<?xml version="1.0" encoding="UTF-8"?>

<PropertyList>

<fx>

<!-- ... -->

  <aircraft-explode>
    <name>aircraft-explode</name>
    <path>Aircraft/JA37/Sounds/aircraft-explode.wav</path>
    <mode>once</mode>
    <condition>
      <equals>
        <property>damage/sounds/explode-on</property>
        <value>1</value>
      </equals>
    </condition>
    <position>
      <x>0.01</x>
      <y>0.01</y>
      <z>0.01</z>
    </position>
    <volume>
      <factor>3</factor>
      <max>3</max>
    </volume>
  </aircraft-explode>

  <aircraft-detach>
    <name>aircraft-detach</name>
    <path>Aircraft/JA37/Sounds/aircraft-wings-detach.wav</path>
    <mode>once</mode>
    <condition>
      <equals>
        <property>damage/sounds/detach-on</property>
        <value>1</value>
      </equals>
    </condition>
    <position>
      <x>0.01</x>
      <y>0.01</y>
      <z>0.01</z>
    </position>      
    <volume>
      <factor>1</factor>
    </volume>
  </aircraft-detach>

  <aircraft-crash>
    <name>aircraft-impact</name>
    <path>Sounds/aircraft-crash.wav</path>
    <mode>once</mode>
    <condition>
      <equals>
        <property>damage/sounds/crash-on</property>
        <value>1</value>
      </equals>
    </condition>
    <position>
      <x>0.01</x>
      <y>0.01</y>
      <z>0.01</z>
    </position>      
    <volume>
      <factor>1</factor>
    </volume>
  </aircraft-crash>

  <aircraft-water-crash>
    <name>aircraft-water-crash</name>
    <path>Aircraft/JA37/Sounds/aircraft-water-crash.wav</path>
    <mode>once</mode>
    <condition>
      <equals>
        <property>damage/sounds/water-crash-on</property>
        <value>1</value>
      </equals>
    </condition>
    <position>
      <x>0.01</x>
      <y>0.01</y>
      <z>0.01</z>
    </position>      
    <volume>
      <factor>1</factor>
    </volume>
  </aircraft-water-crash>

  <aircraft-crack>
    <name>aircraft-crack</name>
    <path>Aircraft/JA37/Sounds/aircraft-crack.wav</path>
    <mode>once</mode>
    <condition>
      <property>sim/current-view/internal</property>
      <equals>
        <property>damage/sounds/crack-on</property>
        <value>1</value>
      </equals>
    </condition>
    <position>
      <x>0.01</x>
      <y>0.01</y>
      <z>0.01</z>
    </position>      
    <volume>
      <property>damage/sounds/crack-volume</property>
      <factor>1</factor>
    </volume>
  </aircraft-crack>

  <aircraft-creaking>
    <name>aircraft-creaking</name>
    <path>Aircraft/JA37/Sounds/aircraft-creaking.wav</path>
    <mode>looped</mode>
    <condition>
      <property>sim/current-view/internal</property>
      <equals>
        <property>damage/sounds/creaking-on</property>
        <value>1</value>
      </equals>
    </condition>
    <position>
      <x>0.01</x>
      <y>0.01</y>
      <z>0.01</z>
    </position>      
    <volume>
      <property>damage/sounds/creaking-volume</property>
      <factor>1</factor>
    </volume>
  </aircraft-creaking>

<!-- ... -->

</fx>

</PropertyList>

Add some sounds to the aircraft sound folder that corresponds to the file names used in the above. (you can eventually use those in the Mig15 or JA-37 folders, depending what kind of sounds you prefer.)

Optionally add these signals to the replay recorder:

        <signal>
          <type>bool</type>
          <property type="string">damage/sounds/explode-on</property>
        </signal>
        <signal>
          <type>bool</type>
          <property type="string">damage/sounds/crash-on</property>
        </signal>
        <signal>
          <type>bool</type>
          <property type="string">damage/sounds/water-crash-on</property>
        </signal>
        <signal>
          <type>bool</type>
          <property type="string">damage/sounds/crack-on</property>
        </signal>
        <signal>
          <type>bool</type>
          <property type="string">damage/sounds/creaking-on</property>
        </signal>
        <signal>
          <type>float</type>
          <property type="string">damage/sounds/crack-volume</property>
        </signal>
        <signal>
          <type>float</type>
          <property type="string">damage/sounds/creaking-volume</property>
        </signal>
        <signal>
          <type>bool</type>
          <property type="string">fdm/jsbsim/structural/wings/serviceable</property>
        </signal>

Notice that the last signal is JSBSim specific, the corresponding YASim signal is:

        <signal>
          <type>bool</type>
          <property type="string">structural/wings/serviceable</property>
        </signal>

That property is also what you would use to animate wings being detached and/or changes in the aerodynamics.

Performance

As it is now you should feel no performance degradation at all from using it.

People volunteering to work on this

  • Bomber
  • Necolatis

Aircrafts that use this system

Saab JA-37 Viggen (version 2.83+)

Related content