정수부의 자리수가 조금 큰 부동소수점수(64비트 double 포맷의 수)를 십진수 표현으로 출력해 보았습니다.

십진수로 표현하면  유효자리수 개수가 약 14~15개 정도인데,

Java 언어로는 유효수자 개수를 17개로 자르고 그 뒤를 모두 0으로 출력하였지만,

C# 언어로는 유효수자 아래 부분을 15개로 자르고 그 뒤를 모두 0으로 출력합니다.

Pyhon 은 C/C++ 의 경우 처럼 유효수자 아래 부분을 0으로 채우지 않습니다.

 

물론 Java, C#, Python, C, C++ 어느 프로그램 언어든

십진수로 표현할 때 자르는 방법이나 유효수자 아래 부분을 채우는 방법은 다르지만,

덧셈, 뺄셈, 곱셈, 나누셈, 기타 등등에서 유효수자 아래부분의 처리 결과는 대동소이합니다.

 

 

// Filename: Test_Of_Native_Double_Precison_01.cs
//
//
// Compile: csc Test_Of_Native_Double_Precison_01.cs /r:System.Numerics.dll
// Execute: Test_Of_Native_Double_Precison_01
// Output:
//                          Math.Pow(2, 128) = 340282366920938000000000000000000000000.00
//                          Math.Pow(2, 128) = 340282366920938000000000000000000000000
//     BigInteger.Pow(new BigInteger(2).128) = 340282366920938463463374607431768211456
//
//
//  ------------------------------------------------------
//  출처: https://scripting.tistory.com/
//  ------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections;
using System.Numerics;


public class Test_Program_Of_Native_Double
{
    public static void Test_01() 
    {
          double y = Math.Pow(2, 128);
          Console.WriteLine("                     Math.Pow(2, 128) = {0:F}", y);
          Console.WriteLine("                     Math.Pow(2, 128) = {0:F0}", y);

          BigInteger z = BigInteger.Pow(new BigInteger(2), 128);
          Console.WriteLine("BigInteger.Pow(new BigInteger(2).128) = {0}", z);
    }
    
    public static void Main(string[] args)
    {
        Test_01();
        Console.WriteLine();
    }
}

 

 

 

Posted by Scripter
,

먼저 파이썬 인터프리터를 실행하여 0.3 - 0.2 - 0.1 의 계산 결과를 알아 보았습니다.

>>> 0.3 - 0.2 - 0.1
-2.7755575615628914e-17

계산 결과가 왜 0이 아닌 엉뚱한 값 -2.7755575615628914e-17 이 될까요?

 

IEEE754 에 대해서는 관련되는 두 문서

    [1]  Double-precision floating-point format  

    [2]  Floating Point Arithmetic: Issues and Limitations 

를 참고하기 바랍니다.

 

NET Framework 4.6.x 이상에서 사용가능한 NET용 분수 계산 라이브러리를 소개합니다.

(소스 수정 없이 NET Core 5.0 이상에서도 사용 가능합니다.)

(Mac OS 에서도 FractionLib 를 빌드하여 쓸 수 있습니다만, UnitTest 프로젝트는 새로 작성해야 합니다.)

FractionLib project  에서 내려받은 프로젝트 파일을

Vusual Studio 2019 이상에서 빌드하여 생성된 FractionLib.dll을,

다른 프로젝트에서 라이브러리로 참조 사용하면 IEEE754 의 배정밀도 부동소숫점수를

분수로 받아들여 보다 정확한 수치 계산을 할 수 있습니다.

내부적으로 C#의 표준 큰 정수 BigInteger를 이용하므로 System.Numerics,dll을

함께 참조 추가하면 더 좋습니다.

FractionLib,dll을 사용할 수 있는 언어로는 C# 언어 외에 F#, Visual Basic, IronPython, C++/CLI

언어들도 가능합니다.

사용 예제는 위 프로젝트의 Examples 폴더에 있습니다.

 

부동소수점수의 뺄셈 계산

      0.3 - 0.2 - 0.1

의 계산 결과는 당연히 0이 되어야 함에도 불구하고 

IEEE 754에서 정한 부동소수점수의 한계(mantissa, 유효숫지 부분의 한계)

때문에 0.3 - 0.2 - 0.1 의 계산 결과가 0이 아닌 적당한 근사값로 계산되며,

그 역수는  -1.0E20 보다 큰 음수로 계산됩니다.

그러나 FractionLib.dll 을 사용하여

 

using knumerics;

    ......................
    ......................

    MyFraction a3 = new MyFraction(0.3);
    MyFraction a2 = new MyFraction(0.2);
    MyFraction a1 = new MyFraction(0.1); 
    MyFraction zero = new MyFraction(0, 1);
    
    MyFraction result = a3 - a2 - a1;
    Console.WriteLine("result == zero ? {0}", result == zero);

 

로 작상하면 0.3 - 0.2 - 0.1의 계산 결과가 정확히 0이 됩니다.

 

참고로, 온라인 상에서 Python 언어, C# 언어, C 언어로 각각 테스트해 보았습니다.

 

Python 언어로 0.3 - 0.2 - 0.1 계산하기

 

C# 언어로 0.3 - 0.2 - 0.1 계산하기

 

 

C 언어로 0.3 - 0.2 - 0.1 계산하기

 

Posted by Scripter
,

C# 언어로 부동소수점수 계산할 때 실수할 수 있는 경우이다.

반복문의 탈출 조건에 저런 것을 이용하다 자칫하면

무한 반복의 늪에 빠질 수 있다.

금액 계산의 경우에 정확한 계산이 요구되기 때문에

float 타입이니 double 타입 보다는 decimal 타입을 사용하는것이

더 바람직할 것이다.

