Sunday, November 25, 2018

c++ / vtk trackball camera style

https://www.vtk.org/Wiki/VTK/Examples/Cxx/Interaction/TrackballCamera

vtk 만으로 style을 수정하려면 위 링크처럼 하면된다.

단, Qt를 사용할경우, QVTKWidget은 기본 스타일이 트랙볼카메라 이므로 속편하게 그냥 쓰면 된다.
$ sudo apt-get install libvtk6-qt-dev  # QVTKWidget이 제공되는 vtk 설치

CMakeLists.txt --------------------------------------------------------
find_package(VTK 6 REQUIRED)
include(${VTK_USE_FILE}) # Not include_directories

find_package(Qt5Widgets REQUIRED)
include_directories( ${Qt5Widgets_INCLUDE_DIRS})
QT5_WRAP_CPP(moc_src viewer.h)

add_executable(${PROJECT_NAME} 
main.cpp
${moc_src}
)

target_link_libraries(${PROJECT_NAME}
${VTK_LIBRARIES}
${QT_LIBRARIES}
)

main.cpp ------------------------------------------------
#include <stdio.h>
#include <QVTKWidget.h>
#include <QWidget>
#include <QApplication>
#include <QVBoxLayout>
#include <vtkSphereSource.h>
#include <vtkActor.h>
#include <vtkSphere.h>
#include <vtkSphereSource.h>
#include <vtkCone.h>
#include <vtkConeSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkSmartPointer.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <QKeyEvent>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkCamera.h>

class MyWidget : public QWidget {
public:
  MyWidget()
    :qvtk_widget_(new QVTKWidget(this))
  {
    QVBoxLayout* layout = new QVBoxLayout;
    setLayout(layout);
    layout->addWidget(qvtk_widget_);
    qvtk_widget_->setFixedSize(640,480);
    renderer_ = vtkSmartPointer<vtkRenderer>::New();
    renderer_->SetBackground(1.0, 1.0, 1.0);
    render_window_ = vtkSmartPointer<vtkRenderWindow>::New();
    render_window_->AddRenderer(renderer_);
    qvtk_widget_->SetRenderWindow(render_window_);

    qvtk_widget_->installEventFilter((QWidget*)this);

    tarckball_style = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
    auto qvtk_interactor = vtkSmartPointer<QVTKInteractor>::New();
    // Make sure that don't auto adjust camera clipping range, because of zoom in/out.
    // AutoAdjust will cause glitch because of wrong adjustment.
    tarckball_style->SetAutoAdjustCameraClippingRange(false);
    qvtk_interactor->SetInteractorStyle(tarckball_style);
    qvtk_interactor->SetRenderWindow(render_window_);

    Initialize();
  }

  vtkSmartPointer<vtkInteractorStyleTrackballCamera> tarckball_style;

  void Initialize(){
    auto sphereSource = vtkSmartPointer<vtkSphereSource>::New();
    sphereSource->SetCenter(1.0, 0.0, 0.0);
    sphereSource->Update();
    auto sphereMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    sphereMapper->SetInputConnection(sphereSource->GetOutputPort());
    auto sphereActor = vtkSmartPointer<vtkActor>::New();
    sphereActor->SetMapper(sphereMapper);
    auto coneSource = vtkSmartPointer<vtkConeSource>::New();
    auto coneMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
    coneMapper->SetInputConnection(coneSource->GetOutputPort());
    vtkSmartPointer<vtkActor> coneActor = vtkSmartPointer<vtkActor>::New();
    coneActor->SetMapper(coneMapper);
    renderer_->AddActor(sphereActor);
    renderer_->AddActor(coneActor);
    ResetCamera();
    return;
  }

  void ResetCamera(){
    renderer_->ResetCamera();
    // Don't forget reset clipiing range after Reset camera.
    vtkCamera* camera = renderer_->GetActiveCamera();
    camera->SetClippingRange(0.001, 1e+8);
    render_window_->Render();
    return;
  }

  bool eventFilter(QObject *obj, QEvent *ev){
    if (ev->type() == QEvent::KeyPress ) {
      QKeyEvent* keyevent = dynamic_cast<QKeyEvent*>(ev);
      if(keyevent->key() == Qt::Key_Q){
        close();
        // eventFilter intercepts the event.
        return true;
      }
      else if(keyevent->key() == Qt::Key_R){
        ResetCamera();
        return true;
      }
      else{
        vtkCamera* camera = renderer_->GetActiveCamera();
        std::cout << tarckball_style->GetAutoAdjustCameraClippingRange()
          << " : " << camera->GetClippingRange()[0]
          << " : " << camera->GetClippingRange()[1] << std::endl;
      }
    }
    // eventFilter doesn't intercept the event.
    return false;
  }

private:
  QVTKWidget*const qvtk_widget_;
  vtkSmartPointer<vtkRenderer> renderer_;
  vtkSmartPointer<vtkRenderWindow> render_window_;
};

