File: TextureGrWnd.cpp

package info (click to toggle)
descent3 1.5.0%2Bds-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid
  • size: 35,256 kB
  • sloc: cpp: 416,147; ansic: 3,233; sh: 10; makefile: 8
file content (1683 lines) | stat: -rw-r--r-- 50,423 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
/*
* Descent 3
* Copyright (C) 2024 Parallax Software
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.

--- HISTORICAL COMMENTS FOLLOW ---

 * $Logfile: /DescentIII/Main/editor/TextureGrWnd.cpp $
 * $Revision: 1.1.1.1 $
 * $Date: 2003-08-26 03:57:39 $
 * $Author: kevinb $
 *
 * Texture view of mine.
 *
 * $Log: not supported by cvs2svn $
 *
 * 122   9/30/99 6:35p Matt
 * Added code to scale the UVs of a texture based on the size of the
 * texture when the texture is applied to a face.  This will cause the
 * applied texture to have the make 3D texel size at the old texture.
 *
 * 121   4/22/99 11:41a Jason
 * fixed right clicking problem (temp fix)
 *
 * 120   4/19/99 6:55p Jason
 * fixed satellite grabbing problem
 *
 * 119   4/18/99 10:55p Chris
 * Added ignore own concussive blasts
 *
 * 118   4/18/99 5:42a Chris
 * Added the FQ_IGNORE_RENDER_THROUGH_PORTALS flag
 *
 * 117   4/15/99 5:49p Chris
 * Fixed a bug with rendering the BOAPath nodes
 *
 * 116   4/14/99 3:13p Chris
 * Beginning to add BoaNode stuff
 *
 * 115   4/03/99 7:39p Matt
 * Don't allow player objects to be given names.
 *
 * 114   3/27/99 7:10p Matt
 * Strip leading & trailing spaces before check for duplicate names.
 *
 * 113   3/02/99 5:54p Jason
 * fixed right mouse clicking with opengl
 *
 * 112   3/01/99 10:39a Matt
 * Strip leading and trailing spaces from object, trigger, and room names
 * on level load and when the names are entered.
 *
 * 111   2/28/99 10:40p Matt
 * Check for name already in use when entering a name.
 *
 * 110   2/21/99 4:20p Matt
 * Added SoundSource objects (and reformatted parts of the object header
 * files).
 *
 * 109   2/19/99 12:04p Jason
 * took out sky band
 *
 * 108   2/17/99 7:06p Kevin
 *
 * 107   2/17/99 5:47p Dan
 * fixed dumb bug
 *
 * 106   2/17/99 1:05p Jason
 * revamped object/face/terrain selection code
 *
 * 105   2/10/99 5:49p Dan
 * fixed fog bug
 *
 * 104   2/09/99 12:25p Jason
 * fixed dumb bug
 *
 * 103   2/09/99 12:16p Jason
 * fixed postrender problem
 *
 * 102   2/09/99 11:36a Dan
 * error checking (m_last_start_rooom invalid, initialized it) Samir
 *
 * 101   2/09/99 9:59a Chris
 * Quick compile patch and changed code to use BOA_IsVisible()
 *
 * 100   2/08/99 6:39p Jason
 * first pass at new indoor engine
 *
 * 99    2/03/99 1:10p Matt
 * Changed the paletted room current faces to be stored in a seperate
 * array, instead of in the room structure.
 *
 * 98    2/01/99 5:47p Nate
 * Implemented Editing/Adding of Dallas Scripts
 *
 * 97    2/01/99 4:24p Matt
 * Added Edit Script and New Script (though they don't do anything yet) to
 * object right-click dialog, and deleted Copy UID and Properties.
 *
 * 96    1/27/99 1:20p Jason
 * made r key rotate the terrain texture
 *
 * 95    1/24/99 12:37a Jeff
 * removed compile warnings
 *
 * 94    1/22/99 8:54p Jeff
 * added custom-default script overrides
 *
 * 93    1/22/99 3:59p Jason
 * added 256x256 textures to help with terrain skies
 *
 * 92    1/20/99 10:50a Jason
 * added new terrain
 *
 * 91    1/08/99 2:56p Samir
 * Ripped out OSIRIS1.
 *
 * 90    12/22/98 2:05p Matt
 * Mark the world as changed when an object name is changed.
 *
 * 89    12/21/98 11:30p Matt
 * Added names for objects
 *
 * 88    10/22/98 10:33a Sean
 * fixed windowed opengl lighting
 *
 * 87    10/18/98 2:06p Matt
 * Bail out of FindRoomFace if the starting room isn't in use any more.
 * This can happen if you click on the texture window after loading a
 * level or doing a New but before the new level has a chance to render.
 *
 * 86    10/06/98 12:27p Sean
 * More state changes
 *
 * 85    10/06/98 11:29a Jason
 * fixed state limited WindowGL
 *
 * 84    10/02/98 5:31p Jason
 * tweaks for statelimited stuff
 *
 * 83    10/02/98 4:24p Jason
 * more attempts to fix Riva128 opengl stuttering
 *
 * 82    10/02/98 4:22p Jason
 * made multipass turn off for gl rendering
 *
 * 81    10/01/98 10:39a Luke
 * FROM JASON: Attempted to fix GL problem....
 *
 * 80    9/30/98 10:25a Jason
 * another attempt to the get the OpenGL window thing working reliably...
 *
 * 79    9/18/98 1:27p Jason
 * cleaned up renderer initting
 *
 * 78    8/15/98 5:04p Matt
 * Added code to copy a texture & UVs from one face to another
 *
 * 77    7/21/98 12:04p Jason
 * V key now tells if the marked room and current room can see each other
 *
 * 76    6/16/98 3:04p Jason
 * fixed framecount bug
 *
 * 75    6/10/98 12:23p Jason
 * added new skies
 *
 * 74    6/09/98 6:16p Jason
 * added some features for windowed opengl
 *
 * 73    6/09/98 4:47p Jason
 * added windowed openGL mode
 *
 * 72    6/04/98 6:16p Jason
 * added terrain occlusion system
 *
 * 71    5/26/98 7:01p Samir
 * new script selection technique that knows what list of scripts to
 * choose from for an object.
 *
 * 70    5/04/98 3:23p Samir
 * only select custom scripts for right clicking.
 *
 * 69    5/01/98 3:51p Jason
 * sped up terrain rendering by precaching all megacell lod bitmaps
 *
 * 68    5/30/98 10:16p Chris
 * Fixed some bad spelling
 *
 * 67    4/21/98 2:43p Matt
 * Added system to disable render updates while deleting large numbers of
 * rooms, since the mine is not stable until this operation is done.
 *
 * 66    4/21/98 12:16a Samir
 * Hopefully if you change script definition, it's reflected as you edit
 * it.
 *
 * 65    4/16/98 10:42a Matt
 * Made texture propagation work across rooms.
 *
 * 64    3/12/98 7:30p Chris
 * Added ObjSetOrient
 *
 * 63    3/02/98 4:03p Samir
 * Simplied script editing and selection code.
 *
 * 62    2/25/98 4:06p Samir
 * Isolated parameter passing data functions.
 *
 * 61    2/24/98 1:50p Jason
 * added V key to check distance from plane for vertices
 *
 * 60    2/10/98 12:25p Samir
 * m_StartFlip should be rest when flip begins.
 *
 * 59    2/10/98 10:48a Matt
 * Moved editor code from gamepath.cpp to epath.cpp
 *
 * 58    2/09/98 6:06p Matt
 * Made Render_all_external_rooms not affect Room View
 *
 * 57    1/30/98 6:05p Matt
 * Use new function to set current editor object
 *
 * 56    1/26/98 6:31p Chris
 * User define paths now render in mine and terrain views
 *
 * 55    1/26/98 4:33p Samir
 * Added ability to copy object ids.
 *
 * 54    1/23/98 3:06p Samir
 * Script selection with parameters.
 *
 * 53    1/20/98 4:12p Samir
 * New script housekeeping system.
 *
 * 52    1/19/98 6:20p Samir
 * Rightclicking brings up menu in terrain.
 *
 * 51    1/16/98 12:41p Matt
 * Took out old debug/test code
 *
 * 50    1/15/98 12:42p Jason
 * big fix for terrain sky rendering
 *
 * 49    1/07/98 4:19p Jason
 * added dome to terrain sky
 *
 * 48    1/06/98 1:27p Matt
 * Cleaned up interfaces to rendering routines, deleted unused code, etc.
 *
 * 47    1/02/98 6:40p Matt
 * User renderer library (instead of viewport) functions to draw lines and
 * to set and read pixels.  Also made FindRoomFace() work without
 * Render_viewport.
 *
 * 46    12/29/97 5:44p Samir
 * Took out references to grViewport and old 2d library.
 *
 * 45    12/19/97 12:29p Samir
 * Oops.
 *
 * 44    12/19/97 11:25a Samir
 * g3_StartFrame and g3_EndFrame replaced by EditorStartFrame and
 * EditorEndFrame
 *
 * 43    12/17/97 5:26p Jason
 * added support for selectable wraparound sky
 *
 * 42    12/01/97 4:20p Jason
 * shadow and lighting changes
 *
 * 41    11/21/97 5:33p Jason
 * print light value when clicking on terrain cell
 *
 * 40    11/17/97 8:33p Jason
 * fixed bug with object selection introduced by last rev
 *
 * 39    11/17/97 6:13p Mark
 * allowed object 0 to be selected
 *
 * 38    11/03/97 7:02p Matt
 * Added better warning message
 *
 * 37    10/31/97 12:14p Jason
 * do a texture screen update after placing a new satellite image
 *
 * 36    9/30/97 2:12p Samir
 * Fully implemeted the Object Script Properties dialog.
 *
 * 35    9/22/97 6:18p Matt
 * Removed include of stub.h
 *
 * 34    9/17/97 1:00p Samir
 * Took out Room_engine and all segment references I could find.
 *
 * 33    9/16/97 6:32p Jason
 * made texture selection on terrain print relevant info
 *
 * 32    9/06/97 3:21p Matt
 * Reset cur portal when room changes
 *
 * 31    9/03/97 8:00p Samir
 * Implemented most of the fixes for the object moving system.
 *
 * 30    9/02/97 2:17p Samir
 * Move objects in Terrain now.
 *
 * 29    8/29/97 1:51p Samir
 * When mouse down in an object, invoke ObjectMoveManager
 *
 * 28    8/28/97 11:53a Matt
 * Don't try to propagate from a face to itself
 *
 * 27    8/27/97 5:19p Jason
 * made ShowRadProgress fill the entire texture window
 *
 * 26    8/26/97 4:37p Jason
 * added floating point hemicube rasterizer, plus "heat" visualization
 *
 * 25    8/22/97 10:16a Matt
 * When change curroom & curface, reset curvert & curedge also
 *
 * 24    8/22/97 10:15a Jason
 * Added error checking to ShowRadView
 *
 * 23    8/18/97 5:57p Jason
 * made radiosity better
 *
 * 22    8/01/97 4:53p Jason
 * made a more general PropagateTextureToFace function call
 *
 * 21    7/29/97 12:07p Matt
 * Took out texturing in room view, & made selecting a face in room view
 * not change the global current room/face
 *
 * 20    7/24/97 6:11p Matt
 * Created symbolic constant for default zoom, and used it every place
 * that specifies zoom
 *
 * 19    7/22/97 7:08p Matt
 * Cleaned up D3EditState, moving some vars in and some out, and renaming
 * and changing a few others
 *
 * 18    7/20/97 7:37p Jason
 * added new sky
 *
 * 17    7/18/97 5:49p Jason
 * flag room changed is you change it
 *
 * 16    7/17/97 3:00p Jason
 * changed "moons" to be called satellites since we're going to have suns
 * and other things in orbit
 *
 *
 * 15    7/16/97 5:20p Jason
 * implemented selection of moons with mouse click
 *
 * 14    7/16/97 4:07p Jason
 * fixed all the remaining drop-out bugs
 *
 * 13    7/15/97 4:19p Jason
 * added object focus for terrain
 *
 * 39    6/30/97 3:54p Jeff
 * Add object properties dialog
 *
 * 38    6/30/97 2:31p Jason
 * took out room rendering from the mine-segment rendering loop
 *
 * 37    6/30/97 1:30p Jason
 * added netherspace stuff
 *
 * 36    6/30/97 12:33p Jeff
 * Added message map and support for right-click popup menu
 *
 * 35    6/30/97 11:34a Jeff
 *
 * 34    6/27/97 5:19p Jeff
 *
 * 33    6/27/97 2:49p Jason
 * added hacked way to change textures for rooms (temporary)
 *
 * 32    6/26/97 4:55p Jason
 * fixed dumb bug
 *
 * 31    6/26/97 4:45p Jason
 * added control_right_click function for box selection
 *
 * 30    6/26/97 4:06p Jason
 * no collision detection if Flat_terrain is set
 *
 * 29    6/25/97 5:30p Jason
 * added code to readin/display a room
 *
 * 28    6/06/97 4:57p Jason
 * more nifty megacell/tmap2 features
 *
 * 27    6/06/97 4:33p Jason
 * added cool stuff for megacells
 *
 * 26    6/05/97 6:58p Jason
 * added more megacell functionality
 *
 * 25    5/22/97 5:15p Jason
 * added tmap2 capability to the terrain
 *
 * 24    5/15/97 3:28a Jason
 * tried to get subwindow clearing to work with terrain - but it won't
 * until samir fixes lock_clear
 *
 * 23    5/08/97 7:46p Matt
 * Added called_from_terrain parm for RenderMine()
 *
 * 22    5/08/97 6:43p Jason
 * added support for terrain/mine reentry handling
 *
 * 21    5/05/97 4:47p Jason
 * made terrain and mine rendering work without explicit calls to
 * g3_Startframe in their main function calls
 * This allows us to integrate mine/terrain engines nicely
 *
 * 20    4/09/97 2:00p Jason
 * moved DrawAllPaths function to gamepath where it belongs
 *
 * 19    4/08/97 10:42a Jason
 * implemented path following interface
 *
 * 18    4/02/97 3:24p Jason
 * changed Viewer_moved back to TV_changed because it didn't do what I
 * thought it would do, namely only update the textured view!
 *
 * 17    4/02/97 2:48p Jason
 * changed TV_changed to viewer move to reforce drawing of textured view,
 * but not wireframe
 *
 * 16    3/31/97 5:58p Matt
 * Revamped mine update flags
 *
 * 15    3/20/97 11:55a Jason
 * changes for terrain editing/drawing
 *
 * 14    3/07/97 4:18p Jason
 * implemented terrain functionality in the editor
 *
 * 13    2/28/97 9:35a Matt
 * Added code to select objects by clicking on them in the texture window.
 *
 * 12    2/27/97 4:26p Matt
 * Fixed curseg selection status messages
 *
 * 11    2/26/97 7:35p Samir
 * Moved TextureGrWnd.h after stdafx.h to get rid of warning and errors.
 *
 * 10    2/20/97 5:37p Samir
 * SHIFT + LEFTBUTTONDOWN = Apply texture.
 *
 * 9     2/19/97 11:06a Samir
 * Only flip screen if we rendered but did not hit the left button down
 * key to prevent green screen flash.
 *
 * 8     2/18/97 7:57p Matt
 * Added code to select a segment by clicking on it in the texture-mapped
 * window
 *
 * 7     2/03/97 8:01p Matt
 * New name and parms for render function
 *
 * 6     2/03/97 5:20p Samir
 * Added gr.h header
 *
 * 5     1/30/97 6:25p Samir
 * Implemented a non-working caption bar system and made some changes for
 * Jason.
 *
 * 4     1/23/97 4:56p Samir
 * Handles saving screen positions of windows and tileability.
 *
 * 3     1/21/97 12:42p Samir
 * Floatable-resizable views
 *
 * $NoKeywords: $
 */