정확한 소수점수 계산을 위해 decimal 타입을 사용한 다음 C# 소스의 실행 결과를 보자.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalcDecimalConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Use double type:");
            Console.WriteLine("{0:F20}", 0.3 - 0.1);
            Console.WriteLine("{0}", 0.3 - 0.1 == 0.2);
            Console.WriteLine("Use Decimal type:");
            Console.WriteLine("{0:F20}", new Decimal(0.3) - new Decimal(0.1));
            Console.WriteLine("{0}", new Decimal(0.3) - new Decimal(0.1) == new Decimal(0.2));
        }
    }
}

/****************************************
Output: -------------------------
Use double type:
0.20000000000000000000
False
Use Decimal type:
0.20000000000000000000
True. . .
****************************************/

 

 

 

 

 

 

Posted by Scripter
,

아래의 글은 MS의 유닛 테스트 적성하기 문서에 오류가 있어 바로 잡기 위한 글입니다.

유닛 테스트하는 도구로는 MSTest, NUnit, xUnit 등 몇 가지가 있는데

이 중에 MSTest를 이용하여 유닛 테스트하는 예를 작성해 보고자 한다.

컨솔 창에 Hello World! 라는 문구가 정상적으로 출력되는지 알아보는 유닛 테스트이다.

Visual Studio 2019 의 메뉴에서 "파일(F)" -> "새로 만들기" -> "프로젝트(P)"를 선택하고, "새 프로젝트 만들기" 창에서아래와 같이 선택하고 "다음(N)" 버큰을 클릭한다.

<새 프로젝트 만들기 창>

 

다음에 프로젝트 이름과 폴토를 선택하는 창에서 아래와 같이 "프로젝트 이름(N)" 입력 난에 HelloWorldTests 라고 입력하고, 그 아래 항목 "위치(L)" 난에서 적당한 폴더를 선택해 준다.

그리고 "다름(N)" 바튼을 클릭하면  Visual Studio 가 소스 작성하는 환경으로 된다.

 

<새 프로젝트 구성 창>

그리고 "다름(N)" 바튼을 클릭하면 Visual Studio 가 소스 작성하는 환경으로 된다.

이제 C# 소스 UnitTest1.cs 를 작성하는 곳의 소스를 다음 처럼 작성한다.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System;

namespace HelloWorldTests
{
    [TestClass]
    public class UnitTest1
    {
        private const string Expected = "Hello World!";
        [TestMethod]
        public void TestMethod1()
        {
            using (var sw = new StringWriter())
            {
                Console.SetOut(sw);
                HelloWorldTests.Program.SayHello();

                var result = sw.ToString().Trim();
                Assert.AreEqual(Expected, result);
            }
        }
    }

    class Program
    {
        public static void SayHello()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

 

소스기 잘 작성되었으면 Visual Studio 의 메뉴에서 "빌드(B)" -> "솔루션 다시 빌드(R)" 을 선택하여

솔루션을 빌드한다.

빌드가 성공되면 아래 그림 처럼 Visual Studio의 메뉴에서 "테스트(S)" -> "테스트 탐색기(T)"를 선택한다.

<테스트 탐색기(T) 선택 메뉴>

 

아래의 테스트 탐색기 창의 도구바 메뉴 중에 가장 좌측에 있는 도구 버튼을 누르고 참시 기다리면 성공한 결과가 아래 처럼 나온다.

 

<유닛 테스트가 성공한 결과>

Posted by Scripter
,

 

C 언어나 C++ 언어에는 세제곱근을 구하는 함수 cbrt() 가 기본적으로 제공되어 있다.

소스에서 단지 #include <math.h> 또는 #include <cmath> 를 추가하기만 된다.

그러나 C# 언어에는 이런 함수가 기본적으로 제공되지 있지 않다. (Framework 의 경우)

그런데 Core 3.0 이상의 경우에는 C# 언어에서도 제곱근 함수 Sqrt() 와 세제곱근 함수 Cbrt() 를

기본적으로 사용할 수 있다. 

using System.Math;  구문이 없더라도 쓸 수 있다.

 

Visual Studion 2019에서 "새 프로젝트 만들기" -> "콘솔 앱(.NET Core)" 하고

프로젝트 이름을 적당히 써 주고 C# 소스 Progam.cs 를 편집하는 창에서

Main() 함수 부분을 다음과 같이 수정하고 빌드하여 실행한다.

 

static void Main(string[] args)
{
    // Calculate the cubic root of a single preceson type.
    float x = 27f;
    float y = MathF.Cbrt(x);
    Console.WriteLine("Cube root of {0} is {1}", x, y);
    
    // Calculate the cubic root of a double preceson type.
    double x2 = 0.000000000000125;
    double y2 = Math.Cbrt(x2);
    Console.WriteLine("Cube root of {0:F15} is {1:F5}", x2, y2);
    
    Console.Write("Press any key... ");
    Console.ReadLine();
}

 

그러면 컨솔 창에 실행 결과가 다음 처럼 출력된다.

Cube root of 27 is 3
Cube root of 0.000000000000125 is 0.00005
Press any key...

 

 

 

Posted by Scripter
,

 

 

원시 피타고라스 삼조(primitive pythagorea triplet)를 생성하는

명령줄 어플(Command Line Application) C# 소스

 

C# 소스:

// Filename: GeneratePrimitivePythagoreanTriplets.cs
//
// Compile: csc GeneratePrimitivePythagoreanTriplets.cs
//
// Execute: GeneratePrimitivePythagoreanTriplets 7

using System;
using System.Collections.Generic;

namespace GeneralCommandLineApp
{
   class Program
    {
    	   public static Int64 GetGCD(Int64 xa, Int64 xb)
    	  {
    	  	  Int64 a = Math.Abs(xa);
    	  	  Int64 b = Math.Abs(xb);
    	  	  Int64 c;
    	  	  if (b > a) {
    	  	  	  c = b;
    	  	  	  b = a;
    	  	  	  a = c;
    	  	  }
    	  	  Int64 r;
    	  	  r = b;
    	  	  while (r > 0)
    	  	  {
    	  	  	  r = a % b;
    	  	  	  a = b;
    	  	  	  b = r;
    	  	  }
    	  	  return a;
    	  }

