forked from rochus-keller/OberonSystem3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dim3Engine.Mod
2540 lines (2279 loc) · 77.6 KB
/
Dim3Engine.Mod
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
(* OBERON System 3, Release 2.3.
Copyright 1999 ETH Zürich Institute for Computer Systems,
ETH Center, CH-8092 Zürich. e-mail: [email protected].
This module may be used under the conditions of the general Oberon
System 3 license contract. The full text can be downloaded from
"ftp://ftp.inf.ethz.ch/pub/software/Oberon/System3/license.txt;A"
Under the license terms stated it is in particular (a) prohibited to modify
the interface of this module in any way that disagrees with the style
or content of the system and (b) requested to provide all conversions
of the source code to another platform with the name OBERON. *)
MODULE Dim3Engine; (** portable *) (* David Ulrich Nov 95 - März 96 *)
(** This module contains a 3D Engine to draw 3D worlds consisting of polygons **)
IMPORT
Attributes, Display, Files, Gadgets, Math, Oberon, Objects, Pictures, Texts, Dim3Paint, Fonts, Dim3Base;
CONST
invisible* = 0; mustClip* = 1; selected* = 2; smooth* = 3; dither* = 4; gouraud* = 5; specular* = 6; (** shape state flags **)
locked* = 0; needUpdate* = 1; (** world state flags **)
maxVertices = 20; (* maximum number of vertices for clipped polygons *)
nPlanes = 5; (* number of clipping planes *)
hither = -0.01; (* z-position of front clipping plane *)
numDynScreen = 500; (* max number of rows in world *)
SKY = 83; GND = 8; (* sky and ground colors based on rembrandt color map *)
DirectLight* = 0; PointLight* = 1; (** types of light sources **)
Dist = 0.2; (* Correction for distance calculation used by point lights for diffuse reflection*)
DistSpec = 0.5; (* Correction for distance calculation used by point lights for specular reflection*)
EOS = 0X; (* end of string *)
MaxString* = 64; (** maximal number of characters in StringTextures **)
TYPE
Vector* = ARRAY 3 OF REAL; (** 4th homogenous coordinate (W) is always assumed to be 1 **)
Matrix* = ARRAY 3, 4 OF REAL; (** bottom row is always assumed to be [0, 0, 0, 1] **)
Color* = ARRAY 3 OF REAL; (** red, green and blue value **)
(** directional or point light sources **)
Light* = POINTER TO LightDesc;
LightDesc* = RECORD
next*: Light;
type*: INTEGER; (** direct light source -> type = DirectLight; point light source -> type = PointLight **)
inten*: REAL; (** light intensity, 0 < inten <= 1 **)
dir*: Vector; (** light direction or position of point light source in world space **)
END;
LightRef = POINTER TO LightRefDesc;
LightRefDesc = RECORD
next: LightRef;
light: Light;
factor: REAL;
R: Vector;
END;
(** geometric structures **)
Point* = POINTER TO PointDesc;
PointRef* = POINTER TO PointRefDesc;
Polygon* = POINTER TO PolygonDesc;
Shape* = POINTER TO ShapeDesc;
Texture = POINTER TO TextureDesc;
TextureDesc = RECORD
stringTexture: BOOLEAN; (* TRUE -> string texture, FALSE -> normal texture *)
name, font: ARRAY MaxString OF CHAR;
fontCol, backCol: Color; (* used for string textures *)
basePict: Pictures.Picture; (* original texture *)
shadedPict: ARRAY 6 OF Dim3Paint.TextureMap; (* shaded textures, maximal 6 mipmaps *)
numPict: INTEGER; (* number of mipmaps used *)
transparent: BOOLEAN; (* use perspective correction *)
END;
PointDesc* = RECORD
next*: Point;
wc*: Vector; (** 3D world coordinates (WC) *)
vrc*: Vector; (** 3D view reference coordinates (VRC) *)
normal: Vector; (* normal vector of point *)
END;
PointRefDesc* = RECORD
next*, prev*: PointRef; (** successor and predecessor in doubly linked polygon list **)
p*: Point; (** referenced point **)
u, v: REAL; (** texture coordinates **)
inten*: REAL; (** light intensity in point, 0 < inten <= 1 **)
specular: REAL; (* specular light intensity, only used during drawing *)
light: LightRef; (* list of lights for specular reflexion *)
END;
PolygonDesc* = RECORD
next*: Polygon;
contour*: PointRef; (** list of contour point references **)
normal*: Vector; (** vector pointing away from polygon (in WC) **)
dist*: REAL; (** distance of polygon to origin => poly.normal * X + poly.dist = (signed) distance of vector X to plane **)
col*: INTEGER; (** color number of shaded polygon **)
shape*: Shape; (** shape that contains polygon **)
texture*: Texture; (** texture, the plane has to be filled with, NIL if no texture **)
END;
ShapeDesc* = RECORD
next*: Shape; (** successor in parent's subshape list **)
parent*: Shape; (** the shape this shape is a part of **)
subshapes*: Shape;
points*, realPoints: Point;
polygons*, realPolygons: Polygon;
lights*: Light; (** local light sources **)
T*: Matrix; (** local transformation matrix (to be set by application) **)
state*: SET;
color*: Color; (** shape surface color **)
grayscale*: BOOLEAN; (** use grayscale colors **)
diffuse*: REAL; (** coefficient for diffuse reflection **)
speccoef*: REAL; (** coefficien for specular reflection **)
specexpo*: INTEGER; (** exponent for specular reflection **)
center: Vector; (* center of bounding sphere in WC *)
radius: REAL; (* radius of bounding sphere *)
cmd*: POINTER TO ARRAY 64 OF CHAR; (** associated command string **)
END;
(* binary space partitioning tree nodes *)
BSPNode = POINTER TO BSPNodeDesc;
BSPNodeDesc = RECORD
front, back: BSPNode; (* subtrees on both sides *)
poly: Polygon; (* polygon which serves as splitting plane *)
END;
(** polygon world **)
World* = POINTER TO WorldDesc;
WorldDesc* = RECORD (Gadgets.ObjDesc)
state*: SET;
shape*: Shape; (** the "world shape" **)
bspTree: BSPNode;
ambient*: REAL; (** intensity of ambient light **)
skyCol*, gndCol*: INTEGER; (** color numbers for sky and ground **)
horizon*: BOOLEAN; (** flag whether to draw horizon or not **)
time*: LONGINT; (** time of selection **)
selCount*: INTEGER; (** number of selected shapes **)
selShape*: Shape; (** selected shape (if only one selected) **)
END;
(** view specification **)
Camera* = RECORD
fov*: REAL; (** field of view angle **)
pos*, u*, v*, w*: Vector; (** camera position and coordinate axes **)
zx, zy: REAL; (* zoom factor in u and v direction *)
END;
VAR
identity*: Matrix; (** transformation matrix containing identity transformation **)
white*, black*: Color; (** default color vectors **)
executor*: Shape; (** shape that issued a command **)
pointPool: Point; (* memory pools for frequently allocated structures *)
refPool: PointRef;
polyPool: Polygon;
bspPool: BSPNode;
W: Texts.Writer;
NullVector: Vector;
(* clipping planes *)
clip: ARRAY nPlanes OF RECORD
normal: Vector; (* points away from view volume *)
dist: REAL; (* distance to origin *)
END;
(* dyn. Screen *)
dynScreen: ARRAY numDynScreen OF Dim3Paint.DSEntry;
tsList: Dim3Paint.TSEntry;
(*--- Errors ---*)
PROCEDURE Halt (cmd, msg: ARRAY OF CHAR);
BEGIN
Texts.WriteString(W, "Dim3Engine."); Texts.WriteString(W, cmd); Texts.WriteString(W, ": ");
Texts.WriteString(W, msg); Texts.WriteLn(W); Texts.Append(Oberon.Log, W.buf);
HALT(127)
END Halt;
(**--- Memory Management of Frequently Used Structures ---**)
(** allocate new point **)
PROCEDURE NewPoint* (VAR p: Point);
BEGIN
IF pointPool = NIL THEN
NEW(p)
ELSE
p := pointPool;
pointPool := pointPool.next;
p.next := NIL
END
END NewPoint;
(** allocate new point ref structure**)
PROCEDURE NewRef* (VAR ref: PointRef);
BEGIN
IF refPool = NIL THEN
NEW(ref)
ELSE
ref := refPool;
refPool := refPool.next;
ref.next := NIL;
ref.light := NIL;
END
END NewRef;
(** allocate new polygon structure**)
PROCEDURE NewPolygon* (VAR poly: Polygon);
BEGIN
IF polyPool = NIL THEN
NEW(poly)
ELSE
poly := polyPool;
polyPool := polyPool.next;
poly.next := NIL;
poly.texture := NIL;
poly.contour := NIL;
poly.shape := NIL;
END
END NewPolygon;
(** free point list to pool **)
PROCEDURE FreePointList* (p: Point);
VAR last: Point;
BEGIN
IF p # NIL THEN
last := p;
WHILE last.next # NIL DO last := last.next END;
last.next := pointPool; pointPool := p
END
END FreePointList;
(** free point ref list to pool **)
PROCEDURE FreeRefList* (ref: PointRef);
BEGIN
IF ref # NIL THEN
ref.prev.next := refPool; refPool := ref
END
END FreeRefList;
(** free polygon list to pool **)
PROCEDURE FreePolyList* (poly: Polygon);
VAR last: Polygon;
BEGIN
IF poly # NIL THEN
last := poly;
WHILE last.next # NIL DO last := last.next END;
last.next := polyPool; polyPool := poly
END
END FreePolyList;
(** free structure pools **)
PROCEDURE ReleaseMem*;
BEGIN
(* make structure pools empty => used memory can be collected by GC *)
pointPool := NIL;
refPool := NIL;
polyPool := NIL
END ReleaseMem;
(** --- Arc tangent of y/x ---**)
PROCEDURE Atan2* (y, x: REAL): REAL;
BEGIN
IF (ABS(x) < 1.0) & (ABS(y) >= ABS(x * MAX(REAL))) THEN (* y / x would result in overflow/divide by zero trap *)
IF y >= 0 THEN RETURN Math.pi/2
ELSE RETURN -Math.pi/2
END
ELSIF x > 0 THEN (* 1st or 4th quadrant *)
RETURN Math.arctan(y / x)
ELSIF x < 0 THEN (* 2nd or 3rd quadrant *)
RETURN Math.arctan(y / x) + Math.pi
END
END Atan2;
(**--- Vector Operations ---**)
(* All routines use VAR parameters for efficiency, so beware of alias problems *)
PROCEDURE InitVector* (VAR v: Vector; x, y, z: REAL);
BEGIN
v[0] := x; v[1] := y; v[2] := z
END InitVector;
PROCEDURE MakeVector* (VAR from, to, v: Vector);
BEGIN
InitVector(v, to[0] - from[0], to[1] - from[1], to[2] - from[2])
END MakeVector;
(** cross product of two vectors **)
PROCEDURE CrossProd* (VAR u, v, w: Vector);
BEGIN
w[0] := u[1] * v[2] - u[2] * v[1];
w[1] := u[2] * v[0] - u[0] * v[2];
w[2] := u[0] * v[1] - u[1] * v[0];
END CrossProd;
(** dot product of two vectors **)
PROCEDURE DotProd* (VAR u, v: Vector): REAL;
BEGIN
RETURN u[0]*v[0] + u[1]*v[1] + u[2]*v[2]
END DotProd;
(** scale vector to unit length **)
PROCEDURE Normalize* (VAR x: Vector);
CONST eps = 1.E-7;
VAR f: REAL;
BEGIN
f := Math.sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);
IF f >= eps THEN
x[0] := x[0]/f; x[1] := x[1]/f; x[2] := x[2]/f
END
END Normalize;
(* add vector y to vector x *)
PROCEDURE VectorSum (VAR x: Vector; y: Vector);
BEGIN
x[0] := x[0] + y[0];
x[1] := x[1] + y[1];
x[2] := x[2] + y[2];
END VectorSum;
(* calculate distance between two points *)
PROCEDURE Distance (x, y: Vector):REAL;
VAR t1, t2, t0: REAL;
BEGIN
t0 := x[0] - y[0]; t1 := x[1] - y[1]; t2 := x[2] - y[2];
RETURN Math.sqrt(t0*t0 + t1*t1 + t2*t2);
END Distance;
PROCEDURE WriteVector (VAR R: Files.Rider; VAR v: Vector);
BEGIN
Files.WriteReal(R, v[0]); Files.WriteReal(R, v[1]); Files.WriteReal(R, v[2])
END WriteVector;
PROCEDURE ReadVector (VAR R: Files.Rider; VAR v: Vector);
BEGIN
Files.ReadReal(R, v[0]); Files.ReadReal(R, v[1]); Files.ReadReal(R, v[2])
END ReadVector;
(**--- Matrix Operations ---**)
(* All routines use VAR parameters for efficiency, so beware of alias problems *)
(** concat matrices A and B and store result in C **)
PROCEDURE ConcatMatrix* (VAR A, B, C: Matrix);
VAR i: INTEGER; a0, a1, a2: REAL;
BEGIN
FOR i := 0 TO 2 DO
a0 := A[i, 0]; a1 := A[i, 1]; a2 := A[i, 2];
C[i, 0] := a0*B[0, 0] + a1*B[1, 0] + a2*B[2, 0]; (* + A[i, 3]*B[3, 0] = 0 *)
C[i, 1] := a0*B[0, 1] + a1*B[1, 1] + a2*B[2, 1]; (* + A[i, 3]*B[3, 1] = 0 *)
C[i, 2] := a0*B[0, 2] + a1*B[1, 2] + a2*B[2, 2]; (* + A[i, 3]*B[3, 2] = 0 *)
C[i, 3] := a0*B[0, 3] + a1*B[1, 3] + a2*B[2, 3] + A[i, 3]
END
END ConcatMatrix;
(** apply transformation matrix to vector **)
PROCEDURE Transform* (VAR M: Matrix; VAR x, y: Vector);
BEGIN
y[0] := M[0, 0]*x[0] + M[0, 1]*x[1] + M[0, 2]*x[2] + M[0, 3];
y[1] := M[1, 0]*x[0] + M[1, 1]*x[1] + M[1, 2]*x[2] + M[1, 3];
y[2] := M[2, 0]*x[0] + M[2, 1]*x[1] + M[2, 2]*x[2] + M[2, 3]
END Transform;
(** compute rotation matrix **)
PROCEDURE GetRotation* (VAR M: Matrix; angle, x, y, z: REAL);
CONST eps = 1.E-10;
VAR s, c, t: REAL;
BEGIN
t := Math.sqrt(x*x + y*y + z*z);
IF t > eps THEN
(* the following formula comes from: A. S. Glassner, Graphic Gems, Addison-Wesley 1990, p. 466 (Rotation Tools) *)
x := x/t; y := y/t; z := z/t; (* normalize axis *)
s := Math.sin(angle); c := Math.cos(angle); t := 1 - c;
M[0, 0] := t*x*x + c; M[0, 1] := t*x*y - s*z; M[0, 2] := t*x*z + s*y; M[0, 3] := 0;
M[1, 0] := t*y*x + s*z; M[1, 1] := t*y*y + c; M[1, 2] := t*y*z - s*x; M[1, 3] := 0;
M[2, 0] := t*z*x - s*y; M[2, 1] := t*z*y + s*x; M[2, 2] := t*z*z + c; M[2, 3] := 0
ELSE Halt("GetRotation", "axis is too short to be normalized")
END
END GetRotation;
(* Translation and scaling matrices are much easier to create, so no GetTranslation/GetScale is provided *)
(*
* The following three procedures append a transformation matrix to a given matrix. Because of the right to left evaluation
* order of transformation matrices, the effect is that the new transformation becomes the first transformation applied
* to a point. This is more convenient for maintaining a current transformation matrix (CTM) during the creation of sceneries
* since it allows local transformations to be applied to subsequent point definitions independent of any inherited CTM.
*)
(** prepend translation to transformation **)
PROCEDURE Translate* (VAR M: Matrix; dx, dy, dz: REAL);
VAR i: INTEGER; m0, m1, m2: REAL;
BEGIN
FOR i := 0 TO 2 DO
m0 := M[i, 0]; m1 := M[i, 1]; m2 := M[i, 2];
M[i, 3] := M[i, 3] + m0*dx + m1*dy + m2*dz
END
END Translate;
(** prepend rotation to transformation **)
PROCEDURE Rotate* (VAR M: Matrix; angle, x, y, z: REAL);
VAR R, Q: Matrix;
BEGIN
GetRotation(R, angle, x, y, z);
Q := M;
ConcatMatrix(Q, R, M)
END Rotate;
(** prepend scale to transformation **)
PROCEDURE Scale* (VAR M: Matrix; sx, sy, sz: REAL);
VAR i: INTEGER;
BEGIN
FOR i:= 0 TO 2 DO
M[i, 0] := sx*M[i, 0];
M[i, 1] := sy*M[i, 1];
M[i, 2] := sz*M[i, 2]
END
END Scale;
(**
* Decompose matrix into rotation angle and axis, scale and translation vectors. In order to achieve the given transformation,
* you first have to scale, then rotate and finally translate any given point. It is assumed that the matrix consists only of
* concatenated rotations, translations and scaling transformations.
**)
PROCEDURE Decompose* (VAR M: Matrix; VAR angle: REAL; VAR axis, scale, trans: Vector);
VAR i: INTEGER; sin, cos, m0, m1, m2: REAL;
BEGIN
(* translation is easy: just copy the last column of M *)
FOR i := 0 TO 2 DO
trans[i] := M[i, 3]
END;
(*
* Consider applying M (without translation) to the unit vectors (1 0 0), (0 1 0) and (0 0 1)
* => the resulting vectors are the columns of M. We can find the scaling factors along each axis by calculating the
* length of the transformed unit vectors.
*)
FOR i := 0 TO 2 DO
m0 := M[0, i]; m1 := M[1, i]; m2 := M[2, i];
scale[i] := Math.sqrt(m0*m0 + m1*m1 + m2*m2)
END;
(* calculate angle (see A. S. Glassner, Graphic Gems, Addison-Wesley 1990, pp. 466 (Rotation Tools)) *)
cos := 0.5 * (M[0, 0]/scale[0] + M[1, 1]/scale[1] + M[2, 2]/scale[2] - 1.0);
sin := Math.sqrt(ABS(1.0 - cos*cos));
angle := Atan2(sin, cos);
(* get axis *)
IF sin > 1.0E-6 THEN
axis[0] := 0.5 * (M[1, 2]/scale[2] - M[2, 1]/scale[1]) / sin;
axis[1] := 0.5 * (M[2, 0]/scale[0] - M[0, 2]/scale[2]) / sin;
axis[2] := 0.5 * (M[0, 1]/scale[1] - M[1, 0]/scale[0]) / sin
ELSE
InitVector(axis, 0, 0, 0)
END
END Decompose;
PROCEDURE WriteMatrix (VAR R: Files.Rider; VAR M: Matrix);
VAR i, j: INTEGER;
BEGIN
FOR i := 0 TO 2 DO
FOR j := 0 TO 3 DO
Files.WriteReal(R, M[i, j])
END
END
END WriteMatrix;
PROCEDURE ReadMatrix (VAR R: Files.Rider; VAR M: Matrix);
VAR i, j: INTEGER;
BEGIN
FOR i := 0 TO 2 DO
FOR j := 0 TO 3 DO
Files.ReadReal(R, M[i, j])
END
END
END ReadMatrix;
(**--- Colors ---**)
PROCEDURE InitColor* (VAR col: Color; r, g, b: REAL);
BEGIN
col[0] := r; col[1] := g; col[2] := b
END InitColor;
(**--- Points ---**)
PROCEDURE InitPoint* (p: Point; x, y, z: REAL);
BEGIN
InitVector(p.wc, x, y, z);
p.next := NIL
END InitPoint;
PROCEDURE WritePoint (VAR R: Files.Rider; p: Point);
BEGIN
WriteVector(R, p.wc); (* it's sufficient to store world coordinates, since the rest will be recalculated anyway *)
END WritePoint;
PROCEDURE ReadPoint (VAR R: Files.Rider; p: Point);
BEGIN
ReadVector(R, p.wc)
END ReadPoint;
(**--- Contours ---**)
(** append point reference to contour, inten = light intensity in point (if known) **)
PROCEDURE AppendPoint* (VAR contour: PointRef; p: Point);
VAR ref: PointRef;
BEGIN
NewRef(ref); ref.p := p; ref.inten := 0; ref.light := NIL;
IF contour = NIL THEN (* first point *)
contour := ref;
ref.next := ref;
ref.prev := ref
ELSE
ref.next := contour;
ref.prev := contour.prev;
ref.prev.next := ref;
ref.next.prev := ref
END
END AppendPoint;
(** append point reference to contour and texture coordinates **)
PROCEDURE AppendTexturePoint* (VAR contour: PointRef; p: Point; u, v: REAL);
VAR ref: PointRef;
BEGIN
NewRef(ref); ref.p := p; ref.u := u; ref.v := v; ref.inten := 0; ref.light := NIL;
IF contour = NIL THEN (* first point *)
contour := ref;
ref.next := ref;
ref.prev := ref
ELSE
ref.next := contour;
ref.prev := contour.prev;
ref.prev.next := ref;
ref.next.prev := ref
END
END AppendTexturePoint;
(* append point reference to contour, inten = light intensity in point (if known) *)
PROCEDURE AppTextPointSpecial (VAR contour: PointRef; p: Point; inten, u, v: REAL);
VAR ref: PointRef;
BEGIN
NewRef(ref); ref.p := p; ref.u := u; ref.v := v; ref.inten := inten; ref.light := NIL;
IF contour = NIL THEN (* first point *)
contour := ref;
ref.next := ref;
ref.prev := ref
ELSE
ref.next := contour;
ref.prev := contour.prev;
ref.prev.next := ref;
ref.next.prev := ref
END
END AppTextPointSpecial;
(* append point reference to contour, inten = light intensity in point (if known) *)
PROCEDURE AppPointSpecial (poly: Polygon; VAR contour: PointRef; p: Point; inten: REAL; lightRef: LightRef);
VAR ref: PointRef; newLight: LightRef; k: REAL; normal, dir: Vector; l: Light;
BEGIN
NewRef(ref); ref.p := p; ref.inten := inten; ref.light := NIL;
WHILE lightRef # NIL DO (* recalculate data for specular reflection *)
NEW(newLight);
newLight.light := lightRef.light; l := lightRef.light;
IF smooth IN poly.shape.state THEN normal := ref.p.normal ELSE normal := poly.normal END;
Normalize(normal);
IF l.type = PointLight THEN
MakeVector(p.wc, l.dir, dir); Normalize(dir);
k := DotProd(normal, dir) * 2;
IF k > 0.0 THEN
newLight.R[0] := normal[0] * k - dir[0]; newLight.R[1] := normal[1] * k - dir[1];
newLight.R[2] := normal[2] * k - dir[2];
newLight.factor := poly.shape.speccoef / (Distance(l.dir, p.wc) * DistSpec);
Normalize(newLight.R);
ELSE
newLight.factor := 0
END;
ELSE
k := DotProd(normal, l.dir) * 2;
newLight.R[0] := normal[0] * k - l.dir[0]; newLight.R[1] := normal[1] * k - l.dir[1];
newLight.R[2] := normal[2] * k - l.dir[2];
IF k > 0.0 THEN
newLight.R[0] := normal[0] * k - l.dir[0]; newLight.R[1] := normal[1] * k - l.dir[1];
newLight.R[2] := normal[2] * k - l.dir[2];
newLight.factor := poly.shape.speccoef;
Normalize(newLight.R);
ELSE
newLight.factor := 0
END;
END;
newLight.next := ref.light; ref.light := newLight;
lightRef := lightRef.next;
END;
IF contour = NIL THEN (* first point *)
contour := ref;
ref.next := ref;
ref.prev := ref
ELSE
ref.next := contour;
ref.prev := contour.prev;
ref.prev.next := ref;
ref.next.prev := ref
END
END AppPointSpecial;
(* clip a list of point references to the field of view of a camera *)
PROCEDURE ClipPoly (contour: PointRef; VAR x, y, w, i, spec, u, v: ARRAY OF REAL; VAR n: INTEGER; shade, texture: BOOLEAN);
VAR
s, f: ARRAY nPlanes OF PointRef; first, inside: ARRAY nPlanes OF BOOLEAN; dist, fdist: ARRAY nPlanes OF REAL;
isList, ref: PointRef;
PROCEDURE Intersection (pRef, qRef: PointRef; dp, dq: REAL): PointRef;
CONST eps = 1.E-7;
VAR s, t, x, y, z: REAL; r, p, q: Point; rRef: PointRef;
BEGIN
p := pRef.p; q := qRef.p;
(* the intersection is a linear combination of p and q, whose distances to p and q are dp and dq *)
IF ABS(dp) < eps THEN
RETURN pRef
ELSIF ABS(dq) < eps THEN
RETURN qRef
ELSE (* true intersection *)
t := dp / (dp - dq); s := 1 - t;
x := s*p.vrc[0] + t*q.vrc[0];
y := s*p.vrc[1] + t*q.vrc[1];
z := s*p.vrc[2] + t*q.vrc[2];
NewPoint(r); InitVector(r.vrc, x, y, z);
NEW(rRef); rRef.p := r;
rRef.inten := s*pRef.inten + t*qRef.inten;
rRef.specular := s*pRef.specular + t*qRef.specular;
IF texture THEN rRef.u := s * pRef.u + t * qRef.u; rRef.v := s * pRef.v + t * qRef.v END;
rRef.next := isList; isList := rRef;
RETURN rRef
END
END Intersection;
PROCEDURE Clip (plane: INTEGER; ref: PointRef);
VAR p: Point; d: REAL; in: BOOLEAN; isRef: PointRef;
BEGIN
p := ref.p;
IF plane = nPlanes THEN (* p is inside all clipping planes => append to clipped polygon *)
(* apply perspective transformation *)
x[n] := -p.vrc[0]/p.vrc[2];
y[n] := -p.vrc[1]/p.vrc[2];
i[n] := ref.inten; spec[n] := ref.specular;
IF texture THEN u[n] := ref.u; v[n] := ref.v; w[n] := -p.vrc[2] END;
INC(n);
RETURN
END;
IF first[plane] THEN (* p is the first point that reaches the current clipping plane *)
first[plane] := FALSE; s[plane] := ref; f[plane] := ref;
dist[plane] := DotProd(p.vrc, clip[plane].normal) + clip[plane].dist;
fdist[plane] := dist[plane];
in := dist[plane] <= 0; inside[plane] := in; (* used to be compiler bug in DOS-Oberon, simplify when fixed *)
ELSE
d := DotProd(p.vrc, clip[plane].normal) + clip[plane].dist;
in := d <= 0;
IF in # inside[plane] THEN (* p and previous point are on different sides of the clipping plane *)
isRef := Intersection(s[plane], ref, dist[plane], d);
inside[plane] := in;
Clip(plane+1, isRef)
END;
s[plane] := ref; dist[plane] := d;
END;
(* propagate visible points to next clipping plane *)
IF inside[plane] THEN Clip(plane+1, s[plane]) END
END Clip;
PROCEDURE Close (plane: INTEGER);
VAR isRef: PointRef;
BEGIN
IF plane < nPlanes THEN
IF ~first[plane] & (inside[plane] # (fdist[plane] <= 0)) THEN (* create intersection between last and first point *)
isRef := Intersection(s[plane], f[plane], dist[plane], fdist[plane]);
Clip(plane+1, isRef)
END;
Close(plane+1)
END
END Close;
BEGIN
(* The procedure uses the well known Sutherland-Hodgman polygon clipping algorithm (CACM 17(1), 1974) *)
n := 0;
WHILE n < nPlanes DO
first[n] := TRUE;
INC(n)
END;
isList := NIL;
n := 0;
ref := contour;
REPEAT
Clip(0, ref);
ref := ref.next
UNTIL (ref = contour) OR (n = LEN(x));
Close(0);
END ClipPoly;
(**--- Textures ---**)
(** build the texture for a string **)
PROCEDURE InitStringTexture* (poly: Polygon; string, font: ARRAY OF CHAR; col, backCol: Color; transparent: BOOLEAN);
VAR P: Pictures.Picture; width, height, i, dx, x, y, w, h, fontCol, bgCol, X: INTEGER; F: Fonts.Font; pat: Display.Pattern;
BEGIN
(* calculate size of picture for the string *)
F := Fonts.This(font);
IF F = NIL THEN F := Fonts.Default END;
height := F.height + 6; width := 6;
i := 0;
WHILE (i < MaxString) & (string[i] # EOS) DO
Fonts.GetChar(F, string[i], dx, x, y, w, h, pat);
INC(width, dx);
INC(i);
END;
(* generate texture for the string *)
fontCol := 240; bgCol := 16;
NEW(P);
Pictures.Create(P,width, height, 8);
Pictures.SetColor(P, fontCol, SHORT(ENTIER(col[0] * 255.99)), SHORT(ENTIER(col[1] * 255.99)), SHORT(ENTIER(col[2] * 255.99)));
Pictures.SetColor(P, bgCol, SHORT(ENTIER(backCol[0] * 255.99)), SHORT(ENTIER(backCol[1] * 255.99)), SHORT(ENTIER(backCol[2] * 255.99)));
Pictures.ReplConst(P, bgCol, 0, 0, width, height, Display.replace);
i := 0; X := 3;
WHILE (i < MaxString) & (string[i] # EOS) DO
Fonts.GetChar(F, string[i], dx, x, y, w, h, pat);
Pictures.CopyPattern(P, fontCol, pat, X+x, y-F.minY +3, Display.paint);
INC(X, dx); INC(i);
END;
NEW(poly.texture);
poly.texture.basePict := P;
poly.texture.transparent := transparent;
poly.texture.stringTexture := TRUE;
poly.texture.name := string;
poly.texture.font := font;
poly.texture.fontCol := col; poly.texture.backCol := backCol;
Texts.Append(Oberon.Log, W.buf);
END InitStringTexture;
(** calculate and init the texture of the polygon **)
PROCEDURE InitTexture* (poly: Polygon; name: ARRAY OF CHAR; transparent: BOOLEAN);
VAR P: Pictures.Picture;
BEGIN
NEW(P);
Pictures.Open(P,name, TRUE);
IF P # NIL THEN
NEW(poly.texture);
poly.texture.basePict := P;
poly.texture.transparent := transparent;
poly.texture.stringTexture := FALSE;
poly.texture.name := name
ELSE
poly.texture := NIL
END;
END InitTexture;
PROCEDURE WriteTexture (VAR R: Files.Rider; poly: Polygon);
VAR texture: Texture;
BEGIN
texture := poly.texture;
Files.WriteBool(R, texture.stringTexture);
Files.WriteBool(R, texture.transparent);
IF texture.stringTexture THEN
Files.WriteReal(R, texture.fontCol[0]); Files.WriteReal(R, texture.fontCol[1]); Files.WriteReal(R, texture.fontCol[2]);
Files.WriteReal(R, texture.backCol[0]); Files.WriteReal(R, texture.backCol[1]); Files.WriteReal(R, texture.backCol[2]);
Files.WriteString(R, texture.name); Files.WriteString(R, texture.font);
ELSE
Files.WriteString(R, texture.name);
END
END WriteTexture;
PROCEDURE ReadTexture (VAR R: Files.Rider; poly: Polygon);
VAR stringTexture, transp: BOOLEAN; fontCol, backCol: Color; name, font: ARRAY MaxString OF CHAR;
BEGIN
Files.ReadBool(R, stringTexture);
Files.ReadBool(R, transp);
IF stringTexture THEN
Files.ReadReal(R, fontCol[0]); Files.ReadReal(R, fontCol[1]); Files.ReadReal(R, fontCol[2]);
Files.ReadReal(R, backCol[0]); Files.ReadReal(R, backCol[1]); Files.ReadReal(R, backCol[2]);
Files.ReadString(R, name); Files.ReadString(R, font);
InitStringTexture(poly, name, font, fontCol, backCol, transp);
ELSE
Files.ReadString(R, name);
InitTexture(poly, name, transp);
END;
END ReadTexture;
(**--- Polygons ---**)
PROCEDURE InitPolygon* (poly: Polygon);
BEGIN
poly.contour := NIL;
poly.shape := NIL;
poly.texture := NIL;
END InitPolygon;
(* compute iteratively the normals of the shape points *)
PROCEDURE CalcPointNormals(normal: Vector; contour: PointRef);
VAR ref: PointRef;
BEGIN
ref := contour;
IF contour = NIL THEN RETURN END;
REPEAT
VectorSum(ref.p.normal,normal);
ref := ref.next;
UNTIL (ref = contour) OR (ref = NIL);
END CalcPointNormals;
(* compute plane equation of a polygon *)
PROCEDURE CalcPlane (poly: Polygon);
VAR p, q, r: Point; ref: PointRef; u, v: Vector;
BEGIN
(* Take the cross product of the first two edge vectors. They are assumed to form a left turn, seen from above *)
ref := poly.contour; p := ref.p;
ref := ref.next; q := ref.p;
ref := ref.next; r := ref.p;
MakeVector(p.wc, q.wc, u); MakeVector(p.wc, r.wc, v);
CrossProd(u, v, poly.normal);
Normalize(poly.normal);
poly.dist := -DotProd(poly.normal, p.wc);
CalcPointNormals(poly.normal,poly.contour)
END CalcPlane;
PROCEDURE WritePoly (VAR R: Files.Rider; poly: Polygon);
VAR ref: PointRef; p: Point; n: INTEGER; texture: BOOLEAN;
BEGIN
texture := poly.texture # NIL;
Files.WriteBool(R, texture);
IF texture THEN WriteTexture(R, poly) END;
(* the contour of the polygon is saved a sequence of point numbers *)
ref := poly.contour;
REPEAT
(* compute point number *)
p := poly.shape.realPoints;
n := 0;
WHILE p # ref.p DO
INC(n);
p := p.next
END;
Files.WriteInt(R, n);
IF texture THEN (* write texture coordinates *)
Files.WriteReal(R, ref.u); Files.WriteReal(R, ref.v);
END;
ref := ref.next
UNTIL ref = poly.contour;
Files.WriteInt(R, -1)
END WritePoly;
PROCEDURE ReadPoly (VAR R: Files.Rider; poly: Polygon);
VAR n: INTEGER; p: Point; texture: BOOLEAN; u, v:REAL;
BEGIN
Files.ReadBool(R, texture);
IF texture THEN ReadTexture(R, poly) END;
Files.ReadInt(R, n);
WHILE n >= 0 DO
p := poly.shape.points;
WHILE n > 0 DO
p := p.next;
DEC(n)
END;
IF texture THEN
Files.ReadReal(R, u); Files.ReadReal(R, v);
AppendTexturePoint(poly.contour, p, u, v)
ELSE
AppendPoint(poly.contour, p);
END;
Files.ReadInt(R, n)
END
END ReadPoly;
(**--- Binary Space Partitioning Trees ---**)
(* split polygon along plane into front and back part *)
PROCEDURE BSPSplit (bsp: BSPNode; poly: Polygon; VAR front, back: Polygon);
CONST eps = 1.0E-5;
VAR
dcur, dpred, dmin, dmax, s, t, u, v, inten: REAL; cur, pred, frontList, backList: PointRef; curP, predP, is, isList: Point;
plane: Polygon; shape: Shape;
BEGIN
plane := bsp.poly;
pred := poly.contour.prev;
dpred := DotProd(plane.normal, pred.p.wc) + plane.dist;
(* check for parallel planes *)
IF ABS(ABS(DotProd(plane.normal, poly.normal)) - 1) < 1.0E-7 THEN (* normals are colinear *)
IF dpred >= 0 THEN
front := poly; back := NIL
ELSE
back := poly; front := NIL
END;
RETURN
END;
frontList := NIL; backList := NIL; isList := NIL;
dmin := MAX(REAL); dmax := MIN(REAL); (* largest distances of points from plane *)
cur := poly.contour;
REPEAT
dcur := DotProd(plane.normal, cur.p.wc) + plane.dist;
IF dcur < dmin THEN
dmin := dcur
END;
IF dcur > dmax THEN
dmax := dcur
END;
IF dcur * dpred < 0 THEN (* add intersection to both lists *)
t := dcur / (dcur - dpred); s := 1 - t;
curP := cur.p; predP := pred.p;
NewPoint(is);
is.wc[0] := s * curP.wc[0] + t * predP.wc[0];
is.wc[1] := s * curP.wc[1] + t * predP.wc[1];
is.wc[2] := s * curP.wc[2] + t * predP.wc[2];
is.normal[0] := s * curP.normal[0] + t * predP.normal[0];
is.normal[1] := s * curP.normal[1] + t * predP.normal[1];
is.normal[2] := s * curP.normal[2] + t * predP.normal[2];
inten := s * cur.inten + t * pred.inten;
is.next := isList; isList := is;
IF poly.texture = NIL THEN
AppPointSpecial(poly, frontList, is, inten, cur.light);
AppPointSpecial(poly, backList, is, inten, cur.light)
ELSE
u := s * cur.u + t * pred.u;
v := s * cur.v + t * pred.v;
AppTextPointSpecial(frontList, is, inten, u, v);
AppTextPointSpecial(backList, is, inten, u, v)
END;
END;
IF dcur >= 0 THEN (* add cur to front list *)
IF poly.texture = NIL THEN
AppPointSpecial(poly, frontList, cur.p, cur.inten, cur.light)
ELSE
AppTextPointSpecial(frontList, cur.p, cur.inten, cur.u, cur.v)
END;
END;
IF dcur <= 0 THEN (* add cur to back list *)
IF poly.texture = NIL THEN
AppPointSpecial(poly, backList, cur.p, cur.inten, cur.light)
ELSE
AppTextPointSpecial(backList, cur.p, cur.inten, cur.u, cur.v)
END;
END;
dpred := dcur; pred := cur; cur := cur.next
UNTIL cur = poly.contour;
IF dmax < eps THEN (* poly is on negative side of plane *)
back := poly; front := NIL;
FreeRefList(frontList); FreeRefList(backList); FreePointList(isList)
ELSIF -dmin < eps THEN (* poly is on positive side of plane *)
front := poly; back := NIL;
FreeRefList(frontList); FreeRefList(backList); FreePointList(isList)
ELSE (* plane splits poly in two => create two new polygons *)
shape := poly.shape;
WHILE isList # NIL DO (* append intersection points to shape points *)
is := isList.next; isList.next := shape.points; shape.points := isList; isList := is
END;
NewPolygon(front); front^ := poly^; front.contour := frontList; front.next := shape.polygons; shape.polygons := front;
NewPolygon(back); back^ := poly^; back.contour := backList; back.next := shape.polygons; shape.polygons := back
END;
END BSPSplit;
(* insert polygon into BSP tree *)
PROCEDURE BSPInsert (VAR bsp: BSPNode; poly: Polygon);
VAR front, back: Polygon;
BEGIN
IF bsp = NIL THEN (* add new leaf node *)
IF bspPool = NIL THEN NEW(bsp) ELSE bsp := bspPool; bspPool := bspPool.front END;
bsp.front := NIL; bsp.back := NIL; bsp.poly := poly
ELSE (* split poly and insert parts *)
BSPSplit(bsp, poly, front, back);
IF front # NIL THEN BSPInsert(bsp.front, front) END;
IF back # NIL THEN BSPInsert(bsp.back, back) END
END
END BSPInsert;
(* return BSP nodes to memory pool *)
PROCEDURE BSPFree (bsp: BSPNode);
BEGIN
IF bsp # NIL THEN
BSPFree(bsp.front);
BSPFree(bsp.back);
bsp.front := bspPool; bspPool := bsp
END
END BSPFree;