#include "stdafx.h"

#include "TextureGrWnd.h"

#include "application.h"
#include "editor.h"
#include "render.h"
#include "manage.h"
#include "gr.h"
#include "boa.h"
#include "gameloop.h"
#include "descent.h"
#include "terrain.h"
#include "HTexture.h"
#include "terraindialog.h"
#include "room.h"
#include "roomuvs.h"
#include "mainfrm.h"
#include <string.h>
#include "ObjMoveManager.h"
#include "lightmap_info.h"
#include "lightmap.h"
#include "EditLineDialog.h"
#include "CustDefaultScriptSelect.h"
#include "erooms.h"
#include "ebnode.h"

#include <assert.h>

#include "mono.h"
#include "3d.h"
#include "gr.h"
#include "ddio.h"
#include "epath.h"
#include "megacell.h"
#include "ObjectPropertiesDialog.h"
#include "ObjectClipboard.h"
#include "radiosity.h"
#include "hemicube.h"
#include "args.h"
#include "game.h"
#include "DallasMainDlg.h"
#include "postrender.h"
#include "SoundSourceDialog.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

// These defines are for the right-click popup menu
#define POPUP_PROPERTIES 0x60
#define POPUP_DELETE 0x61
#define POPUP_PASTE 0x62
#define POPUP_CUT 0x63
#define POPUP_COPY 0x64
#define POPUP_COPYID 0x66
#define POPUP_OBJNAME 0x69
#define POPUP_EDITNAME 0x6a
#define POPUP_CUSTOMDEFAULTSCRIPT 0x6b
#define POPUP_EDITSCRIPT 0x6c
#define POPUP_NEWSCRIPT 0x6d
#define POPUP_SOUND 0x6e