    	  public static void GeneratePrimitivePythagoreanTriplets(List<PythagoreanTriplet> data, Int64 k)
    	  {
    	  	  for (Int64 m = 2; m <= k; m++)
    	  	  {
    	  	      for (Int64 n = 1; n < m; n++)
    	  	      {
    	  	      	     if (GetGCD(m, n) == 1 && ((m % 2 == 0 && n % 2 != 0) || (m % 2 != 0 && n % 2 == 0))) {
    	  	  	         data.Add(new PythagoreanTriplet(m, n));
    	  	  	     }
    	  	      }
    	  	  }
        }

    	  public static void PrintTripletsAsTableForm(List<PythagoreanTriplet> data)
    	  {
    	  	  Int64 k = data.Count;
    	  	  Int64 a, b, c, m, n;
    	  	  Console.WriteLine("Print out some primitive Pythagorean triplets (a, b, c)\neach of which satisfies a^2 + b^2 = c^2.");
    	  	  Console.WriteLine();
    	  	  Console.WriteLine("      +--------+--------+-----------+-----------+-----------+");
    	  	  Console.WriteLine("      |        |        | m^2 - n^2 |     2mn   | m^2 + n^2 |");
    	  	  Console.WriteLine("      |     m  |     n  |      a    |      b    |      c    |");
    	  	  Console.WriteLine("      +--------+--------+-----------+-----------+-----------+");
    	  	  for (int i = 0; i < k; i++) {
    	  	      a = data[i].GetA();
    	  	  b = data[i].GetB();
    	  	  c = data[i].GetC();
    	  	  m = (Int64) Math.Sqrt((a + c)/2);
    	  	  n = b/(2*m);
    	  	  Console.WriteLine("      | {0, 6} | {1, 6} | {2, 9} | {3, 9} | {4, 9} |", m, n, a, b, c);
               }
               Console.WriteLine("      +--------+--------+-----------+-----------+-----------+");
        }

        static void Main(string[] args)
        {
        	Int64 c;
        	if (args.Length == 1) {
                c = Convert.ToInt64(args[0]);
                if (c < 1) {
                     Console.WriteLine("Sorry, you should a positive integer as an upper boud.");
                     return;
                }
                else {
                    List<PythagoreanTriplet> data = new List<PythagoreanTriplet>();
                    GeneratePrimitivePythagoreanTriplets(data, c);
                    PrintTripletsAsTableForm(data);
                    return;
                }
            }
            else
                Console.WriteLine("Usage:  GeneratePrimitivePythagoreanTriplets [UpperBound]");
        }
    }


     class PythagoreanTriplet {
        Int64 a, b, c;
        public PythagoreanTriplet(Int64 m, Int64 n) {
           	this.a = m*m - n*n;
            	this.b = 2*m*n;;
           	this.c = m*m + n*n;
       }
        public Int64 GetA() {
        	return this.a;
        }
        public Int64 GetB() {
        	return this.b;
        }
        public Int64 GetC() {
        	return this.c;
        }

        public override string ToString() {
        	return "(" + this.a + ", " + this.b + ", " + this.c + ")";
        }

        public bool IsPrimitive(Int64 xa, Int64 xb, Int64 xc)
        {
            return GCD(xa, xb, xc) == 1;
        

        public Int64 GCD(Int64 xa, Int64 xb)
        {
            Int64 a = Math.Abs(xa);
            Int64 b = Math.Abs(xb);
            Int64 c;
            if (b > a) {
                c = b;
                b = a;
                a = c;
            }
            Int64 r;
            r = b;
            while (r > 0)
            {
                r = a % b;
                 a = b;
                b = r;
            }
            return a;
        }

        public Int64 GCD(Int64 xa, Int64 xb, Int64 xc)
        {
            Int64 t = GCD(xa, xb);
            Int64 y = GCD(t, xc);
            return y;
        }
    }
}

 

명령 GeneratePrimitivePythagoreanTriplets 7 에 의한 실행 결과:

Print out some primitive Pythagorean triplets (a, b, c)
each of which satisfies a^2 + b^2 = c^2.

      +--------+--------+-----------+-----------+-----------+
      |        |        | m^2 - n^2 |     2mn   | m^2 + n^2 |
      |     m  |     n  |      a    |      b    |      c    |
      +--------+--------+-----------+-----------+-----------+
      |      2 |      1 |         3 |         4 |         5 |
      |      3 |      2 |         5 |        12 |        13 |
      |      4 |      1 |        15 |         8 |        17 |
      |      4 |      3 |         7 |        24 |        25 |
      |      5 |      2 |        21 |        20 |        29 |
      |      5 |      4 |         9 |        40 |        41 |
      |      6 |      1 |        35 |        12 |        37 |
      |      6 |      5 |        11 |        60 |        61 |
      |      7 |      2 |        45 |        28 |        53 |
      |      7 |      4 |        33 |        56 |        65 |
      |      7 |      6 |        13 |        84 |        85 |
      +--------+--------+-----------+-----------+-----------+

 

Posted by Scripter
,

C# 소스:

// Filename: GeneratePythagoreanTriplesn.cs
//
// Compile: csc GeneratePythagoreanTriples.cs
//
// Execute: GeneratePythagoreanTriples 40

using System;
using System.Collections.Generic;

namespace GeneralCommandLineApp
{
     class PythagorianTriple {
        Int64 a, b, c;
        public PythagorianTriple(Int64 x) {
             Int64 t;
        	if (x >1 && x % 2 == 1) {
           	    this.a = x;
            	    this.b = (x*x - 1)/2;;
           	    this.c = this.b + 1;;
        	}
        	else if (x >= 2) {
        	    t = x + 2;
            	    this.a = t;
            	    this.b = t*t/4 - 1;
           	    this.c = this.b + 2;;
           	}
       }
        public Int64 GetA() {
        	return this.a;
        }
        public Int64 GetB() {
        	return this.b;
        }
        public Int64 GetC() {
        	return this.c;
        }