int main(int argc, char**argv){
  QApplication app(argc, argv);
  MyWidget mywidget;
  mywidget.show();
  app.exec();
  return 1;
}
------------------------------------------------------------

Friday, November 2, 2018

Logging

1) glog를 이용한 logging 예시
-------------------------------------------------------------------------------------------

int f3(){
  print_stacktrace();
  printf("hello f3\n");
  LOG(INFO) << "Hello" << std::endl;
  std::vector<int> vec = {1, 2, 3, 4};
  int j = vec.at(20);
  return j;
}
void f2(){
  f3();
  return;
}

void f1(){
  f2();
  return;
}

void WriteToStderr(const char* data, int size) {
  //LOG(ERROR) << __pretty_function__ << ":Error..." << std::string(data,size);
  LOG(ERROR) << __func__ << ":Error..." << std::string(data,size);
}

int main(int argc, char** argv){
  std::string log_destination = "/home/geonuk/atlas/ws/test/output/log";
  google::InstallFailureSignalHandler();
  google::InstallFailureWriter(WriteToStderr);
  google::InitGoogleLogging(argv[0]);
  google::SetLogDestination(google::GLOG_INFO, log_destination.c_str() );
  f3();
  return 0;
}

-------------------------------------------------------------------------------------------
2) subtrace를 얻는법 예시

void print_trace(void) {
  void *array[10];
  char **strings;
  size_t size = backtrace(array, 10);
  backtrace_symbols_fd(array, size, STDERR_FILENO);
}
-------------------------------------------------------------------------------------------


Monday, October 22, 2018

vrep study, memo

1) 우선 model browser에서 Bill on path.ttm 불러와, scene에 추가. bill on path의 script를 참고해서, camera motion을 구현하려고함.
미리 만든 환경에 bill on path.ttm model 추가.
이름(Bill#0) 옆의 script (문서모양 아이콘)을 클릭하면 예시로 참고할 Non-threaded child script가 표시된다.

2) bill on path 를 모방해서 path를 추종하는 camera를 만든다.

그림과 같이 root Dummy를 Cam이라 명명하고, 그 밑에 path, dummy 추가. dumyy의 자식에 vision_sensor를 더 추가.

vision_sensor가 보는 화면을 확인하기 위해서, floating view를 추가한다.
scene viewer에서 마우스 우클릭 - Add - Floating view

새로 추가된 Floating view (empty) 우클릭 - View - view selector - Vision_sensor 선택
default parameter는 resolution이 매우 안좋다.  속성을 바꾸기 위해서 Scene hierarchy의vision_sensor의 아이콘 클릭.
Resolution X/Y를 최소 640/480 픽셀 이상으로, 적절하게 지정.
Near/far clipping도 최소값/최대값으로 지정해서 자연스러운 카메라 화면이 나오게 한다.

이번에는 bill on path의 script를 참고해서 path 를 추종하도록 함.
path의 편집은 path edit mode에서 add point를 통해 수행.
http://www.coppeliarobotics.com/helpFiles/en/pathEditMode.htm

Scene hierarchy - root Dummy (Cam) 우클릭 - Add - associated child script - non threaded




Wednesday, October 17, 2018

언리얼

1.우분투
github 계정 / epicgames 계정 필요 (가입)
epicgames 계정에 github 계정 연결 필요. 자세한 내용은 아래링크 참고
https://www.unrealengine.com/en-US/ue4-on-github
https://wiki.unrealengine.com/Building_On_Linux
$ git clone https://github.com/EpicGames/UnrealEngine.git
$ cd UnrealEngine
$ ./Setup.sh
$ ./GenerateProjectFiles.sh 

퀵스타트 와 엔진내 튜토리얼(학사모 모양 아이콘) 을 조회하면 대략적인 사용법을 익힐 수 있다.
특히 actor와 blue print 개념이 중요해 보임.

2. 윈도우
마켓플레이스의 asset donwload는 기본적으로 윈도우에서만 된다.
https://www.reddit.com/r/unrealengine/comments/5lqub5/unreal_asset_installation_linux/