grViewport *rad_Viewport;
static int DoOpenGL = 0;

/////////////////////////////////////////////////////////////////////////////
// CTextureGrWnd

CTextureGrWnd::CTextureGrWnd() : CGrWnd("TextureScreen") {
  m_StartFlip = FALSE;
  m_last_start_room = -1;
}

CTextureGrWnd::~CTextureGrWnd() {}

BEGIN_MESSAGE_MAP(CTextureGrWnd, CWnd)
//{{AFX_MSG_MAP(CTextureGrWnd)
ON_WM_SIZE()
ON_WM_PAINT()
ON_WM_DESTROY()
ON_WM_MOVE()
ON_WM_CREATE()
ON_WM_SYSCOMMAND()
ON_WM_NCACTIVATE()
ON_WM_NCPAINT()
ON_WM_LBUTTONDOWN()
ON_WM_MOUSEMOVE()
ON_WM_RBUTTONDOWN()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

void DrawPlayerOnWireframe();

bool Disable_editor_rendering = 0;
static int first_time = 1;

extern int Just_returned_from_game;
extern float Just_returned_time;
int Successive_count = 0;

HWND save_wnd;
oeLnxApplication *app;

void CTextureGrWnd::TexGrStartOpenGL() {
  if (DoOpenGL) {
    app = (oeLnxApplication *)Descent;
    StateLimited = 1;
    // TODO - hwnd from SDL windows
    // save_wnd = (HWND)app->m_hWnd;
    // app->m_hWnd = (HWnd)m_hWnd;
    // rend_SetOpenGLWindowState (1,Descent,NULL); // LGT: not defined anymore
    rend_ClearScreen(0);
    StateLimited = 1;
    UseMultitexture = 0;
    NoLightmaps = false;
  }
}

void CTextureGrWnd::TexGrStopOpenGL() {
  if (DoOpenGL) {
    // rend_SetOpenGLWindowState (0,Descent,NULL); // LGT: not defined anymore
    // TODO - hwnd from SDL windows
    // app->m_hWnd = (HWnd)save_wnd;
  }
}

