]> git.mxchange.org Git - flightgear.git/blob - src/Radio/radio.cxx
remove debugging code
[flightgear.git] / src / Radio / radio.cxx
1 // radio.cxx -- implementation of FGRadio
2 // Class to manage radio propagation using the ITM model
3 // Written by Adrian Musceac, started August 2011.
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <math.h>
26 #define NDEBUG
27 #include <assert.h>
28 #include <stdlib.h>
29 #include <deque>
30 #include "radio.hxx"
31 #include <simgear/scene/material/mat.hxx>
32 #include <Scenery/scenery.hxx>
33
34 #define WITH_POINT_TO_POINT 1
35 #include "itm.cpp"
36
37
38 FGRadioTransmission::FGRadioTransmission() {
39         
40         /** radio parameters (which should probably be set for each radio) */
41         
42         _receiver_sensitivity = -110.0; // typical AM receiver sensitivity seems to be 0.8 microVolt at 12dB SINAD
43         
44         /** AM transmitter power in dBm.
45         *       Note this value is calculated from the typical final transistor stage output
46         *       small aircraft have portable transmitters which operate at 36 dBm output (4 Watts) others operate in the range 10-20 W
47         *       later possibly store this value in aircraft description
48         *       ATC comms usually operate high power equipment, thus making the link asymetrical; this is taken care of in propagation routines
49         *       Typical output powers for ATC ground equipment, VHF-UHF:
50         *       40 dBm - 10 W (ground, clearance)
51         *       44 dBm - 20 W (tower)
52         *       47 dBm - 50 W (center, sectors)
53         *       50 dBm - 100 W (center, sectors)
54         *       53 dBm - 200 W (sectors, on directional arrays)
55         **/
56         _transmitter_power = 43.0;
57         
58         _tx_antenna_height = 2.0; // TX antenna height above ground level
59         
60         _rx_antenna_height = 2.0; // RX antenna height above ground level
61         
62         /** pilot plane's antenna gain + AI aircraft antenna gain
63         *       real-life gain for conventional monopole/dipole antenna
64         **/
65         _antenna_gain = 2.0;
66         
67         _rx_antenna_gain = 1.0;
68         _tx_antenna_gain = 1.0;
69         
70         _rx_line_losses = 2.0;  // to be configured for each station
71         _tx_line_losses = 2.0;
72         
73         _propagation_model = 2; //  choose between models via option: realistic radio on/off
74         _terrain_sampling_distance = fgGetDouble("/sim/radio/sampling-distance", 90.0); // regular SRTM is 90 meters
75 }
76
77 FGRadioTransmission::~FGRadioTransmission() 
78 {
79 }
80
81
82 double FGRadioTransmission::getFrequency(int radio) {
83         double freq = 118.0;
84         switch (radio) {
85                 case 1:
86                         freq = fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
87                         break;
88                 case 2:
89                         freq = fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
90                         break;
91                 default:
92                         freq = fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
93                         
94         }
95         return freq;
96 }
97
98 /*** TODO: receive multiplayer chat message and voice
99 ***/
100 void FGRadioTransmission::receiveChat(SGGeod tx_pos, double freq, string text, int ground_to_air) {
101
102 }
103
104 /*** TODO: receive navaid 
105 ***/
106 double FGRadioTransmission::receiveNav(SGGeod tx_pos, double freq, int transmission_type) {
107         
108         // typical VOR/LOC transmitter power appears to be 200 Watt ~ 53 dBm
109         // vor/loc typical sensitivity between -107 and -101 dBm
110         // glideslope sensitivity between -85 and -81 dBm
111         if ( _propagation_model == 1) {
112                 return LOS_calculate_attenuation(tx_pos, freq, 1);
113         }
114         else if ( _propagation_model == 2) {
115                 return ITM_calculate_attenuation(tx_pos, freq, 1);
116         }
117         
118         return -1;
119
120 }
121
122 /*** Receive ATC radio communication as text
123 ***/
124 void FGRadioTransmission::receiveATC(SGGeod tx_pos, double freq, string text, int ground_to_air) {
125
126         
127         double comm1 = getFrequency(1);
128         double comm2 = getFrequency(2);
129         if ( !(fabs(freq - comm1) <= 0.0001) &&  !(fabs(freq - comm2) <= 0.0001) ) {
130                 //cerr << "Frequency not tuned: " << freq << " Radio1: " << comm1 << " Radio2: " << comm2 << endl;
131                 return;
132         }
133         else {
134         
135                 if ( _propagation_model == 0) {
136                         fgSetString("/sim/messages/atc", text.c_str());
137                 }
138                 else if ( _propagation_model == 1 ) {
139                         // TODO: free space, round earth
140                         double signal = LOS_calculate_attenuation(tx_pos, freq, ground_to_air);
141                         if (signal <= 0.0) {
142                                 SG_LOG(SG_GENERAL, SG_BULK, "Signal below receiver minimum sensitivity: " << signal);
143                                 //cerr << "Signal below receiver minimum sensitivity: " << signal << endl;
144                                 return;
145                         }
146                         else {
147                                 SG_LOG(SG_GENERAL, SG_BULK, "Signal completely readable: " << signal);
148                                 //cerr << "Signal completely readable: " << signal << endl;
149                                 fgSetString("/sim/messages/atc", text.c_str());
150                                 /** write signal strength above threshold to the property tree
151                                 *       to implement a simple S-meter just divide by 3 dB per grade (VHF norm)
152                                 **/
153                                 fgSetDouble("/sim/radio/comm1-signal", signal);
154                         }
155                 }
156                 else if ( _propagation_model == 2 ) {
157                         // Use ITM propagation model
158                         double signal = ITM_calculate_attenuation(tx_pos, freq, ground_to_air);
159                         if (signal <= 0.0) {
160                                 SG_LOG(SG_GENERAL, SG_BULK, "Signal below receiver minimum sensitivity: " << signal);
161                                 //cerr << "Signal below receiver minimum sensitivity: " << signal << endl;
162                                 return;
163                         }
164                         if ((signal > 0.0) && (signal < 12.0)) {
165                                 /** for low SNR values implement a way to make the conversation
166                                 *       hard to understand but audible
167                                 *       in the real world, the receiver AGC fails to capture the slope
168                                 *       and the signal, due to being amplitude modulated, decreases volume after demodulation
169                                 *       the workaround below is more akin to what would happen on a FM transmission
170                                 *       therefore the correct way would be to work on the volume
171                                 **/
172                                 /*
173                                 string hash_noise = " ";
174                                 int reps = (int) (fabs(floor(signal - 11.0)) * 2);
175                                 int t_size = text.size();
176                                 for (int n = 1; n <= reps; ++n) {
177                                         int pos = rand() % (t_size -1);
178                                         text.replace(pos,1, hash_noise);
179                                 }
180                                 */
181                                 double volume = (fabs(signal - 12.0) / 12);
182                                 double old_volume = fgGetDouble("/sim/sound/voices/voice/volume");
183                                 SG_LOG(SG_GENERAL, SG_BULK, "Usable signal at limit: " << signal);
184                                 //cerr << "Usable signal at limit: " << signal << endl;
185                                 fgSetDouble("/sim/sound/voices/voice/volume", volume);
186                                 fgSetString("/sim/messages/atc", text.c_str());
187                                 fgSetDouble("/sim/radio/comm1-signal", signal);
188                                 fgSetDouble("/sim/sound/voices/voice/volume", old_volume);
189                         }
190                         else {
191                                 SG_LOG(SG_GENERAL, SG_BULK, "Signal completely readable: " << signal);
192                                 //cerr << "Signal completely readable: " << signal << endl;
193                                 fgSetString("/sim/messages/atc", text.c_str());
194                                 /** write signal strength above threshold to the property tree
195                                 *       to implement a simple S-meter just divide by 3 dB per grade (VHF norm)
196                                 **/
197                                 fgSetDouble("/sim/radio/comm1-signal", signal);
198                         }
199                         
200                 }
201                 
202         }
203         
204 }
205
206 /***  Implement radio attenuation               
207           based on the Longley-Rice propagation model
208 ***/
209 double FGRadioTransmission::ITM_calculate_attenuation(SGGeod pos, double freq, int transmission_type) {
210
211         
212         
213         /** ITM default parameters 
214                 TODO: take them from tile materials (especially for sea)?
215         **/
216         double eps_dielect=15.0;
217         double sgm_conductivity = 0.005;
218         double eno = 301.0;
219         double frq_mhz;
220         if( (freq < 118.0) || (freq > 137.0) )
221                 frq_mhz = 125.0;        // sane value, middle of bandplan
222         else
223                 frq_mhz = freq;
224         int radio_climate = 5;          // continental temperate
225         int pol=1;      // assuming vertical polarization although this is more complex in reality
226         double conf = 0.90;     // 90% of situations and time, take into account speed
227         double rel = 0.90;      
228         double dbloss;
229         char strmode[150];
230         int p_mode = 0; // propgation mode selector: 0 LOS, 1 diffraction dominant, 2 troposcatter
231         double horizons[2];
232         int errnum;
233         
234         double clutter_loss = 0.0;      // loss due to vegetation and urban
235         double tx_pow = _transmitter_power;
236         double ant_gain = _antenna_gain;
237         double signal = 0.0;
238         
239         if(transmission_type == 1)
240                 tx_pow = _transmitter_power + 6.0;
241
242         if((transmission_type == 1) || (transmission_type == 3))
243                 ant_gain = _antenna_gain + 3.0; //pilot plane's antenna gain + ground station antenna gain
244         
245         double link_budget = tx_pow - _receiver_sensitivity + ant_gain; 
246
247         FGScenery * scenery = globals->get_scenery();
248         
249         double own_lat = fgGetDouble("/position/latitude-deg");
250         double own_lon = fgGetDouble("/position/longitude-deg");
251         double own_alt_ft = fgGetDouble("/position/altitude-ft");
252         double own_alt= own_alt_ft * SG_FEET_TO_METER;
253         
254         
255         //cerr << "ITM:: pilot Lat: " << own_lat << ", Lon: " << own_lon << ", Alt: " << own_alt << endl;
256         
257         SGGeod own_pos = SGGeod::fromDegM( own_lon, own_lat, own_alt );
258         SGGeod max_own_pos = SGGeod::fromDegM( own_lon, own_lat, SG_MAX_ELEVATION_M );
259         SGGeoc center = SGGeoc::fromGeod( max_own_pos );
260         SGGeoc own_pos_c = SGGeoc::fromGeod( own_pos );
261         
262         /**     position of sender radio antenna (HAAT)
263                         sender can be aircraft or ground station
264         **/
265         double ATC_HAAT = 30.0;
266         double Aircraft_HAAT = 5.0;
267         double sender_alt_ft,sender_alt;
268         double transmitter_height=0.0;
269         double receiver_height=0.0;
270         SGGeod sender_pos = pos;
271         
272         sender_alt_ft = sender_pos.getElevationFt();
273         sender_alt = sender_alt_ft * SG_FEET_TO_METER;
274         SGGeod max_sender_pos = SGGeod::fromGeodM( pos, SG_MAX_ELEVATION_M );
275         SGGeoc sender_pos_c = SGGeoc::fromGeod( sender_pos );
276         //cerr << "ITM:: sender Lat: " << parent->getLatitude() << ", Lon: " << parent->getLongitude() << ", Alt: " << sender_alt << endl;
277         
278         double point_distance= _terrain_sampling_distance; 
279         double course = SGGeodesy::courseRad(own_pos_c, sender_pos_c);
280         double distance_m = SGGeodesy::distanceM(own_pos, sender_pos);
281         double probe_distance = 0.0;
282         /** If distance larger than this value (300 km), assume reception imposssible */
283         if (distance_m > 300000)
284                 return -1.0;
285         /** If above 8000 meters, consider LOS mode and calculate free-space att */
286         if (own_alt > 8000) {
287                 dbloss = 20 * log10(distance_m) +20 * log10(frq_mhz) -27.55;
288                 SG_LOG(SG_GENERAL, SG_BULK,
289                         "ITM Free-space mode:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, free-space attenuation");
290                 //cerr << "ITM Free-space mode:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, free-space attenuation" << endl;
291                 signal = link_budget - dbloss;
292                 return signal;
293         }
294         
295                 
296         int max_points = (int)floor(distance_m / point_distance);
297         double delta_last = fmod(distance_m, point_distance);
298         
299         deque<double> _elevations;
300         deque<string> materials;
301         
302
303         double elevation_under_pilot = 0.0;
304         if (scenery->get_elevation_m( max_own_pos, elevation_under_pilot, NULL )) {
305                 receiver_height = own_alt - elevation_under_pilot + 3; //assume antenna located 3 meters above ground
306         }
307
308         double elevation_under_sender = 0.0;
309         if (scenery->get_elevation_m( max_sender_pos, elevation_under_sender, NULL )) {
310                 transmitter_height = sender_alt - elevation_under_sender;
311         }
312         else {
313                 transmitter_height = sender_alt;
314         }
315         
316         if(transmission_type == 1) 
317                 transmitter_height += ATC_HAAT;
318         else
319                 transmitter_height += Aircraft_HAAT;
320         
321         SG_LOG(SG_GENERAL, SG_BULK,
322                         "ITM:: RX-height: " << receiver_height << " meters, TX-height: " << transmitter_height << " meters, Distance: " << distance_m << " meters");
323         cerr << "ITM:: RX-height: " << receiver_height << " meters, TX-height: " << transmitter_height << " meters, Distance: " << distance_m << " meters" << endl;
324         
325         unsigned int e_size = (deque<unsigned>::size_type)max_points;
326         
327         while (_elevations.size() <= e_size) {
328                 probe_distance += point_distance;
329                 SGGeod probe = SGGeod::fromGeoc(center.advanceRadM( course, probe_distance ));
330                 const SGMaterial *mat = 0;
331                 double elevation_m = 0.0;
332         
333                 if (scenery->get_elevation_m( probe, elevation_m, &mat )) {
334                         if((transmission_type == 3) || (transmission_type == 4)) {
335                                 _elevations.push_back(elevation_m);
336                                 if(mat) {
337                                         const std::vector<string> mat_names = mat->get_names();
338                                         materials.push_back(mat_names[0]);
339                                 }
340                                 else {
341                                         materials.push_back("None");
342                                 }
343                         }
344                         else {
345                                  _elevations.push_front(elevation_m);
346                                  if(mat) {
347                                          const std::vector<string> mat_names = mat->get_names();
348                                          materials.push_front(mat_names[0]);
349                                 }
350                                 else {
351                                         materials.push_front("None");
352                                 }
353                         }
354                 }
355                 else {
356                         if((transmission_type == 3) || (transmission_type == 4)) {
357                                 _elevations.push_back(0.0);
358                                 materials.push_back("None");
359                         }
360                         else {
361                                 _elevations.push_front(0.0);
362                                 materials.push_front("None");
363                         }
364                 }
365         }
366         if((transmission_type == 3) || (transmission_type == 4)) {
367                 _elevations.push_front(elevation_under_pilot);
368                 if (delta_last > (point_distance / 2) )                 // only add last point if it's farther than half point_distance
369                         _elevations.push_back(elevation_under_sender);
370         }
371         else {
372                 _elevations.push_back(elevation_under_pilot);
373                 if (delta_last > (point_distance / 2) )
374                         _elevations.push_front(elevation_under_sender);
375         }
376         
377         
378         double max_alt_between=0.0;
379         for( deque<double>::size_type i = 0; i < _elevations.size(); i++ ) {
380                 if (_elevations[i] > max_alt_between) {
381                         max_alt_between = _elevations[i];
382                 }
383         }
384         
385         double num_points= (double)_elevations.size();
386         //cerr << "ITM:: Max alt between: " << max_alt_between << ", num points:" << num_points << endl;
387         _elevations.push_front(point_distance);
388         _elevations.push_front(num_points -1);
389         int size = _elevations.size();
390         double itm_elev[size];
391         for(int i=0;i<size;i++) {
392                 itm_elev[i]=_elevations[i];
393                 //cerr << "ITM:: itm_elev: " << _elevations[i] << endl;
394         }
395
396         if((transmission_type == 3) || (transmission_type == 4)) {
397                 // the sender and receiver roles are switched
398                 point_to_point(itm_elev, receiver_height, transmitter_height,
399                         eps_dielect, sgm_conductivity, eno, frq_mhz, radio_climate,
400                         pol, conf, rel, dbloss, strmode, p_mode, horizons, errnum);
401                 if( fgGetBool( "/sim/radio/use-clutter-attenuation", false ) )
402                         clutterLoss(frq_mhz, distance_m, itm_elev, materials, receiver_height, transmitter_height, p_mode, horizons, clutter_loss);
403         }
404         else {
405                 point_to_point(itm_elev, transmitter_height, receiver_height,
406                         eps_dielect, sgm_conductivity, eno, frq_mhz, radio_climate,
407                         pol, conf, rel, dbloss, strmode, p_mode, horizons, errnum);
408                 if( fgGetBool( "/sim/radio/use-clutter-attenuation", false ) )
409                         clutterLoss(frq_mhz, distance_m, itm_elev, materials, transmitter_height, receiver_height, p_mode, horizons, clutter_loss);
410         }
411         SG_LOG(SG_GENERAL, SG_BULK,
412                         "ITM:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, " << strmode << ", Error: " << errnum);
413         cerr << "ITM:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, " << strmode << ", Error: " << errnum << endl;
414         
415         cerr << "Clutter loss: " << clutter_loss << endl;
416         //if (errnum == 4)      // if parameters are outside sane values for lrprop, the alternative method is used
417         //      return -1;
418         signal = link_budget - dbloss - clutter_loss;
419         return signal;
420
421 }
422
423 /*** Calculate losses due to vegetation and urban clutter (WIP)
424 *        We are only worried about clutter loss, terrain influence 
425 *        on the first Fresnel zone is calculated in the ITM functions
426 ***/
427 void FGRadioTransmission::clutterLoss(double freq, double distance_m, double itm_elev[], deque<string> materials,
428         double transmitter_height, double receiver_height, int p_mode,
429         double horizons[], double &clutter_loss) {
430         
431         distance_m = itm_elev[0] * itm_elev[1]; // only consider elevation points
432         
433         if (p_mode == 0) {      // LOS: take each point and see how clutter height affects first Fresnel zone
434                 int mat = 0;
435                 int j=1; 
436                 for (int k=3;k < (int)(itm_elev[0]) + 2;k++) {
437                         
438                         double clutter_height = 0.0;    // mean clutter height for a certain terrain type
439                         double clutter_density = 0.0;   // percent of reflected wave
440                         get_material_properties(materials[mat], clutter_height, clutter_density);
441                         
442                         double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
443                         // First Fresnel radius
444                         double frs_rad = 548 * sqrt( (j * itm_elev[1] * (itm_elev[0] - j) * itm_elev[1] / 1000000) / (  distance_m * freq / 1000) );
445                         assert(frs_rad > 0);
446                         
447                         //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
448                         
449                         double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
450                         double d1 = j * itm_elev[1];
451                         if ((itm_elev[2] + transmitter_height) > ( itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) {
452                                 d1 = (itm_elev[0] - j) * itm_elev[1];
453                         }
454                         double ray_height = (grad * d1) + min_elev;
455                         
456                         double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
457                         double intrusion = fabs(clearance);
458                         
459                         if (clearance >= 0) {
460                                 // no losses
461                         }
462                         else if (clearance < 0 && (intrusion < clutter_height)) {
463                                 
464                                 clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
465                         }
466                         else if (clearance < 0 && (intrusion > clutter_height)) {
467                                 clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
468                         }
469                         else {
470                                 // no losses
471                         }
472                         j++;
473                         mat++;
474                 }
475                 
476         }
477         else if (p_mode == 1) {         // diffraction
478                 
479                 if (horizons[1] == 0.0) {       //      single horizon: same as above, except pass twice using the highest point
480                         int num_points_1st = (int)floor( horizons[0] * itm_elev[0]/ distance_m ); 
481                         int num_points_2nd = (int)ceil( (distance_m - horizons[0]) * itm_elev[0] / distance_m ); 
482                         //cerr << "Diffraction 1 horizon:: points1: " << num_points_1st << " points2: " << num_points_2nd << endl;
483                         int last = 1;
484                         /** perform the first pass */
485                         int mat = 0;
486                         int j=1; 
487                         for (int k=3;k < num_points_1st + 2;k++) {
488                                 if (num_points_1st < 1)
489                                         break;
490                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
491                                 double clutter_density = 0.0;   // percent of reflected wave
492                                 get_material_properties(materials[mat], clutter_height, clutter_density);
493                                 
494                                 double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[num_points_1st + 2] + clutter_height) / distance_m;
495                                 // First Fresnel radius
496                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_1st - j) * itm_elev[1] / 1000000) / ( num_points_1st * itm_elev[1] * freq / 1000) );
497                                 assert(frs_rad > 0);
498                                 
499                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
500                                 
501                                 double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[num_points_1st + 2] + clutter_height);
502                                 double d1 = j * itm_elev[1];
503                                 if ( (itm_elev[2] + transmitter_height) > (itm_elev[num_points_1st + 2] + clutter_height) ) {
504                                         d1 = (num_points_1st - j) * itm_elev[1];
505                                 }
506                                 double ray_height = (grad * d1) + min_elev;
507                                 
508                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
509                                 double intrusion = fabs(clearance);
510                                 
511                                 if (clearance >= 0) {
512                                         // no losses
513                                 }
514                                 else if (clearance < 0 && (intrusion < clutter_height)) {
515                                         
516                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
517                                 }
518                                 else if (clearance < 0 && (intrusion > clutter_height)) {
519                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
520                                 }
521                                 else {
522                                         // no losses
523                                 }
524                                 j++;
525                                 mat++;
526                                 last = k;
527                         }
528                         
529                         /** and the second pass */
530                         mat +=1;
531                         j =1; // first point is diffraction edge, 2nd the RX elevation
532                         for (int k=last+2;k < (int)(itm_elev[0]) + 2;k++) {
533                                 if (num_points_2nd < 1)
534                                         break;
535                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
536                                 double clutter_density = 0.0;   // percent of reflected wave
537                                 get_material_properties(materials[mat], clutter_height, clutter_density);
538                                 
539                                 double grad = fabs(itm_elev[last+1] + clutter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
540                                 // First Fresnel radius
541                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_2nd - j) * itm_elev[1] / 1000000) / (  num_points_2nd * itm_elev[1] * freq / 1000) );
542                                 assert(frs_rad > 0);
543                                 
544                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
545                                 
546                                 double min_elev = SGMiscd::min(itm_elev[last+1] + clutter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
547                                 double d1 = j * itm_elev[1];
548                                 if ( (itm_elev[last+1] + clutter_height) > (itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) { 
549                                         d1 = (num_points_2nd - j) * itm_elev[1];
550                                 }
551                                 double ray_height = (grad * d1) + min_elev;
552                                 
553                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
554                                 double intrusion = fabs(clearance);
555                                 
556                                 if (clearance >= 0) {
557                                         // no losses
558                                 }
559                                 else if (clearance < 0 && (intrusion < clutter_height)) {
560                                         
561                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
562                                 }
563                                 else if (clearance < 0 && (intrusion > clutter_height)) {
564                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
565                                 }
566                                 else {
567                                         // no losses
568                                 }
569                                 j++;
570                                 mat++;
571                         }
572                         
573                 }
574                 else {  // double horizon: same as single horizon, except there are 3 segments
575                         
576                         int num_points_1st = (int)floor( horizons[0] * itm_elev[0] / distance_m ); 
577                         int num_points_2nd = (int)floor(horizons[1] * itm_elev[0] / distance_m ); 
578                         int num_points_3rd = (int)itm_elev[0] - num_points_1st - num_points_2nd; 
579                         //cerr << "Double horizon:: horizon1: " << horizons[0] << " horizon2: " << horizons[1] << " distance: " << distance_m << endl;
580                         //cerr << "Double horizon:: points1: " << num_points_1st << " points2: " << num_points_2nd << " points3: " << num_points_3rd << endl;
581                         int last = 1;
582                         /** perform the first pass */
583                         int mat = 0;
584                         int j=1; // first point is TX elevation, 2nd is obstruction elevation
585                         for (int k=3;k < num_points_1st +2;k++) {
586                                 if (num_points_1st < 1)
587                                         break;
588                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
589                                 double clutter_density = 0.0;   // percent of reflected wave
590                                 get_material_properties(materials[mat], clutter_height, clutter_density);
591                                 
592                                 double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[num_points_1st + 2] + clutter_height) / distance_m;
593                                 // First Fresnel radius
594                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_1st - j) * itm_elev[1] / 1000000) / (  num_points_1st * itm_elev[1] * freq / 1000) );
595                                 assert(frs_rad > 0);
596                                 
597                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
598                                 
599                                 double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[num_points_1st + 2] + clutter_height);
600                                 double d1 = j * itm_elev[1];
601                                 if ( (itm_elev[2] + transmitter_height) > (itm_elev[num_points_1st + 2] + clutter_height) ) {
602                                         d1 = (num_points_1st - j) * itm_elev[1];
603                                 }
604                                 double ray_height = (grad * d1) + min_elev;
605                                 
606                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
607                                 double intrusion = fabs(clearance);
608                                 
609                                 if (clearance >= 0) {
610                                         // no losses
611                                 }
612                                 else if (clearance < 0 && (intrusion < clutter_height)) {
613                                         
614                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
615                                 }
616                                 else if (clearance < 0 && (intrusion > clutter_height)) {
617                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
618                                 }
619                                 else {
620                                         // no losses
621                                 }
622                                 j++;
623                                 last = k;
624                         }
625                         mat +=1;
626                         /** and the second pass */
627                         int last2=1;
628                         j =1; // first point is 1st obstruction elevation, 2nd is 2nd obstruction elevation
629                         for (int k=last+2;k < num_points_1st + num_points_2nd +2;k++) {
630                                 if (num_points_2nd < 1)
631                                         break;
632                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
633                                 double clutter_density = 0.0;   // percent of reflected wave
634                                 get_material_properties(materials[mat], clutter_height, clutter_density);
635                                 
636                                 double grad = fabs(itm_elev[last+1] + clutter_height - itm_elev[num_points_1st + num_points_2nd + 2] + clutter_height) / distance_m;
637                                 // First Fresnel radius
638                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_2nd - j) * itm_elev[1] / 1000000) / (  num_points_2nd * itm_elev[1] * freq / 1000) );
639                                 
640                                 assert(frs_rad > 0);
641                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
642                                 
643                                 double min_elev = SGMiscd::min(itm_elev[last+1] + clutter_height, itm_elev[num_points_1st + num_points_2nd +2] + clutter_height);
644                                 double d1 = j * itm_elev[1];
645                                 if ( (itm_elev[last+1] + clutter_height) > (itm_elev[num_points_1st + num_points_2nd + 2] + clutter_height) ) { 
646                                         d1 = (num_points_2nd - j) * itm_elev[1];
647                                 }
648                                 double ray_height = (grad * d1) + min_elev;
649                                 
650                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
651                                 double intrusion = fabs(clearance);
652                                 
653                                 if (clearance >= 0) {
654                                         // no losses
655                                 }
656                                 else if (clearance < 0 && (intrusion < clutter_height)) {
657                                         
658                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
659                                 }
660                                 else if (clearance < 0 && (intrusion > clutter_height)) {
661                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
662                                 }
663                                 else {
664                                         // no losses
665                                 }
666                                 j++;
667                                 mat++;
668                                 last2 = k;
669                         }
670                         
671                         /** third and final pass */
672                         mat +=1;
673                         j =1; // first point is 2nd obstruction elevation, 3rd is RX elevation
674                         for (int k=last2+2;k < (int)itm_elev[0] + 2;k++) {
675                                 if (num_points_3rd < 1)
676                                         break;
677                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
678                                 double clutter_density = 0.0;   // percent of reflected wave
679                                 get_material_properties(materials[mat], clutter_height, clutter_density);
680                                 
681                                 double grad = fabs(itm_elev[last2+1] + clutter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
682                                 // First Fresnel radius
683                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_3rd - j) * itm_elev[1] / 1000000) / (  num_points_3rd * itm_elev[1] * freq / 1000) );
684                                 
685                                 assert(frs_rad > 0);
686                                 
687                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
688                                 
689                                 double min_elev = SGMiscd::min(itm_elev[last2+1] + clutter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
690                                 double d1 = j * itm_elev[1];
691                                 if ( (itm_elev[last2+1] + clutter_height) > (itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) { 
692                                         d1 = (num_points_3rd - j) * itm_elev[1];
693                                 }
694                                 double ray_height = (grad * d1) + min_elev;
695                                 
696                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
697                                 double intrusion = fabs(clearance);
698                                 
699                                 if (clearance >= 0) {
700                                         // no losses
701                                 }
702                                 else if (clearance < 0 && (intrusion < clutter_height)) {
703                                         
704                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
705                                 }
706                                 else if (clearance < 0 && (intrusion > clutter_height)) {
707                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
708                                 }
709                                 else {
710                                         // no losses
711                                 }
712                                 j++;
713                                 mat++;
714                                 
715                         }
716                         
717                 }
718         }
719         else if (p_mode == 2) {         //      troposcatter: ignore ground clutter for now...
720                 clutter_loss = 0.0;
721         }
722         
723 }
724
725 /***    Temporary material properties database
726 *               height: median clutter height
727 *               density: radiowave attenuation factor
728 ***/
729 void FGRadioTransmission::get_material_properties(string mat_name, double &height, double &density) {
730         
731         if(mat_name == "Landmass") {
732                 height = 15.0;
733                 density = 0.2;
734         }
735
736         else if(mat_name == "SomeSort") {
737                 height = 15.0;
738                 density = 0.2;
739         }
740
741         else if(mat_name == "Island") {
742                 height = 15.0;
743                 density = 0.2;
744         }
745         else if(mat_name == "Default") {
746                 height = 15.0;
747                 density = 0.2;
748         }
749         else if(mat_name == "EvergreenBroadCover") {
750                 height = 20.0;
751                 density = 0.2;
752         }
753         else if(mat_name == "EvergreenForest") {
754                 height = 20.0;
755                 density = 0.2;
756         }
757         else if(mat_name == "DeciduousBroadCover") {
758                 height = 15.0;
759                 density = 0.3;
760         }
761         else if(mat_name == "DeciduousForest") {
762                 height = 15.0;
763                 density = 0.3;
764         }
765         else if(mat_name == "MixedForestCover") {
766                 height = 20.0;
767                 density = 0.25;
768         }
769         else if(mat_name == "MixedForest") {
770                 height = 15.0;
771                 density = 0.25;
772         }
773         else if(mat_name == "RainForest") {
774                 height = 25.0;
775                 density = 0.55;
776         }
777         else if(mat_name == "EvergreenNeedleCover") {
778                 height = 15.0;
779                 density = 0.2;
780         }
781         else if(mat_name == "WoodedTundraCover") {
782                 height = 5.0;
783                 density = 0.15;
784         }
785         else if(mat_name == "DeciduousNeedleCover") {
786                 height = 5.0;
787                 density = 0.2;
788         }
789         else if(mat_name == "ScrubCover") {
790                 height = 3.0;
791                 density = 0.15;
792         }
793         else if(mat_name == "BuiltUpCover") {
794                 height = 30.0;
795                 density = 0.7;
796         }
797         else if(mat_name == "Urban") {
798                 height = 30.0;
799                 density = 0.7;
800         }
801         else if(mat_name == "Construction") {
802                 height = 30.0;
803                 density = 0.7;
804         }
805         else if(mat_name == "Industrial") {
806                 height = 30.0;
807                 density = 0.7;
808         }
809         else if(mat_name == "Port") {
810                 height = 30.0;
811                 density = 0.7;
812         }
813         else if(mat_name == "Town") {
814                 height = 10.0;
815                 density = 0.5;
816         }
817         else if(mat_name == "SubUrban") {
818                 height = 10.0;
819                 density = 0.5;
820         }
821         else if(mat_name == "CropWoodCover") {
822                 height = 10.0;
823                 density = 0.1;
824         }
825         else if(mat_name == "CropWood") {
826                 height = 10.0;
827                 density = 0.1;
828         }
829         else if(mat_name == "AgroForest") {
830                 height = 10.0;
831                 density = 0.1;
832         }
833         else {
834                 height = 0.0;
835                 density = 0.0;
836         }
837         
838 }
839
840 /*** implement simple LOS propagation model (WIP)
841 ***/
842 double FGRadioTransmission::LOS_calculate_attenuation(SGGeod pos, double freq, int transmission_type) {
843         double frq_mhz;
844         if( (freq < 118.0) || (freq > 137.0) )
845                 frq_mhz = 125.0;        // sane value, middle of bandplan
846         else
847                 frq_mhz = freq;
848         double dbloss;
849         double tx_pow = _transmitter_power;
850         double ant_gain = _antenna_gain;
851         double signal = 0.0;
852         double ATC_HAAT = 30.0;
853         double Aircraft_HAAT = 5.0;
854         double sender_alt_ft,sender_alt;
855         double transmitter_height=0.0;
856         double receiver_height=0.0;
857         double own_lat = fgGetDouble("/position/latitude-deg");
858         double own_lon = fgGetDouble("/position/longitude-deg");
859         double own_alt_ft = fgGetDouble("/position/altitude-ft");
860         double own_alt= own_alt_ft * SG_FEET_TO_METER;
861         
862         if(transmission_type == 1)
863                 tx_pow = _transmitter_power + 6.0;
864
865         if((transmission_type == 1) || (transmission_type == 3))
866                 ant_gain = _antenna_gain + 3.0; //pilot plane's antenna gain + ground station antenna gain
867         
868         double link_budget = tx_pow - _receiver_sensitivity + ant_gain; 
869
870         //cerr << "ITM:: pilot Lat: " << own_lat << ", Lon: " << own_lon << ", Alt: " << own_alt << endl;
871         
872         SGGeod own_pos = SGGeod::fromDegM( own_lon, own_lat, own_alt );
873         
874         SGGeod sender_pos = pos;
875         
876         sender_alt_ft = sender_pos.getElevationFt();
877         sender_alt = sender_alt_ft * SG_FEET_TO_METER;
878         
879         receiver_height = own_alt;
880         transmitter_height = sender_alt;
881         
882         double distance_m = SGGeodesy::distanceM(own_pos, sender_pos);
883         
884         if(transmission_type == 1) 
885                 transmitter_height += ATC_HAAT;
886         else
887                 transmitter_height += Aircraft_HAAT;
888         
889         /** radio horizon calculation with wave bending k=4/3 */
890         double receiver_horizon = 4.12 * sqrt(receiver_height);
891         double transmitter_horizon = 4.12 * sqrt(transmitter_height);
892         double total_horizon = receiver_horizon + transmitter_horizon;
893         
894         if (distance_m > total_horizon) {
895                 return -1;
896         }
897         
898         // free-space loss (distance calculation should be changed)
899         dbloss = 20 * log10(distance_m) +20 * log10(frq_mhz) -27.55;
900         signal = link_budget - dbloss;
901         SG_LOG(SG_GENERAL, SG_BULK,
902                         "LOS:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm ");
903         //cerr << "LOS:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm " << endl;
904         return signal;
905         
906 }
907
908