        public override string ToString() {
        	return "(" + this.a + ", " + this.b + ", " + this.c + ")";
        }
    }
    
   class Program
    {
         public static void GenerateTriples(List<PythagorianTriple> data, Int64 k)
        {
    	  for (Int64 i = 1; i <= k; i++)
    	  {
    	      data.Add(new PythagorianTriple(2*i + 1));
    	      data.Add(new PythagorianTriple(2*i));
    	  }
        }

        public static void PrintTriplesAsTableForm(List<PythagorianTriple> data)
        {
    	  Int64 c = data.Count;
    	   int j;
              Console.WriteLine("Show Pythagorian triples (a, b, c) each of which satisfies a^2 + b^2 = c^2.");
              Console.WriteLine();
              Console.WriteLine("      +--------+--------+--------+         +--------+--------+--------+");
              Console.WriteLine("      |   Odd  |        |        |         |  Even  |        |        |");
              Console.WriteLine("      |     a  |     b  |     c  |         |     a  |     b  |     c  |");
              Console.WriteLine("      +--------+--------+--------+         +--------+--------+--------+");
               for (int i = 0; i < c; i += 2) {
                   Console.Write("      | {0, 6} | {1, 6} | {2, 6} |", data[i].GetA(), data[i].GetB(), data[i].GetC());
                   j = i + 1;
                   Console.WriteLine("         | {0, 6} | {1, 6} | {2, 6} |", data[j].GetA(), data[j].GetB(), data[j].GetC());
               }
              Console.WriteLine("      +--------+--------+--------+         +--------+--------+--------+");
        }


        static void Main(string[] args)
        {
        	Int64 c;
        	if (args.Length == 1) {
                c = Convert.ToInt64(args[0]);
                if (c < 1) {
                     Console.WriteLine("Sorry, you should a positive integer.");
                     return;
                }
                else {
                    List<PythagorianTriple> data = new List<PythagorianTriple>();
                    GenerateTriples(data, c);
                     PrintTriplesAsTableForm(data);
                     return;
                }
            }
            else
                Console.WriteLine("Usage:  GeneratePyThagoriaTriples  [number]");
        }
    }
}

 

 

 

 

 

실행: 프롬프트> GeneratePythagoreanTriples 40

실행 결과:

더보기

Show Pythagorian triples (a, b, c) each of which satisfies a^2 + b^2 = c^2.

+--------+--------+--------+ +--------+--------+--------+
| Odd | | | | Even | | |
| a | b | c | | a | b | c |
+--------+--------+--------+ +--------+--------+--------+
| 3 | 4 | 5 | | 4 | 3 | 5 |
| 5 | 12 | 13 | | 6 | 8 | 10 |
| 7 | 24 | 25 | | 8 | 15 | 17 |
| 9 | 40 | 41 | | 10 | 24 | 26 |
| 11 | 60 | 61 | | 12 | 35 | 37 |
| 13 | 84 | 85 | | 14 | 48 | 50 |
| 15 | 112 | 113 | | 16 | 63 | 65 |
| 17 | 144 | 145 | | 18 | 80 | 82 |
| 19 | 180 | 181 | | 20 | 99 | 101 |
| 21 | 220 | 221 | | 22 | 120 | 122 |
| 23 | 264 | 265 | | 24 | 143 | 145 |
| 25 | 312 | 313 | | 26 | 168 | 170 |
| 27 | 364 | 365 | | 28 | 195 | 197 |
| 29 | 420 | 421 | | 30 | 224 | 226 |
| 31 | 480 | 481 | | 32 | 255 | 257 |
| 33 | 544 | 545 | | 34 | 288 | 290 |
| 35 | 612 | 613 | | 36 | 323 | 325 |
| 37 | 684 | 685 | | 38 | 360 | 362 |
| 39 | 760 | 761 | | 40 | 399 | 401 |
| 41 | 840 | 841 | | 42 | 440 | 442 |
| 43 | 924 | 925 | | 44 | 483 | 485 |
| 45 | 1012 | 1013 | | 46 | 528 | 530 |
| 47 | 1104 | 1105 | | 48 | 575 | 577 |
| 49 | 1200 | 1201 | | 50 | 624 | 626 |
| 51 | 1300 | 1301 | | 52 | 675 | 677 |
| 53 | 1404 | 1405 | | 54 | 728 | 730 |
| 55 | 1512 | 1513 | | 56 | 783 | 785 |
| 57 | 1624 | 1625 | | 58 | 840 | 842 |
| 59 | 1740 | 1741 | | 60 | 899 | 901 |
| 61 | 1860 | 1861 | | 62 | 960 | 962 |
| 63 | 1984 | 1985 | | 64 | 1023 | 1025 |
| 65 | 2112 | 2113 | | 66 | 1088 | 1090 |
| 67 | 2244 | 2245 | | 68 | 1155 | 1157 |
| 69 | 2380 | 2381 | | 70 | 1224 | 1226 |
| 71 | 2520 | 2521 | | 72 | 1295 | 1297 |
| 73 | 2664 | 2665 | | 74 | 1368 | 1370 |
| 75 | 2812 | 2813 | | 76 | 1443 | 1445 |
| 77 | 2964 | 2965 | | 78 | 1520 | 1522 |
| 79 | 3120 | 3121 | | 80 | 1599 | 1601 |
| 81 | 3280 | 3281 | | 82 | 1680 | 1682 |
+--------+--------+--------+ +--------+--------+--------+

 

 

Posted by Scripter
,

 

 

C# 언어 소스:

// Filename: TestHexView03.cs
//
// Compile: csc TestHexView03.cs
// Execute: TestHexView03 [filename]
//
// Date: 2013. 7. 31.

using System;
using System.IO;

public class TestHexView03 {

    public static void PrintUsage() {
        Console.WriteLine("TestHexView03 [filename]");
    }
   