void CTextureGrWnd::Render() {
  if (first_time) {
    first_time = 0;
    if (FindArg("-WindowGL"))
      DoOpenGL = 1;
  }

  if (DoOpenGL) {
    if (Just_returned_from_game) {
      Successive_count++;
      if (Successive_count < 2) {
        mprintf(0, "Not doing opengl!\n");
        DoOpenGL = 0;
        first_time = 1;
      } else {
        Just_returned_from_game = 0;
        Successive_count = 0;
      }
    }
  }

  if (Disable_editor_rendering)
    return;

  FrameCount++;

  if (m_grScreen == NULL)
    return;
  if (m_grViewport == NULL)
    return;

  rad_Viewport = m_grViewport;

  TexGrStartOpenGL();

  ResetPostrenderList();
  // Reset fog
  Num_fogged_rooms_this_frame = 0;
  if (Editor_view_mode == VM_ROOM) {
    if ((D3EditState.current_room == -1) || (Rooms[D3EditState.current_room].used < 1)) {
      TexGrStopOpenGL();
      return;
    }

    // Disable render-all-rooms in room view
    bool save_RAER = Render_all_external_rooms;
    Render_all_external_rooms = 0;

    // Render
    TGWRenderMine(&Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM, D3EditState.current_room);

    // Restore render-all-rooms state
    Render_all_external_rooms = save_RAER;
  } else if (Editor_view_mode == VM_TERRAIN) {

    if (GetFunctionMode() == EDITOR_MODE) {
      DrawPlayerOnWireframe();
      if (!Flat_terrain && (Viewer_object->pos.y < GetTerrainGroundPoint(&Viewer_object->pos) + 5))
        Viewer_object->pos.y = GetTerrainGroundPoint(&Viewer_object->pos) + 5;
    }

    StartEditorFrame(m_grViewport, &Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM);
    RenderTerrain(0);
    //	we need to save these for object movement.
    g3_GetViewPosition(&m_ViewPos);
    g3_GetViewMatrix(&m_ViewMatrix);
    EndEditorFrame();

    if (KEY_STATE(KEY_X)) {
      vector pos;
      float yval;

      ComputeTerrainSegmentCenter(&pos, (128 * TERRAIN_WIDTH) + 128);
      yval = GetTerrainGroundPoint(&pos);

      pos.y = yval;
      Viewer_object->pos = pos;
      ObjSetOrient(Viewer_object, &Identity_matrix);
      World_changed = 1;
    }
  } else // Mine view
  {
    TGWRenderMine(&Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM, Viewer_object->roomnum);
  }

  PostRender(Viewer_object->roomnum);

  // Draws all User Defined Paths
  DrawAllPaths(m_grViewport, &Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM);
  EBNode_Draw(EBN_draw_type, m_grViewport, &Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM);

  TexGrStopOpenGL();

  m_StartFlip = TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CTextureGrWnd message handlers

BOOL CTextureGrWnd::Create(RECT &rect, BOOL movable, CWnd *pParent) {
  RECT new_rect;
  DWORD dwstyle;

  dwstyle = (movable ? GRWND_STYLE : GRWND_STATIC_STYLE);

  ::CopyRect(&new_rect, &rect);
  ::AdjustWindowRect(&new_rect, dwstyle, FALSE);

  //	We want this window to start at rect.left, rect.top.
  if (new_rect.left < rect.left) {
    int offx;
    offx = rect.left - new_rect.left;
    new_rect.left += offx;
    new_rect.right += offx;
  }
  if (new_rect.top < rect.top) {
    int offy;
    offy = rect.top - new_rect.top;
    new_rect.top += offy;
    new_rect.bottom += offy;
  }

  ::CopyRect(&rect, &new_rect);

  m_grCreated = TRUE;
  m_Movable = movable;

  lstrcpy(m_Name, "Texture");

  ObjectInBuffer = false;

  return CWnd::Create(NULL, m_Name, dwstyle, rect, pParent, IDC_TEXTURE_WND);
}

void CTextureGrWnd::OnSize(UINT nType, int cx, int cy) {
  RECT rect;
  char text[32];

  CGrWnd::OnSize(nType, cx, cy);

  if (m_Movable) { // don't define these if this box is static
    D3EditState.texscr_w = cx;
    D3EditState.texscr_h = cy;
  }

  GetClientRect(&rect);
  sprintf(text, "Texture (%dx%d)", rect.right - rect.left, rect.bottom - rect.top);
  lstrcpy(m_Name, text);
  SetWindowText(m_Name);
}

void CTextureGrWnd::OnPaint() {
  CPaintDC dc(this); // device context for painting

  //	Draw what's on the screen back page to the desktop
  if (theApp.paused())
    return;

  if (m_StartFlip) { // do if a flip was signaled
    m_StartFlip = FALSE;

    if (DoOpenGL) {
      HWND save_wnd;
      oeLnxApplication *app;

      app = (oeLnxApplication *)Descent;

      // save_wnd = (HWND)app->m_hWnd;
      // app->m_hWnd = (HWnd)m_hWnd;
      // rend_SetOpenGLWindowState (1,Descent,NULL);  // LGT: not defined anymore

      rend_Flip();

      // rend_SetOpenGLWindowState (0,Descent,NULL);  // LGT: not defined anymore
      // app->m_hWnd = (HWnd)save_wnd;
    } else {
      m_grScreen->flip();
      m_grViewport->clear();
    }
  }

  // Do not call CWnd::OnPaint() for painting messages
  if (!m_Movable) { // print out window title, since there is no caption
    dc.SetBkMode(TRANSPARENT);
    dc.SetTextColor(RGB(192, 192, 192));
    dc.TextOut(10, 10, m_Name, lstrlen(m_Name));
    //		m_grViewport->puts(10,10, m_Name);
  }
}

void CTextureGrWnd::OnDestroy() {
  //	mprintf(0, "CTextureGrWnd::OnDestroy:: m_grScreen\n");
  CGrWnd::OnDestroy();
  theApp.textured_view = NULL;
}

void CTextureGrWnd::OnMove(int x, int y) {
  CGrWnd::OnMove(x, y);

  //	Must do this to adjust window rect to view's client.
  if (m_Movable) {
    RECT rect;
    GetWindowRect(&rect);
    GetParent()->ScreenToClient(&rect);
    D3EditState.texscr_x = rect.left;
    D3EditState.texscr_y = rect.top;
  }
}

int CTextureGrWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) {
  if (CGrWnd::OnCreate(lpCreateStruct) == -1)
    return -1;

  // TODO: Add your specialized creation code here
  theApp.textured_view = this;

  return 0;
}

void CTextureGrWnd::OnSysCommand(UINT nID, LPARAM lParam) {
  // TODO: Add your message handler code here and/or call default
  //	take care of 'close' box for one thing

  switch (nID) {
  case SC_CLOSE:
    D3EditState.texscr_visible = 0;
    break;
  }

  CWnd::OnSysCommand(nID, lParam);
}

BOOL CTextureGrWnd::OnNcActivate(BOOL bActive) {
  // TODO: Add your message handler code here and/or call default

  return CGrWnd::OnNcActivate(bActive);
}

void CTextureGrWnd::OnNcPaint() { CGrWnd::OnNcPaint(); }

int Tracing_drops = 0;
int Drop_seg = 0;

int CTextureGrWnd::TGWFindRoomFace(int x, int y, int *roomnum, int *facenum) {
  /*if (m_last_start_room == -1)
          return 0;
  if (! Rooms[m_last_start_room].used)
          return 0;

  int ret;

  StartEditorFrame(m_grViewport,&m_last_viewer_eye,&m_last_viewer_orient,m_last_zoom);

  ret = FindRoomFace(x,y,m_last_start_room,roomnum,facenum);
  PostRender(Viewer_object->roomnum);

  EndEditorFrame();*/

  return 0;
}

int CTextureGrWnd::TGWFindLightmapFace(int x, int y, int *roomnum, int *facenum, int *lumel_num) {
  /*if (! Rooms[m_last_start_room].used)
          return 0;

  int ret;

  StartEditorFrame(m_grViewport,&m_last_viewer_eye,&m_last_viewer_orient,m_last_zoom);

  ret = FindLightmapFace(x,y,m_last_start_room,roomnum,facenum,lumel_num);

  EndEditorFrame();*/

  return 0;
}

void CTextureGrWnd::TGWRenderMine(vector *pos, matrix *orient, float zoom, int start_roomnum) {
  if (start_roomnum < 0 || start_roomnum > MAX_ROOMS + MAX_PALETTE_ROOMS)
    return;

  // save these vars for possible use by FindRoomFace()
  m_last_viewer_eye = *pos;
  m_last_viewer_orient = *orient;
  m_last_zoom = zoom;
  m_last_start_room = start_roomnum;

  StartEditorFrame(m_grViewport, pos, orient, zoom);
  FrameCount++;

  RenderMine(start_roomnum, 0, 0);
  PostRender(Viewer_object->roomnum);

  //	we need to save these for object movement.
  g3_GetViewPosition(&m_ViewPos);
  g3_GetViewMatrix(&m_ViewMatrix);

  EndEditorFrame();
}

// Set the current object
void SelectObject(int objnum);