대부분의 asset을 마켓플레이스에서 구해야하므로, 리눅스에서 개발여부와는 상관없이 윈도우 버전도 설치해두는게 편리.
http://api.unrealengine.com/KOR/GettingStarted/Installation/
윈도우에서 설치는 install guide에 따라 unreal launcher 설치 -> launcher 내에서 engine 설치.


* 필요한 mesh가 없으면 freeCAD나, blender를 이용해서 구현. 유튜브의 튜토리얼 참고.

Wednesday, September 12, 2018

vim 변수 설정, 디버깅

https://www.reddit.com/r/vim/comments/4ozqm9/why_is_vim_doing_4_spaces_for_tabs_even_though_i/


set tabstop
* tabstop의 현재 값 확인

verbose set tabstop?
* tabstop이 가장마지막에 어느 파일에 의해 변경됬는지 확인.

set tabstop=2
* tabstopㅇ

Tuesday, August 21, 2018

gdb 멀티쓰레드 디버깅

중단점이 걸렸다는 가정하에,

모든 thread 나열
gdb> info thread


해당 thread로 이동
gdb> thread [thread_number]



이하는 아직 이해 안됨. 정리중.






Tuesday, August 7, 2018

std::remove_if

#include <iostream>
#include <vector>
#include <algorithm>

int main(int argcv, char** argv)
{
    std::vector<int> test = {-1, 2, -3,-1,-5, 5,-5, -7,  -3, -3 , 6,  -1, 9 ,};
#if 1
    // success case
    auto f = [](int i) { return i < 0; };
    auto new_end =std::remove_if(test.begin(), test.end(), f);
    test.erase(new_end, test.end());
#else
    // failure case
    for(auto it = test.begin(); it != test.end(); it++){
        int i = *it;
        if(i < 0)
            test.erase(it);
    }
#endif
    for(auto it = test.begin(); it != test.end(); it++){
        int i = *it;
        printf("%d,", i);
    }
    printf("\n");
    return 0;
}


Monday, August 6, 2018

소스코드 부분 최적

https://twitter.com/MittringMartin/status/912817354827907073

Visual studio :
#pragma optimize( "", off )
 ..code..
#pragma optimize( "", on )


GCC 44.4 and up:
https://news.ycombinator.com/item?id=4711571

#pragma GCC push_options
#pragma GCC optimize ("O0")

memset(a, 0, 3); // .. code ..

#pragma GCC pop_options

Thursday, July 26, 2018

c++ template 연습 몇가지.

#include <iostream>
#include <string>
#include <memory>

template<typename T>
void swap(T& a, T& b){
    T tmp = a;
    a = b;
    b = tmp;
}

template<typename T>
void print(T a){
    std::cout <<"print1 : " << a << std::endl;
}

template<typename T>
void print(T a, T b){
    std::cout <<"print2 : " << a <<", " << b << std::endl;
}

template<typename... Args>
void prints(Args... args){
    print(args...);
    return;
}

class C{
    public:
    template<typename... Args>
    static std::shared_ptr<C> create(Args&&... args){
        return std::shared_ptr<C>(new C(args...));
    }
   
    private:
    explicit C(const int& a, int& b){
        printf("construct C(%d, %d)\n", a, b);
        int tmp = a;
        //a = b;
        b = tmp;
    }
};

int main()
{
    int a = 10;
    int b = 20;
    prints(a);  // variadic templates
    prints(a,b);
   
    printf("before swap : %d, %d\n", a, b);
    swap(a,b); // == swap<int>(a,b)
    printf("after swap : %d, %d\n", a, b);

    std::shared_ptr<C> c1 = C::create(a, b);
    printf("after construct : %d, %d\n", a, b);
   
    return 1;
}

Thursday, July 12, 2018

유튜브 방송

https://obsproject.com/

for ubuntu 16.0.4

  sudo add-apt-repository ppa:obsproject/obs-studio
  sudo apt-get update
  sudo apt-get install obs-studio


Friday, June 22, 2018

리눅스에서 문서화

리눅스에서 코드 문서화 작업하려는데, Playonlinux로 office2016 설치 시도하다가 포기하고 만든 차선책.

1) 온라인 파워포인트
https://office.live.com/start/PowerPoint.aspx
윈도우 버전처럼 그림의 배경색제거, 3D 회전같은 기능은 지원안됨.