    public static String toHex(byte b) {
        String s = "";
        int x1, x2;
        x1 = (b & 0xF0) >> 4;
        x2 = b & 0x0F;
        if (x1 < 10)
            s += (char)('0' + x1);
        else
            s += (char)((x1 - 10) + 'A');
        if (x2 < 10)
            s += (char)('0' + x2);
        else
            s += (char)((x2 - 10) + 'A');
        return s;
    }

    public static String toHex8(int n) {
        String s = "";
        int x1, x2, x3, x4, x5, x6, x7, x8;
        x1 = (int)((n & 0xF0000000) >> 28);
        x2 = (n & 0xF000000) >> 24;
        x3 = (n & 0xF00000) >> 20;
        x4 = (n & 0xF0000) >> 16;
        x5 = (n & 0xF000) >> 12;
        x6 = (n & 0xF00) >> 8;
        x7 = (n & 0xF0) >> 4;
        x8 = n & 0x0F;
        if (x1 < 10)
            s += (char)(x1 + '0');
        else
            s += (char)((x1 - 10) + 'A');
        if (x2 < 10)
            s += (char)(x2 + '0');
        else
            s += (char)((x2 - 10) + 'A');
        if (x3 < 10)
            s += (char)(x3 + '0');
        else
            s += (char)((x3 - 10) + 'A');
        if (x4 < 10)
            s += (char)(x4 + '0');
        else
            s += (char)((x4 - 10) + 'A');
        s += " ";
        if (x5 < 10)
            s += (char)(x5 + '0');
        else
            s += (char)((x5 - 10) + 'A');
        if (x6 < 10)
            s += (char)(x6 + '0');
        else
            s += (char)((x6 - 10) + 'A');
        if (x7 < 10)
            s += (char)(x7 + '0');
        else
            s += (char)((x7 - 10) + 'A');
        if (x8 < 10)
            s += (char)(x8 + '0');
        else
            s += (char)((x8 - 10) + 'A');
  
        return s;
    }

    private static bool IsDirectory(string path)
    {
        System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
        bool isDirectory = false;
        if ((fa & FileAttributes.Directory) != 0)
        {
            isDirectory = true;
        }
        return isDirectory;
    }
    
    public static void Main(string[] args) {
        if (args.Length < 1) {
            PrintUsage();
            Environment.Exit(1);
        }
     
        String filename = args[0];
     
        BinaryReader br = null;

        try {
             if  (!File.Exists(filename)) {
                 Console.WriteLine("The file \"" + filename + "\" does not exist.");
                 Environment.Exit(1);
             }

             if  (IsDirectory(filename)) {
                 Console.WriteLine("The file \"" + filename + "\" is a directory.");
                 Environment.Exit(1);
             }

            long fileSize = new FileInfo(filename).Length;
            if  (fileSize < 1L) {
                 Console.WriteLine("The file size is zero.");
                 Environment.Exit(1);
            }

            Console.WriteLine("The size of the file \"" + filename + "\" is " + fileSize + ".\n");
            
            br = new BinaryReader(File.Open(filename, FileMode.Open));

            long n = 0L;

            int data;
            String dum = "";

            while (n < fileSize && (data = br.ReadByte()) != -1) {
                if (n % 16 == 0L) {
                    Console.Write(toHex8((int) (n & 0xFFFFFFFF)) + ": ");
                }
             
                if (n % 16 != 8L) {
                    Console.Write(" ");
                }
                else {
                    Console.Write("-");
                }
                Console.Write( toHex((byte) (data & 0xFF)) );
               
                if ((data & 0xFF) >= 0x20 && (data & 0xFF) <= 0x7E) {
                    dum += (char)  (data & 0xFF);
                }
                else {
                    dum += ".";
                }
                
                if (n > 0 && n % 16 == 15L) {
                    Console.Write("  |");
                    Console.Write(dum);
                    Console.Write("|");
                    Console.WriteLine();
                    dum = "";
                }
             
                n++;
            }

            if (n > 0 && n % 16 > 0) {
                for (int i = (int)(n % 16); i < 16; i++) {
                    Console.Write("   ");
                }
                Console.Write("  |");
                Console.Write(dum);
                for (int i = (int)(n % 16); i < 16; i++) {
                    Console.Write(" ");
                }
                Console.Write("|");
                Console.WriteLine();
                dum = "";
            }

            Console.WriteLine();
            Console.WriteLine("Read " + n + " bytes");
        }
        catch (IOException ex) 
        {
            Console.WriteLine("Error message: " + ex.Message);
        }   
        finally
        {
            if (br != null)
            {
                br.Close();
            }
        }
    }
}

 

 

실행 예 1> TestHexView03 temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes

 

실행 예 2> TestHexView03 myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes

 

 

Posted by Scripter
,

컴파일에 필요한 dll 파일들은 CsGL 을 다운로드하면 들어 있다.

이전에 올린 C 언어용 소스와 Python 언어용 소스와 비교하면 이해할 수 있을 것이다.

 

#region BSD License
/*
 BSD License
Copyright (c) 2002, Randy Ridge, The CsGL Development Team
http://csgl.sourceforge.net/
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of The CsGL Development Team nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE.
 */
#endregion BSD License

#region Original Credits / License
/*
 * Copyright (c) 1993-1997, Silicon Graphics, Inc.
 * ALL RIGHTS RESERVED
 * Permission to use, copy, modify, and distribute this software for
 * any purpose and without fee is hereby granted, provided that the above
 * copyright notice appear in all copies and that both the copyright notice
 * and this permission notice appear in supporting documentation, and that
 * the name of Silicon Graphics, Inc. not be used in advertising
 * or publicity pertaining to distribution of the software without specific,
 * written prior permission.
 *
 * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
 * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
 * FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL SILICON
 * GRAPHICS, INC.  BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
 * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
 * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
 * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
 * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC.  HAS BEEN
 * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
 * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * US Government Users Restricted Rights
 * Use, duplication, or disclosure by the Government is subject to
 * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
 * (c)(1)(ii) of the Rights in Technical Data and Computer Software
 * clause at DFARS 252.227-7013 and/or in similar or successor
 * clauses in the FAR or the DOD or NASA FAR Supplement.
 * Unpublished-- rights reserved under the copyright laws of the
 * United States.  Contractor/manufacturer is Silicon Graphics,
 * Inc., 2011 N.  Shoreline Blvd., Mountain View, CA 94039-7311.
 *
 * OpenGL(R) is a registered trademark of Silicon Graphics, Inc.
 */
#endregion Original Credits / License

using CsGL.OpenGL;
using CsGL.Pointers;
using CsGL.Util;
using System;
using CsGL.Basecode;
using System.Reflection;

#region AssemblyInfo
[assembly: AssemblyCompany("The CsGL Development Team (http://csgl.sourceforge.net)")]
[assembly: AssemblyCopyright("2002 The CsGL Development Team (http://csgl.sourceforge.net)")]
[assembly: AssemblyDescription("Redbook Teapots")]
[assembly: AssemblyProduct("Redbook Teapots")]
[assembly: AssemblyTitle("Redbook Teapots")]
[assembly: AssemblyVersion("1.0.0.0")]
#endregion AssemblyInfo

namespace RedbookExamples {
 /// <summary>
 /// Redbook Teapots -- Material Properties (http://www.opengl.org/developers/code/examples/redbook/redbook.html)
 /// Implemented In C# By The CsGL Development Team (http://csgl.sourceforge.net)
 /// </summary>
 public sealed class RedbookTeapots : Model {
  // --- Fields ---
  #region Private Fields
  private static uint teapotList;
  #endregion Private Fields