void CTextureGrWnd::OnLButtonDown(UINT nFlags, CPoint point) {
  TexGrStartOpenGL();

  ResetPostrenderList();

  if (Editor_view_mode == VM_ROOM) {
    TSearch_found_type = -1;
    TSearch_seg = -1;
    TSearch_on = 1;
    TSearch_x = point.x;
    TSearch_y = point.y;

    TGWRenderMine(&Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM, Viewer_object->roomnum);

    TSearch_on = 0;

    if (TSearch_found_type == TSEARCH_FOUND_MINE) {
      Current_faces[TSearch_seg - FIRST_PALETTE_ROOM] = TSearch_face;
      EditorStatus("Face %d selected.", TSearch_face);
      State_changed = 1;
      return;
    }
  } else if (Editor_view_mode == VM_TERRAIN) {
    TSearch_found_type = -1;
    TSearch_seg = -1;
    TSearch_on = 1;
    TSearch_x = point.x;
    TSearch_y = point.y;

    StartEditorFrame(m_grViewport, &Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM);
    RenderTerrain(0);
    PostRender(Viewer_object->roomnum);
    EndEditorFrame();
    TSearch_on = 0;
    if (TSearch_found_type != -1) {

      // Check for objects
      if (TSearch_found_type == TSEARCH_FOUND_OBJECT) {
        // Found an object
        mprintf(0, "Found an object! objnum=%d\n", TSearch_seg);
        SelectObject(TSearch_seg);
        // start object moving if mouse down in an object.
        ObjMoveManager.Start(this, m_grViewport->width(), m_grViewport->height(), &m_ViewPos, &m_ViewMatrix, point.x,
                             point.y);
      }

      if (TSearch_found_type == TSEARCH_FOUND_SKY_DOME) {
        if (nFlags & MK_SHIFT) {
          Terrain_sky.dome_texture = D3EditState.texdlg_texture;

          World_changed = 1;
          TV_changed = 1;
        }
      }

      // Check for satellite
      if (TSearch_found_type == TSEARCH_FOUND_SATELLITE) {
        if (nFlags & MK_SHIFT) {
          Terrain_sky.satellite_texture[TSearch_seg] = D3EditState.texdlg_texture;
          theApp.main_frame->m_TerrainDialog->SetCurrentMoon(TSearch_seg);
          World_changed = 1;
          TV_changed = 1;
        }

        else {
          theApp.main_frame->m_TerrainDialog->SetCurrentMoon(TSearch_seg);
          if (KEY_STATE(KEY_G))
            D3EditState.texdlg_texture = Terrain_sky.satellite_texture[TSearch_seg];
        }
      }

      if (TSearch_found_type == TSEARCH_FOUND_TERRAIN) {
        if (KEY_STATE(KEY_P)) {
          Tracing_drops = 1;
          Drop_seg = TSearch_seg;
          Terrain_tex_seg[Terrain_seg[Drop_seg].texseg_index].tex_index = 0;
        } else if (KEY_STATE(KEY_R)) {
          // Rotate this texture
          int val = Terrain_tex_seg[Terrain_seg[TSearch_seg].texseg_index].rotation & 0x0F;
          val++;
          val %= 4;
          Terrain_tex_seg[Terrain_seg[TSearch_seg].texseg_index].rotation &= ~0x0F;
          Terrain_tex_seg[Terrain_seg[TSearch_seg].texseg_index].rotation |= val;

          TV_changed = 1;
        }

        if (nFlags & MK_SHIFT) {

          Terrain_tex_seg[Terrain_seg[TSearch_seg].texseg_index].tex_index = D3EditState.texdlg_texture;
          TV_changed = 1;
        } else if (nFlags & MK_CONTROL) {
          if (TerrainSelected[TSearch_seg]) {
            TerrainSelected[TSearch_seg] = 0;
            Num_terrain_selected--;
          } else {
            TerrainSelected[TSearch_seg] = 1;
            Num_terrain_selected++;
          }
          TV_changed = 1;
        } else {
          memset(TerrainSelected, 0, TERRAIN_WIDTH * TERRAIN_DEPTH);
          EditorStatus("Cell %d selected. Light=%d Height=%.2f (%d).  Texture=%s", TSearch_seg,
                       Terrain_seg[TSearch_seg].l, Terrain_seg[TSearch_seg].y, Terrain_seg[TSearch_seg].ypos,
                       GameTextures[Terrain_tex_seg[Terrain_seg[TSearch_seg].texseg_index].tex_index].name);
          TerrainSelected[TSearch_seg]++;
          Num_terrain_selected = 1;
          TV_changed = 1;
        }
      }
    }
  } else {
    int roomnum, facenum;

    //	mprintf(0,"ButtonDown %d,%d\n",point.x,point.y);
    TSearch_found_type = -1;
    TSearch_seg = -1;
    TSearch_on = 1;
    TSearch_x = point.x;
    TSearch_y = point.y;

    TGWRenderMine(&Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM, Viewer_object->roomnum);
    TSearch_on = 0;

    // this looks at the last frame rendered
    if (TSearch_found_type == TSEARCH_FOUND_OBJECT) {
      // Found a face or object
      m_StartFlip = FALSE; // unsignal flip.
      SelectObject(TSearch_seg);
      // start object moving if mouse down in an object.
      ObjMoveManager.Start(this, m_grViewport->width(), m_grViewport->height(), &m_ViewPos, &m_ViewMatrix, point.x,
                           point.y);
    } else if (TSearch_found_type == TSEARCH_FOUND_MINE) {
      roomnum = TSearch_seg;
      facenum = TSearch_face;

      if (nFlags & MK_SHIFT) { // apply current texture to face
        HTextureApplyToRoomFace(&Rooms[TSearch_seg], TSearch_face, D3EditState.texdlg_texture);
        EditorStatus("Texture %d applied to room %d face %d\n", D3EditState.texdlg_texture, TSearch_seg, TSearch_face);
        World_changed = 1;
      } else if (KEY_STATE(KEY_J)) // apply texture, scaling UVs based on texture size
      {
        int old_width = bm_w(GetTextureBitmap(Rooms[TSearch_seg].faces[TSearch_face].tmap, 0), 0);
        int new_width = bm_w(GetTextureBitmap(D3EditState.texdlg_texture, 0), 0);
        HTextureApplyToRoomFace(&Rooms[TSearch_seg], TSearch_face, D3EditState.texdlg_texture);
        ScaleFaceUVs(&Rooms[TSearch_seg], TSearch_face, (float)old_width / new_width);
        EditorStatus("Texture %d applied to room %d face %d\n", D3EditState.texdlg_texture, TSearch_seg, TSearch_face);
        World_changed = 1;
      } else if (KEY_STATE(KEY_P)) {
        // P + Click = Propagate from current face
        if ((TSearch_seg == ROOMNUM(Curroomp)) && (TSearch_face == Curface))
          EditorStatus("Cannot propagate from a face to itself.");
        else if (HTexturePropagateToFace(&Rooms[roomnum], facenum, Curroomp, Curface)) {
          EditorStatus("Texture propagated from %d:%d to %d:%d\n", ROOMNUM(Curroomp), Curface, roomnum, facenum);
          World_changed = 1;
        } else {
          OutrageMessageBox("Room:face %d:%d is not adjacent to Current room:face (%d:%d)", roomnum, facenum,
                            ROOMNUM(Curroomp), Curface);
          return;
        }
      } else if (KEY_STATE(KEY_E)) {
        // C + Click = Copy uv values from marked face
        static int last_copy_marked_room = -1, last_copy_marked_face = -1;
        static int last_copy_room = -1, last_copy_face = -1;
        static int count;

        if (Markedroomp == NULL) {
          OutrageMessageBox("You must have a marked face for this operation.");
          return;
        }

        if ((roomnum == ROOMNUM(Markedroomp)) && (facenum == Markedface))
          EditorStatus("Cannot copy from a face to itself.");
        else {
          if ((last_copy_marked_room == ROOMNUM(Markedroomp)) && (last_copy_marked_face == Markedface) &&
              (last_copy_room == roomnum) && (last_copy_face == facenum))
            count++;
          else {
            count = 0;
            last_copy_marked_room = ROOMNUM(Markedroomp);
            last_copy_marked_face = Markedface;
            last_copy_room = roomnum;
            last_copy_face = facenum;
          }

          if (HTextureCopyUVsToFace(&Rooms[roomnum], facenum, Markedroomp, Markedface, count)) {
            Rooms[roomnum].faces[facenum].tmap = Markedroomp->faces[Markedface].tmap;
            EditorStatus("Texture & UVs copied from %d:%d to %d:%d (rotation = %d/%d)\n", ROOMNUM(Markedroomp),
                         Markedface, roomnum, facenum, count % Markedroomp->faces[Markedface].num_verts,
                         Markedroomp->faces[Markedface].num_verts);
            World_changed = 1;
          } else
            EditorStatus("Can't copy UVs: faces don't have the same number of vertices.");
        }
      } else if (KEY_STATE(KEY_N)) {
        vector vec = Rooms[roomnum].verts[Rooms[roomnum].faces[facenum].face_verts[0]];
        vector norm = Rooms[roomnum].faces[facenum].normal;
        float plane_dist = -(vec.x * norm.x + vec.y * norm.y + vec.z * norm.z);
        int i;
        for (i = 0; i < Rooms[roomnum].faces[facenum].num_verts; i++) {
          vec = Rooms[roomnum].verts[Rooms[roomnum].faces[facenum].face_verts[i]];
          float dist = vec.x * norm.x + vec.y * norm.y + vec.z * norm.z + plane_dist;
          mprintf(0, "Vertex %d distance from plane=%f\n", i, dist);
        }
      } else if (KEY_STATE(KEY_V)) {
        // Do visibility check
        int rooma = (Markedroomp - Rooms);
        int roomb = (Curroomp - Rooms);
        int answer = BOA_IsVisible(rooma, roomb);

        mprintf(0, "Answer 1 is %d\n", answer);

        answer = BOA_IsVisible(roomb, rooma);

        mprintf(0, "Answer 2 is %d\n", answer);
      } else { // Just change curface
        State_changed = 1;
        EditorStatus("Current room:face set to %d:%d", roomnum, facenum);
      }

      // All clicks on face change the current face
      Curroomp = &Rooms[roomnum];
      Curface = facenum;
      Curedge = Curvert = 0;
      Curportal = -1;
    }
  }

  TexGrStopOpenGL();

  CWnd::OnLButtonDown(nFlags, point);
}

