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