  #region Public Properties
  /// <summary>
  /// Example title.
  /// </summary>
  public override string Title {
   get {
    return "Redbook Teapots -- Material Properties";
   }
  }

  /// <summary>
  /// Example description.
  /// </summary>
  public override string Description {
   get {
    return "This program demonstrates lots of material properties.  A single light source illuminates the objects.";
   }
  }

  /// <summary>
  /// Example URL.
  /// </summary>
  public override string Url {
   get {
    return "http://www.opengl.org/developers/code/examples/redbook/redbook.html";
   }
  }
  #endregion Public Properties

  // --- Entry Point ---
  #region Main()
  /// <summary>
  /// Application's entry point, runs this Redbook example.
  /// </summary>
  public static void Main() {              // Entry Point
   App.Run(new RedbookTeapots());            // Run Our Example As A Windows Forms Application
  }
  #endregion Main()

  // --- Basecode Methods ---
  #region Initialize()
  /// <summary>
  /// Overrides OpenGL's initialization.
  /// </summary>
  public override void Initialize() {
   // Initialize depth buffer, projection matrix, light source, and lighting
   // model.  Do not specify a material property here
   float[] ambient = {0.0f, 0.0f, 0.0f, 1.0f};
   float[] diffuse = {1.0f, 1.0f, 1.0f, 1.0f};
   float[] specular = {1.0f, 1.0f, 1.0f, 1.0f};
   float[] position = {0.0f, 3.0f, 3.0f, 0.0f};
   float[] lmodel_ambient = {0.2f, 0.2f, 0.2f, 1.0f};
   float[] local_view = {0.0f};

   glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
   glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
   glLightfv(GL_LIGHT0, GL_POSITION, position);
   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
   glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view);

   glFrontFace(GL_CW);
   glEnable(GL_LIGHTING);
   glEnable(GL_LIGHT0);
   glEnable(GL_AUTO_NORMAL);
   glEnable(GL_NORMALIZE);
   glEnable(GL_DEPTH_TEST);
   // be efficient--make teapot display list
   teapotList = glGenLists(1);
   glNewList(teapotList, GL_COMPILE);
    glutSolidTeapot(1.0f);
   glEndList ();
   
   System.Console.WriteLine(OpenGLContext.Current.PixelFormat);
   System.Console.WriteLine(OpenGLContext.Current.PixelFormat.flags);
   System.Console.WriteLine((uint)OpenGLContext.Current.PixelFormat.flags);
  }
  #endregion Initialize()