void CTextureGrWnd::OnMouseMove(UINT nFlags, CPoint point) { CWnd::OnMouseMove(nFlags, point); }

void CTextureGrWnd::OnRButtonDown(UINT nFlags, CPoint point) {
  int n = D3EditState.current_megacell;
  int newobjnum = -1;
  bool do_popup = false;

  TexGrStartOpenGL();

  if (Editor_view_mode == VM_TERRAIN) {
    TSearch_seg = -1;
    TSearch_on = 1;
    TSearch_x = point.x;
    TSearch_y = point.y;
    TSearch_found_type = -1;

    StartEditorFrame(m_grViewport, &Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM);
    RenderTerrain(0);
    PostRender(Viewer_object->roomnum);
    EndEditorFrame();
    TSearch_on = 0;
    if (TSearch_found_type == TSEARCH_FOUND_TERRAIN) {
      if (nFlags & MK_SHIFT) {
        int w = Megacells[n].width;
        int h = Megacells[n].height;

        for (int i = 0; i < h; i++) {
          for (int t = 0; t < w; t++) {
            int terrain_x = (TSearch_seg % TERRAIN_WIDTH) + t;
            int terrain_z = (TSearch_seg / TERRAIN_WIDTH) - i;
            int mx, my;

            if (terrain_x < 0 || terrain_x >= TERRAIN_WIDTH)
              continue;
            if (terrain_z < 0 || terrain_z >= TERRAIN_DEPTH)
              continue;

            if (D3EditState.randomize_megacell) {
              mx = rand() % w;
              my = rand() % h;
            } else {
              mx = t;
              my = i;
            }

            TV_changed = 1;
          }
        }
      }
      if (nFlags & MK_CONTROL) {
        int x, z, i, t;

        for (i = 0; i < TERRAIN_DEPTH * TERRAIN_WIDTH; i++) {
          if (TerrainSelected[i]) {
            x = i % TERRAIN_WIDTH;
            z = i / TERRAIN_WIDTH;

            break;
          }
        }

        if (i == TERRAIN_DEPTH * TERRAIN_WIDTH)
          return; // nothing to do!

        Num_terrain_selected = 0;
        memset(TerrainSelected, 0, TERRAIN_WIDTH * TERRAIN_DEPTH);

        int terrain_x = (TSearch_seg % TERRAIN_WIDTH);
        int terrain_z = (TSearch_seg / TERRAIN_WIDTH);

        int width = abs(terrain_x - x);
        int height = abs(terrain_z - z);
        int start_x = x;
        int start_z = z;

        if (terrain_x < x)
          start_x = terrain_x;
        if (terrain_z < z)
          start_z = terrain_z;

        for (i = 0; i <= height; i++)
          for (t = 0; t <= width; t++) {
            Num_terrain_selected++;
            TerrainSelected[((i + start_z) * TERRAIN_WIDTH) + start_x + t] = 1;
          }
      }
    }
    // Check for objects
    else if (TSearch_found_type == TSEARCH_FOUND_OBJECT) {
      newobjnum = TSearch_seg;
      do_popup = true;

      mprintf(0, "Found an object! objnum=%d\n", newobjnum);
      SelectObject(newobjnum);

      Render();
      RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
    }
  }
  // Code to put up popup menu when right clicking
  else {
    int roomnum, facenum;

    TSearch_found_type = -1;
    TSearch_seg = -1;
    TSearch_on = 1;
    TSearch_x = point.x;
    TSearch_y = point.y;

    TGWRenderMine(&Viewer_object->pos, &Viewer_object->orient, D3_DEFAULT_ZOOM, Viewer_object->roomnum);
    TSearch_on = 0;

    // this looks at the last frame rendered
    if (TSearch_found_type == TSEARCH_FOUND_MINE || TSearch_found_type == TSEARCH_FOUND_OBJECT) {
      roomnum = TSearch_seg;
      facenum = TSearch_face;
      m_StartFlip = FALSE; // unsignal flip.
      mprintf(0, "found point: %d %d %d\n", roomnum, facenum);

      do_popup = true;

      if (TSearch_found_type == TSEARCH_FOUND_OBJECT) { // found an object
        newobjnum = (roomnum);
        SelectObject(newobjnum);
      }
    }

    Render();
    RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
  }

  //	right click popup menu
  if (do_popup) {
    CMenu popup;
    bool ret = true;
    char *title = NULL;

    if (newobjnum > -1)
      title = Objects[newobjnum].name;

    if (popup.CreatePopupMenu())
      ret = SetupPopup(&popup, title);
    else {
      mprintf(0, "Warning: Could not create popup menu!\n");
      ret = false;
    }

    if (newobjnum > -1) {
      object *foundobj = &Objects[newobjnum];
      if (!ObjectInBuffer)
        popup.EnableMenuItem(POPUP_PASTE, MF_GRAYED);
      if (foundobj->control_type != CT_SOUNDSOURCE)
        popup.EnableMenuItem(POPUP_SOUND, MF_GRAYED);
    } else {
      popup.EnableMenuItem(POPUP_OBJNAME, MF_GRAYED);
      popup.EnableMenuItem(POPUP_EDITNAME, MF_GRAYED);
      popup.EnableMenuItem(POPUP_EDITSCRIPT, MF_GRAYED);
      popup.EnableMenuItem(POPUP_NEWSCRIPT, MF_GRAYED);
      popup.EnableMenuItem(POPUP_CUT, MF_GRAYED);
      popup.EnableMenuItem(POPUP_COPY, MF_GRAYED);
      popup.EnableMenuItem(POPUP_SOUND, MF_GRAYED);
      if (!ObjectInBuffer)
        popup.EnableMenuItem(POPUP_PASTE, MF_GRAYED);
      popup.EnableMenuItem(POPUP_DELETE, MF_GRAYED);
    }

    if (ret)
      if (!popup.TrackPopupMenu(TPM_LEFTALIGN, point.x, point.y + 20, this, NULL))
        mprintf(0, "TrackPopupMenu error!\n");
  }

  TexGrStopOpenGL();

  CWnd::OnRButtonDown(nFlags, point);
}