2) https://pixlr.com/editor/
위 단점들 보완을 위해 사용.
create new iamge - transparent 투명 배경 선택
ㄴ 파워포인트에서 다른 이미지와 조합을 고려함.

새 layout  생성
컴퓨터에서 이미지 파일 열기 - wand(W) 또는 lasso (L) 툴로 오려내기
* wand 비활성화 : Marquee(Q) == 사각형 잘라내기 선택후 레이아웃 아무 자리 클릭.
배경제거 복사 붙여넣기. etc..
edit - free transform - 꼭지점 크기조정 / 꼭지점에서 offset 10  ~ 30? 픽셀 위치에서 rotation
edit - free distortion - 꼭지점 위치 옮겨서 3D 회전 연출.




Tuesday, May 15, 2018

steam / ubuntu

playonlinux 설치
* apt-get install은 구버전
* 홈페이지에서 최신 deb 파일 설치

playonlinux 실행해서,
tools - manage wine versions - 2.22-staging
* apt install wine 대신  이걸로 설치.

카카오톡
Configure 아이콘 - new - 32bit windows
- 2.22-staging - kakao (virtual drive 이름 지정)

virtual drive 선택 - install components 탭 -
(gdiplus /riched20 / riched30 / wmp9 )
다운로드중 에러발생시 될때가지 retry

Wine 탭 - wine configure - window 7 이상


AOE2 HD
install - aoe2hd - 스팀설치까지
Wine 탭 - wine configure - window xp
General 탭 - Arguments : -no-cef-sandbox
이상 steam black screen 버그 해결

그다음 게임 다운로드 버그는

$cd ~
$vim .PlayOnLinux/wineprefix/AOE2HD/drive_c/Program\ Files/Steam/config/config.vdf
cip, cm 항목 밑에
"CS" "valve511.steamcontent.com;valve501.steamcontent.com;valve517.steamcontent.com;valve557.steamcontent.com;valve513.steamcontent.com;valve535.steamcontent.com;valve546.steamcontent.com;valve538.steamcontent.com;valve536.steamcontent.com;valve530.steamcontent.com;valve559.steamcontent.com;valve545.steamcontent.com;valve518.steamcontent.com;valve548.steamcontent.com;valve555.steamcontent.com;valve556.steamcontent.com;valve506.steamcontent.com;valve544.steamcontent.com;valve525.steamcontent.com;valve567.steamcontent.com;valve521.steamcontent.com;valve510.steamcontent.com;valve542.steamcontent.com;valve519.steamcontent.com;valve526.steamcontent.com;valve504.steamcontent.com;valve500.steamcontent.com;valve554.steamcontent.com;valve562.steamcontent.com;valve524.steamcontent.com;valve502.steamcontent.com;valve505.steamcontent.com;valve547.steamcontent.com;valve560.steamcontent.com;valve503.steamcontent.com;valve507.steamcontent.com;valve553.steamcontent.com;valve520.steamcontent.com;valve550.steamcontent.com;valve531.steamcontent.com;valve558.steamcontent.com;valve552.steamcontent.com;valve563.steamcontent.com;valve540.steamcontent.com;valve541.steamcontent.com;valve537.steamcontent.com;valve528.steamcontent.com;valve523.steamcontent.com;valve512.steamcontent.com;valve532.steamcontent.com;valve561.steamcontent.com;valve549.steamcontent.com;valve522.steamcontent.com;valve514.steamcontent.com;valve551.steamcontent.com;valve564.steamcontent.com;valve543.steamcontent.com;valve565.steamcontent.com;valve529.steamcontent.com;valve539.steamcontent.com;valve566.steamcontent.com;valve165.steamcontent.com;valve959.steamcontent.com;valve164.steamcontent.com;valve1611.steamcontent.com;valve1601.steamcontent.com;valve1617.steamcontent.com;valve1603.steamcontent.com;valve1602.steamcontent.com;valve1610.steamcontent.com;valve1615.steamcontent.com;valve909.steamcontent.com;valve900.steamcontent.com;valve905.steamcontent.com;valve954.steamcontent.com;valve955.steamcontent.com;valve1612.steamcontent.com;valve1607.steamcontent.com;valve1608.steamcontent.com;valve1618.steamcontent.com;valve1619.steamcontent.com;valve1606.steamcontent.com;valve1605.steamcontent.com;valve1609.steamcontent.com;valve907.steamcontent.com;valve901.steamcontent.com;valve902.steamcontent.com;valve1604.steamcontent.com;valve908.steamcontent.com;valve950.steamcontent.com;valve957.steamcontent.com;valve903.steamcontent.com;valve1614.steamcontent.com;valve904.steamcontent.com;valve952.steamcontent.com;valve1616.steamcontent.com;valve1613.steamcontent.com;valve958.steamcontent.com;valve956.steamcontent.com;valve906.steamcontent.com"
추가 후, steam 재실행