  #region Draw()
  /// <summary>
  /// Draws Redbook Teapots scene.
  /// </summary>
  public override void Draw() {
   long t = System.DateTime.Now.Ticks;
   // Here's Where We Do All The Drawing
   // First column:  emerald, jade, obsidian, pearl, ruby, turquoise
   // 2nd column:  brass, bronze, chrome, copper, gold, silver
   // 3rd column:  black, cyan, green, red, white, yellow plastic
   // 4th column:  black, cyan, green, red, white, yellow rubber
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

   RenderTeapot(2.0f, 17.0f, 0.0215f, 0.1745f, 0.0215f, 0.07568f, 0.61424f, 0.07568f, 0.633f, 0.727811f, 0.633f, 0.6f);
   RenderTeapot(2.0f, 14.0f, 0.135f, 0.2225f, 0.1575f, 0.54f, 0.89f, 0.63f, 0.316228f, 0.316228f, 0.316228f, 0.1f);
   RenderTeapot(2.0f, 11.0f, 0.05375f, 0.05f, 0.06625f, 0.18275f, 0.17f, 0.22525f, 0.332741f, 0.328634f, 0.346435f, 0.3f);
   RenderTeapot(2.0f, 8.0f, 0.25f, 0.20725f, 0.20725f, 1.0f, 0.829f, 0.829f, 0.296648f, 0.296648f, 0.296648f, 0.088f);
   RenderTeapot(2.0f, 5.0f, 0.1745f, 0.01175f, 0.01175f, 0.61424f, 0.04136f, 0.04136f, 0.727811f, 0.626959f, 0.626959f, 0.6f);
   RenderTeapot(2.0f, 2.0f, 0.1f, 0.18725f, 0.1745f, 0.396f, 0.74151f, 0.69102f, 0.297254f, 0.30829f, 0.306678f, 0.1f);
   RenderTeapot(6.0f, 17.0f, 0.329412f, 0.223529f, 0.027451f, 0.780392f, 0.568627f, 0.113725f, 0.992157f, 0.941176f, 0.807843f, 0.21794872f);
   RenderTeapot(6.0f, 14.0f, 0.2125f, 0.1275f, 0.054f, 0.714f, 0.4284f, 0.18144f, 0.393548f, 0.271906f, 0.166721f, 0.2f);
   RenderTeapot(6.0f, 11.0f, 0.25f, 0.25f, 0.25f, 0.4f, 0.4f, 0.4f, 0.774597f, 0.774597f, 0.774597f, 0.6f);
   RenderTeapot(6.0f, 8.0f, 0.19125f, 0.0735f, 0.0225f, 0.7038f, 0.27048f, 0.0828f, 0.256777f, 0.137622f, 0.086014f, 0.1f);
   RenderTeapot(6.0f, 5.0f, 0.24725f, 0.1995f, 0.0745f, 0.75164f, 0.60648f, 0.22648f, 0.628281f, 0.555802f, 0.366065f, 0.4f);
   RenderTeapot(6.0f, 2.0f, 0.19225f, 0.19225f, 0.19225f, 0.50754f, 0.50754f, 0.50754f, 0.508273f, 0.508273f, 0.508273f, 0.4f);
   RenderTeapot(10.0f, 17.0f, 0.0f, 0.0f, 0.0f, 0.01f, 0.01f, 0.01f, 0.50f, 0.50f, 0.50f, 0.25f);
   RenderTeapot(10.0f, 14.0f, 0.0f, 0.1f, 0.06f, 0.0f, 0.50980392f, 0.50980392f, 0.50196078f, 0.50196078f, 0.50196078f, 0.25f);
   RenderTeapot(10.0f, 11.0f, 0.0f, 0.0f, 0.0f, 0.1f, 0.35f, 0.1f, 0.45f, 0.55f, 0.45f, 0.25f);
   RenderTeapot(10.0f, 8.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.7f, 0.6f, 0.6f, 0.25f);
   RenderTeapot(10.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.55f, 0.55f, 0.55f, 0.70f, 0.70f, 0.70f, 0.25f);
   RenderTeapot(10.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.0f, 0.60f, 0.60f, 0.50f, 0.25f);
   RenderTeapot(14.0f, 17.0f, 0.02f, 0.02f, 0.02f, 0.01f, 0.01f, 0.01f, 0.4f, 0.4f, 0.4f, 0.078125f);
   RenderTeapot(14.0f, 14.0f, 0.0f, 0.05f, 0.05f, 0.4f, 0.5f, 0.5f, 0.04f, 0.7f, 0.7f, 0.078125f);
   RenderTeapot(14.0f, 11.0f, 0.0f, 0.05f, 0.0f, 0.4f, 0.5f, 0.4f, 0.04f, 0.7f, 0.04f, 0.078125f);
   RenderTeapot(14.0f, 8.0f, 0.05f, 0.0f, 0.0f, 0.5f, 0.4f, 0.4f, 0.7f, 0.04f, 0.04f, 0.078125f);
   RenderTeapot(14.0f, 5.0f, 0.05f, 0.05f, 0.05f, 0.5f, 0.5f, 0.5f, 0.7f, 0.7f, 0.7f, 0.078125f);
   RenderTeapot(14.0f, 2.0f, 0.05f, 0.05f, 0.0f, 0.5f, 0.5f, 0.4f, 0.7f, 0.7f, 0.04f, 0.078125f);

   glFlush();
   t = System.DateTime.Now.Ticks - t;
   System.Console.WriteLine("time "+(1e-7*t));
  }
  #endregion Draw()

  #region Reshape(int width, int height)
  /// <summary>
  /// Overrides OpenGL reshaping.
  /// </summary>
  /// <param name="width">New width.</param>
  /// <param name="height">New height.</param>
  public override void Reshape(int width, int height) {       // Resize And Initialize The GL Window
   glViewport(0, 0, width, height);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   if(width <= height) {
    glOrtho(0.0f, 16.0f, 0.0f, 16.0f * (float) height / (float) width, -10.0f, 10.0f);
   }
   else {
    glOrtho(0.0f, 16.0f * (float) width / (float) height, 0.0f, 16.0f, -10.0f, 10.0f);
   }
   glMatrixMode(GL_MODELVIEW);
  }
  #endregion Reshape(int width, int height)