//=================
//	Sets up the popup menu for a right click
// Parameters:	popup: pointer to CMenu object
// Returns:	true if everything went ok
// Notes: The CMenu object must be initialized before sent to this function (use CreatePopupMenu())
//=================
bool CTextureGrWnd::SetupPopup(CMenu *popup, char *title) {
  bool ret;
  ret = true;

  if (!popup->AppendMenu(MF_STRING + MF_DISABLED, POPUP_OBJNAME, title ? title : "(no name)")) {
    ret = false;
    mprintf(0, "Warning: Could not add Title to popup\n");
  }
  if (!popup->AppendMenu(MF_SEPARATOR)) {
    ret = false;
    mprintf(0, "Warning: Could not add seperator to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_COPY, "Copy")) {
    ret = false;
    mprintf(0, "Warning: Could not add Copy to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_CUT, "Cut")) {
    ret = false;
    mprintf(0, "Warning: Could not add Cut to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_PASTE, "Paste")) {
    ret = false;
    mprintf(0, "Warning: Could not add Paste to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_DELETE, "Delete")) {
    ret = false;
    mprintf(0, "Warning: Could not add Delete to popup\n");
  }
  if (!popup->AppendMenu(MF_SEPARATOR)) {
    ret = false;
    mprintf(0, "Warning: Could not add seperator to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_EDITNAME, "Edit Name")) {
    ret = false;
    mprintf(0, "Warning: Could not add Edit Name to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_SOUND, "Sound")) {
    ret = false;
    mprintf(0, "Warning: Could not add Sound to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_EDITSCRIPT, "Edit Dallas Scripts")) {
    ret = false;
    mprintf(0, "Warning: Could not add Edit Script to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_NEWSCRIPT, "New Dallas Script")) {
    ret = false;
    mprintf(0, "Warning: Could not add New Script to popup\n");
  }
  if (!popup->AppendMenu(MF_STRING, POPUP_CUSTOMDEFAULTSCRIPT, "Set a custom default script")) {
    ret = false;
    mprintf(0, "Warning: Could not add Set a custom default script to popup\n");
  }
  //@@if(!popup->AppendMenu(MF_STRING,POPUP_PROPERTIES,"Properties"))
  //@@{
  //@@	ret=false;
  //@@	mprintf(0,"Warning: Could not add Properties to popup\n");
  //@@}
  //@@if(!popup->AppendMenu(MF_STRING,POPUP_COPYID,"Copy UID"))
  //@@{
  //@@	ret=false;
  //@@	mprintf(0,"Warning: Could not add Copy UID to popup\n");
  //@@}
  return ret;
}

void UpdateProperties(CObjectPropertiesDialog *prop_dlg) {

  object *curobj;
  curobj = &Objects[Cur_object_index];

  curobj->mtype.phys_info.velocity.x = prop_dlg->m_fVelocityX;
  curobj->mtype.phys_info.velocity.y = prop_dlg->m_fVelocityY;
  curobj->mtype.phys_info.velocity.z = prop_dlg->m_fVelocityZ;

  curobj->mtype.phys_info.thrust.x = prop_dlg->m_fThrustX;
  curobj->mtype.phys_info.thrust.y = prop_dlg->m_fThrustY;
  curobj->mtype.phys_info.thrust.z = prop_dlg->m_fThrustZ;

  curobj->mtype.phys_info.rotvel.x = prop_dlg->m_fRotVelX;
  curobj->mtype.phys_info.rotvel.y = prop_dlg->m_fRotVelY;
  curobj->mtype.phys_info.rotvel.z = prop_dlg->m_fRotVelZ;

  curobj->mtype.phys_info.rotthrust.x = prop_dlg->m_fRotThrustX;
  curobj->mtype.phys_info.rotthrust.y = prop_dlg->m_fRotThrustY;
  curobj->mtype.phys_info.rotthrust.z = prop_dlg->m_fRotThrustZ;

  curobj->mtype.phys_info.turnroll = prop_dlg->m_sTurnrollAngle;
  curobj->mtype.phys_info.num_bounces = prop_dlg->m_iNumBounces;
  curobj->mtype.phys_info.mass = prop_dlg->m_fMass;
  curobj->mtype.phys_info.drag = prop_dlg->m_fDrag;
  curobj->mtype.phys_info.rotdrag = prop_dlg->m_fRotDrag;
  curobj->mtype.phys_info.full_thrust = prop_dlg->m_fFullThrust;
  curobj->mtype.phys_info.full_rotthrust = prop_dlg->m_fFullRotThrust;
  curobj->mtype.phys_info.max_turnroll_rate = prop_dlg->m_fMaxTurnrollrate;
  curobj->mtype.phys_info.turnroll_ratio = prop_dlg->m_fTurnrollRatio;
  curobj->mtype.phys_info.wiggle_amplitude = prop_dlg->m_fWiggleAmplitude;
  curobj->mtype.phys_info.wiggles_per_sec = prop_dlg->m_fWigglesPerSecond;

  curobj->mtype.phys_info.flags = 0;

  if (prop_dlg->m_bTurnroll)
    curobj->mtype.phys_info.flags |= PF_TURNROLL;
  if (prop_dlg->m_bLevelling)
    curobj->mtype.phys_info.flags |= PF_LEVELING;
  if (prop_dlg->m_bBounce)
    curobj->mtype.phys_info.flags |= PF_BOUNCE;
  if (prop_dlg->m_bWiggle)
    curobj->mtype.phys_info.flags |= PF_WIGGLE;
  if (prop_dlg->m_bSticks)
    curobj->mtype.phys_info.flags |= PF_STICK;
  if (prop_dlg->m_bPersistent)
    curobj->mtype.phys_info.flags |= PF_PERSISTENT;
  if (prop_dlg->m_bUsesThrust)
    curobj->mtype.phys_info.flags |= PF_USES_THRUST;
  if (prop_dlg->m_bGravity)
    curobj->mtype.phys_info.flags |= PF_GRAVITY;
  if (prop_dlg->m_bMagnetism)
    curobj->mtype.phys_info.flags |= PF_IGNORE_OWN_CONC_FORCES;
  if (prop_dlg->m_bWind)
    curobj->mtype.phys_info.flags |= PF_WIND;

  if ((prop_dlg->m_bUnlimitedBounce) || (!prop_dlg->m_bBounce)) {
    curobj->mtype.phys_info.num_bounces = -1;
  }
}

#include "osiris_predefs.h"
extern bool StripLeadingTrailingSpaces(char *s);

BOOL CTextureGrWnd::OnCommand(WPARAM wParam, LPARAM lParam) {
  // TODO: Add your specialized code here and/or call the base class
  if (HIWORD(wParam) == 0) {
    switch (LOWORD(wParam)) {
    case POPUP_EDITSCRIPT: {
      mprintf(0, "Edit script for object %d\n", Cur_object_index);
      // Nate: Add code here to edit/view an object's scripts

      // Make sure Dallas is open
      if (theApp.m_DallasModelessDlgPtr == NULL) {
        theApp.m_DallasModelessDlgPtr = new CDallasMainDlg;
        theApp.m_DallasModelessDlgPtr->Create(IDD_DALLAS_MAIN_DIALOG, this);
        theApp.m_DallasModelessDlgPtr->ShowWindow(SW_SHOW);
      } else
        theApp.m_DallasModelessDlgPtr->ShowWindow(SW_RESTORE);

      object *curobj = &Objects[Cur_object_index];
      if (curobj->name == NULL)
        break;

      // Tell Dallas to add a new script with this object as the owner
      theApp.m_DallasModelessDlgPtr->m_ScriptOwnerType = OBJECT_TYPE;
      theApp.m_DallasModelessDlgPtr->m_ScriptOwnerHandle = curobj->handle;
      theApp.m_DallasModelessDlgPtr->PostMessage(WM_HIGHLIGHT_SCRIPTS);
    } break;

    case POPUP_NEWSCRIPT: {
      mprintf(0, "Add new script for object %d\n", Cur_object_index);
      // Nate: Add code here to create a new script for an object

      // Make sure Dallas is open
      if (theApp.m_DallasModelessDlgPtr == NULL) {
        theApp.m_DallasModelessDlgPtr = new CDallasMainDlg;
        theApp.m_DallasModelessDlgPtr->Create(IDD_DALLAS_MAIN_DIALOG, this);
        theApp.m_DallasModelessDlgPtr->ShowWindow(SW_SHOW);
      } else
        theApp.m_DallasModelessDlgPtr->ShowWindow(SW_RESTORE);

      object *curobj = &Objects[Cur_object_index];
      if (curobj->name == NULL)
        break;

      // Tell Dallas to highlight all scripts that have this object as the owner
      theApp.m_DallasModelessDlgPtr->m_ScriptOwnerType = OBJECT_TYPE;
      theApp.m_DallasModelessDlgPtr->m_ScriptOwnerHandle = curobj->handle;
      theApp.m_DallasModelessDlgPtr->PostMessage(WM_ADD_SCRIPT);
    } break;

    case POPUP_EDITNAME: {
      if (Objects[Cur_object_index].type == OBJ_PLAYER) {
        EditorMessageBox("You cannot name a player object.");
        break;
      }

      char tempname[OBJ_NAME_LEN + 1] = "";
      object *curobj = &Objects[Cur_object_index];
      if (curobj->name) {
        ASSERT(strlen(curobj->name) <= OBJ_NAME_LEN);
        strcpy(tempname, curobj->name);
      }

    try_again:;
      if (!InputString(tempname, OBJ_NAME_LEN, "Object Name", "Enter a new name:"))
        break;

      if (StripLeadingTrailingSpaces(tempname))
        EditorMessageBox("Note: Leading and/or trailing spaces have been removed from this name (\"%s\")", tempname);

      int handle = osipf_FindObjectName(tempname);
      if ((handle != OBJECT_HANDLE_NONE) && (handle != curobj->handle)) {
        EditorMessageBox("Object %d already has this name.", OBJNUM(ObjGet(handle)));
        goto try_again;
      }

      if (curobj->name) {
        mem_free(curobj->name);
        curobj->name = NULL;
      }

      if (strlen(tempname)) {
        curobj->name = (char *)mem_malloc(strlen(tempname) + 1);
        strcpy(curobj->name, tempname);
      }

      World_changed = 1;

      break;
    }

    case POPUP_CUSTOMDEFAULTSCRIPT: {
      object *curobj = &Objects[Cur_object_index];

      CCustDefaultScriptSelect dlg;

      if (curobj->custom_default_script_name)
        dlg.m_Name = curobj->custom_default_script_name;
      else
        dlg.m_Name = "";

      if (curobj->custom_default_module_name)
        dlg.m_Module = curobj->custom_default_module_name;
      else
        dlg.m_Module = "";

      if (dlg.DoModal()) {

        if (curobj->custom_default_module_name) {
          mem_free(curobj->custom_default_module_name);
          curobj->custom_default_module_name = NULL;
        }

        if (curobj->custom_default_script_name) {
          mem_free(curobj->custom_default_script_name);
          curobj->custom_default_script_name = NULL;
        }

        if (!dlg.m_Module.IsEmpty()) {
          char module_name[MAX_MODULENAME_LEN];
          curobj->custom_default_module_name = (char *)mem_malloc(dlg.m_Module.GetLength() + 1);

          ddio_SplitPath(dlg.m_Module.GetBuffer(0), NULL, module_name, NULL);
          strcpy(curobj->custom_default_module_name, module_name);
        }

        if (!dlg.m_Name.IsEmpty()) {
          curobj->custom_default_script_name = (char *)mem_malloc(dlg.m_Name.GetLength() + 1);
          strcpy(curobj->custom_default_script_name, dlg.m_Name.GetBuffer(0));
        }
      }

      World_changed = 1; //?

    } break;

      //@@case POPUP_PROPERTIES:
      //@@	{
      //@@		CObjectPropertiesDialog prop_dlg;
      //@@		object *curobj=&Objects[Cur_object_index];
      //@@		mprintf(0,"Properties selected\n");
      //@@		if(prop_dlg.DoModal()==IDOK) UpdateProperties(&prop_dlg);
      //@@		break;
      //@@	}
      //@@
      //@@case POPUP_COPYID:
      //@@	Copied_object_id = Objects[Cur_object_index].handle;
      //@@	break;

    case POPUP_DELETE:
      if (!ObjectDelete())
        OutrageMessageBox("Could not Delete Object!");
      break;
    case POPUP_PASTE:
      if (!ObjectPaste())
        OutrageMessageBox("Could not Paste Object!");
      break;
    case POPUP_CUT:
      if (!ObjectCut())
        OutrageMessageBox("Could not Cut Object!");
      break;
    case POPUP_COPY:
      if (!ObjectCopy())
        OutrageMessageBox("Could not Copy Object!");
      break;

    case POPUP_SOUND: {
      CSoundSourceDialog dlg(&Objects[Cur_object_index].ctype.soundsource_info);
      dlg.DoModal();
    }
    }
  }
  return CWnd::OnCommand(wParam, lParam);
}

// Shows radiosity progress in the texture window.
// This function needs to go in this file because of the stupid MFC
// problems that occur if you try to access MFC member variables from a non-
// MFC file
void ShowRadView() {
  grSurface *cur_surf;
  int i, t;

  CTextureGrWnd *tview = theApp.textured_view;

  cur_surf = rad_Viewport->lock();
  uint16_t *dest = (uint16_t *)cur_surf->data();
  int rowsize = cur_surf->rowsize() / 2;

  int height = cur_surf->height();
  int width = cur_surf->width();

  fix du = IntToFix(rad_Hemicube.ff_res) / cur_surf->width();
  fix dv = IntToFix(rad_Hemicube.ff_res) / cur_surf->height();
  fix u, v;

  for (v = 0, i = 0; i < height; i++, v += dv)
    for (u = 0, t = 0; t < width; t++, u += du) {
      int x = FixToInt(u);
      int y = FixToInt(v);

      int color = rad_Hemicube.id_grid[y * rad_Hemicube.ff_res + x];
      if (color == -1)
        dest[i * rowsize + t] = 0;
      else
        dest[i * rowsize + t] = GR_COLOR_TO_16(color);
    }

  rad_Viewport->unlock();
  tview->Invalidate();
  tview->SendMessage(WM_PAINT);

  World_changed = 1;
}