드라이브 열어서, AoK HD.exe -> Launcher.exe 

Tuesday, April 10, 2018

코딩/네이밍 컨벤션 툴

내 경우 c++은 구글 스타일 가이드, python은 pep8을 따르려고 한다.
다만, 주로 작업하는 언어가 boost python을 이용한 python + c++ 혼합이라 naming convention이 서로 충돌하기 때문에 c++, python 모두 naming convention은 pep8-naming convention으로 통일.

* Python을 쓰기 전에는 함수는 lower camelCase, 클래스는 upper CamelCase를 사용했는데, 생각해보니 opencv naming convention  영향을 많이 받은듯.

아래는 컨벤션 체크에 사용하려고 알아본 프로그램.

# c++
1-1 cpplint
https://github.com/cpplint/cpplint
* 구글 스타일 체크.
* 단점 :  네이밍 컨벤션 체크는 지원안함.

1-2 cncc
https://github.com/mapbox/cncc
* 굉장히 단순한 파이썬 코드+정규식 정의로 c++ 네이밍 컨벤션을 체크해줌.
* 정규식으로 style파일을 만들어 프로젝트에서 약속한 네이밍 컨벤션을 지정할 수 있음.
* cpplint를 보완해서 쓰면 좋음.

# python
2-1 flake8
* http://flake8.pycqa.org/en/latest/index.html#quickstart
* 코딩 컨벤션 / 네이밍 컨벤션 모두 체크해줌.

Wednesday, March 28, 2018

Reference parsing with regex

https://regexr.com/3n0ac


https://regexr.com/3n0dl


파이썬 라틴 유니코드

https://stackoverflow.com/questions/2247205/python-returning-the-wrong-length-of-string-when-using-special-characters

word = u'a\u0301'
unicodedata.normalize('NFC', word)
의 결과로
u'\xe1' # single character: á

를 얻을수 있고, 필요에 따라선 'NFD'로 그 역으로 변환 가능.

print(u'a\u0301')와 print(u'\xe1') 는 둘다 á 라고만 출력하지만, 정작 비교하면
u'a\u0301' == u'\xe1' 결과는 False가 되서 고통스러운 문제를 일으킨다.

다음 예시 참고.

Thursday, January 18, 2018

gdb

1. Getting PID / Attach gdb to current process with PID
$ ps l | grep [program]

$ sudo gdb [program]
$ set target-asycn 1
$ attach [pid] &
 ~~~~
$ detach
$ quit

2. Bash command line에서 batch로 gdb  command 입력 

$gdb --ex="set breakpoint pending on" --ex="b some.cpp:13" --ex="r" --ex="plot mat" -args ./bin/ex arg1 arg2

--ex  순서대로 gdb command 자동입력 (배치파일로 입력하는건 다음에 정리)
-args : 프로그래명 arguments 순서대로 입력.

3. Core file 로부터 symbol 불러오기 
Core dump를 bash 에서 명령하는 방법을 주로 이야기하지만, 나는 gdb에서 디버깅하다가 중간에 종료하는 경우가 더 많으므로, gdb 에서 core dump를 하는 방법부터 대신 다룸.

gdb> generate-core-file [core_filename]
$ gdb [program] [core_filename]

Core dump도 debug info 가 필요하므로 bash 의 core dump 명령이든, gdb 의 core dump 명령이든 프로그램은 debug mode나 최소한 RelWithDebInfo 로 빌드되있어야함. 

4. 그외 기본적인 gdb command 
gdb> set breakpoint pending on : 아직 load 되지 않은 shared-lib의 코드에 break point 허용
gdb> b : break point
n : Next
f  [stack number] : 지정된 frame 으로 이동
bt : back trace. stack 의 frame을 나열
info b : break point를 보여줌
generate-core-file : 중단점에 걸린 현재 상태를 core dump. 이후

5. Watching

gdb> rwatch *0xfeedface



References>
https://stackoverflow.com/questions/100444/how-to-set-breakpoints-on-future-shared-libraries-with-a-command-flag