  // --- Example Methods ---
  #region RenderTeapot(float x, float y, float ambr, float ambg, float ambb, float difr, float difg, float difb, float specr, float specg, float specb, float shine)
  /// <summary>
  /// Renders a teapot into position with the supplied properties.
  /// </summary>
  /// <param name="x">X coordinate.</param>
  /// <param name="y">Y coordinate.</param>
  /// <param name="ambr">Ambient red.</param>
  /// <param name="ambg">Ambient green.</param>
  /// <param name="ambb">Ambient blue.</param>
  /// <param name="difr">Diffuse red.</param>
  /// <param name="difg">Diffuse green.</param>
  /// <param name="difb">Diffuse blue.</param>
  /// <param name="specr">Specular red.</param>
  /// <param name="specg">Specular green.</param>
  /// <param name="specb">Specular blue.</param>
  /// <param name="shine">Shininess.</param>
  private static void RenderTeapot(float x, float y, float ambr, float ambg, float ambb, float difr, float difg, float difb, float specr, float specg, float specb, float shine)
  {
   float[] mat = new float[4];
   glPushMatrix();
    glTranslatef(x, y, 0.0f);
    mat[0] = ambr;
    mat[1] = ambg;
    mat[2] = ambb;
    mat[3] = 1.0f;
    glMaterialfv(GL_FRONT, GL_AMBIENT, mat);

    mat[0] = difr;
    mat[1] = difg;
    mat[2] = difb;
    glMaterialfv(GL_FRONT, GL_DIFFUSE, mat);

    mat[0] = specr;
    mat[1] = specg;
    mat[2] = specb;
    glMaterialfv(GL_FRONT, GL_SPECULAR, mat);

    glMaterialf(GL_FRONT, GL_SHININESS, shine * 128.0f);
    glCallList(teapotList);
   glPopMatrix();
  }
  #endregion RenderTeapot(float x, float y, float ambr, float ambg, float ambb, float difr, float difg, float difb, float specr, float specg, float specb, float shine)
 }
}

 

컴파일하기: csc RedbookTeapots.cs /r:csgl.dll,CsGL.Basecode.dll

실행하기: RedbookTeapots

실행 결과:

 

 

 

Posted by Scripter
,

컴파일에 필요한 dll 파일들은 CsGL 을 다운로드하면 들어 있다.

이전에 올린 C 언어용 소스와 Python 언어용 소스와 비교하면 이해할 수 있을 것이다.

 

#region BSD License
/*
 BSD License
Copyright (c) 2002, Randy Ridge, The CsGL Development Team
http://csgl.sourceforge.net/
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of The CsGL Development Team nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE.
 */
#endregion BSD License

#region Original Credits / License
/*
 * Copyright (c) 1993-1997, Silicon Graphics, Inc.
 * ALL RIGHTS RESERVED
 * Permission to use, copy, modify, and distribute this software for
 * any purpose and without fee is hereby granted, provided that the above
 * copyright notice appear in all copies and that both the copyright notice
 * and this permission notice appear in supporting documentation, and that
 * the name of Silicon Graphics, Inc. not be used in advertising
 * or publicity pertaining to distribution of the software without specific,
 * written prior permission.
 *
 * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
 * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
 * FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL SILICON
 * GRAPHICS, INC.  BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
 * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
 * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
 * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
 * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC.  HAS BEEN
 * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
 * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * US Government Users Restricted Rights
 * Use, duplication, or disclosure by the Government is subject to
 * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
 * (c)(1)(ii) of the Rights in Technical Data and Computer Software
 * clause at DFARS 252.227-7013 and/or in similar or successor
 * clauses in the FAR or the DOD or NASA FAR Supplement.
 * Unpublished-- rights reserved under the copyright laws of the
 * United States.  Contractor/manufacturer is Silicon Graphics,
 * Inc., 2011 N.  Shoreline Blvd., Mountain View, CA 94039-7311.
 *
 * OpenGL(R) is a registered trademark of Silicon Graphics, Inc.
 */
#endregion Original Credits / License

using CsGL.Basecode;
using System.Reflection;

#region AssemblyInfo
[assembly: AssemblyCompany("The CsGL Development Team (http://csgl.sourceforge.net)")]
[assembly: AssemblyCopyright("2002 The CsGL Development Team (http://csgl.sourceforge.net)")]
[assembly: AssemblyDescription("Redbook Cube")]
[assembly: AssemblyProduct("Redbook Cube")]
[assembly: AssemblyTitle("Redbook Cube")]
[assembly: AssemblyVersion("1.0.0.0")]
#endregion AssemblyInfo

namespace RedbookExamples {
 /// <summary>
 /// Redbook Cube -- Demonstrates Modeling And Viewing Transforms (http://www.opengl.org/developers/code/examples/redbook/redbook.html)
 /// Implemented In C# By The CsGL Development Team (http://csgl.sourceforge.net)
 /// </summary>
 public sealed class RedbookCube : Model {
  // --- Fields ---
  #region Public Properties
  /// <summary>
  /// Example title.
  /// </summary>
  public override string Title {
   get {
    return "Redbook Cube -- Demonstrates Modeling And Viewing Transforms";
   }
  }

  /// <summary>
  /// Example description.
  /// </summary>
  public override string Description {
   get {
    return "This program demonstrates a single modeling transformation, glScalef() and a single viewing transformation, gluLookAt(). A wireframe box is rendered.";
   }
  }

  /// <summary>
  /// Example URL.
  /// </summary>
  public override string Url {
   get {
    return "http://www.opengl.org/developers/code/examples/redbook/redbook.html";
   }
  }
  #endregion Public Properties

  // --- Entry Point ---
  #region Main()
  /// <summary>
  /// Application's entry point, runs this Redbook example.
  /// </summary>
  public static void Main() {              // Entry Point
   App.Run(new RedbookCube());             // Run Our Example As A Windows Forms Application
  }
  #endregion Main()

  // --- Basecode Methods ---
  #region Initialize()
  /// <summary>
  /// Overrides OpenGL's initialization.
  /// </summary>
  public override void Initialize() {
   glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
   glShadeModel(GL_FLAT);
  }
  #endregion Initialize()

  #region Draw()
  /// <summary>
  /// Draws Redbook Cube scene.
  /// </summary>
  public override void Draw() {             // Here's Where We Do All The Drawing
   glClear(GL_COLOR_BUFFER_BIT);
   glColor3f(1.0f, 1.0f, 1.0f);
   glLoadIdentity ();               // Clear The Matrix
   gluLookAt(0.0f, 0.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);   // Viewing Transformation
   glScalef(1.0f, 2.0f, 1.0f);             // Modeling Transformation
   glutWireCube(1.0f);
   glFlush();
  }
  #endregion Draw()

  #region Reshape(int width, int height)
  /// <summary>
  /// Overrides OpenGL reshaping.
  /// </summary>
  /// <param name="width">New width.</param>
  /// <param name="height">New height.</param>
  public override void Reshape(int width, int height) {       // Resize And Initialize The GL Window
   glViewport(0, 0, width, height);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glFrustum(-1.0f, 1.0f, -1.0f, 1.0f, 1.5f, 20.0f);
   glMatrixMode(GL_MODELVIEW);
  }
  #endregion Reshape(int width, int height)
 }
}

 

컴파일하기: csc RedbookCube.cs /r:csgl.dll,CsGL.Basecode.dll

실행하기: RedbookCube

실행 결과:

 

 

 

Posted by Scripter
,