Matterport SDK (PHP/JS)

Tony Kim·2023년 8월 29일
0

3D

목록 보기
1/1
post-thumbnail

Matterport사의 Online 3D Room Tour기능을 우연히 접하게 되었는데, 그 몰입도와 완성도가 매우 뛰어나다.
(개인적인 견해지만 직방, 다방의 3D 룸 투어에서 접했던 경험과는 차원이 다르다.)

촬영 된 이미지 파일 (전용 카메라 또는 휴대폰 카메라)을 Matterport사의 인공지능으로 전처리를 하면서 3D 이미지로 만들어준다고 한다.

본인도 테스트를 위해 앱을 깔고 현재 있는 공간 내부를 정말 대충 찍어보았으나 정말 간단하고 스캔 결과마저 정교하다.



1. 서비스 회원가입


https://support.matterport.com/s/?language=ko



2. SDK 사용을 위한 Key 발급

  1. 로그인 후 https://my.matterport.com 접속
  2. 좌측 사이드바 메뉴 > 설정
  3. LNB 메뉴의 개발자 도구 탭으로 이동
  4. 최하단의 SDK 키 관리에서 키 생성

⚠️ 무료 버전을 사용하는 경우 일부 기능 구현에 제한이 있다. 이러한 서비스를 구축한다고 하였을 때 어떠한 아키텍처로 구성이 되고 보여지는지를 체험하는 정도로 프로젝트를 진행하면 좋다.



3. SDK 가이드 라인을 따라 수행

SDK 가이드 북 링크

해당 링크로 가면 친절하게도 바로 HTML 퀵 가이드가 보인다.
아래 예제 코드에서는 위에서 발급받은 SDK Key와 Model Key (스캔을 한 객체의 고유 ID)를 통해 Iframe을 호출하면 된다.

<html>
  <head>
    <script src='https://static.matterport.com/showcase-sdk/latest.js'></script>
  </head>
  <body>
    <iframe
      width="853"
      height="480"
      src="https://my.matterport.com/show?m=SxQL3iGyoDo&play=1&applicationKey=[YOUR_SDK_KEY_HERE]"
      frameborder="0"
      allowfullscreen
      allow="xr-spatial-tracking"
      id="showcase-iframe">
    </iframe>
    <script>
      (async function connectSdk() {
        const sdkKey = '[YOUR_SDK_KEY_HERE]'; // TODO: replace with your sdk key
        const iframe = document.getElementById('showcase-iframe');

        // connect the sdk; log an error and stop if there were any connection issues
        try {
          const mpSdk = await window.MP_SDK.connect(
            iframe, // Obtained earlier
            sdkKey, // Your SDK key
            '' // Unused but needs to be a valid string
          );
          onShowcaseConnect(mpSdk);
        } catch (e) {
          console.error(e);
        }
      })();

      async function onShowcaseConnect(mpSdk) {
        // insert your sdk code here. See the ref https://matterport.github.io/showcase-sdk//docs/reference/current/index.html

        // try retrieving the model data and log the model's sid
        try {
          const modelData = await mpSdk.Model.getData();
          console.log('Model sid:' + modelData.sid);
        } catch (e) {
          console.error(e);
        }
      }
    </script>
  <body>
</html>



4. SDK Tutorials 코드 확인하기

앞서 말했듯이 무료 SDK Key로는 일부 기능 구현이 제한 된다.

5. 일부 기능 구현해보기

<?php 
include_once('./config.php');
?>
<html>
  <head>
    <script src='//static.matterport.com/showcase-sdk/latest.js'></script>
  </head>
  <body>
    <iframe
      width="100%"
      height="480"
      src="//my.matterport.com/show?m=<?=MODEL_ID?>&play=1&applicationKey=<?=MATTERPORT_KEY?>"
      frameborder="0"
      allowfullscreen
      allow="xr-spatial-tracking"
      id="showcase-iframe">
    </iframe>
    <script>

      (async function connectSdk() {
        const sdkKey = '<?=MATTERPORT_KEY?>'; // TODO: replace with your sdk key
        const iframe = document.getElementById('showcase-iframe');

        // connect the sdk; log an error and stop if there were any connection issues
        try {
          const mpSdk = await window.MP_SDK.connect(
            iframe, // Obtained earlier
            sdkKey, // Your SDK key
            '' // Unused but needs to be a valid string
          );
          onShowcaseConnect(mpSdk);
        } catch (e) {
          console.error(e);
        }
      })();

      var mattertags = [{
        label: 'Custom Tag 1',
        description: '[Link to Google!](https://www.google.com)',
        anchorPosition: { x: 0, y: 0, z: 0},
        stemVector: { x: 1, y: 1, z: 0} //태그 줄기 길이
      },{
        label: 'Custom Tag 2',
        description: 'This Tag included Photo resouces',
        anchorPosition: { x: 1, y: 0, z: 0 },
        stemVector: { x: 0, y: 1, z: 1} //태그 줄기 길이
      },{
        label: 'Custom Tag 3',
        description: 'This Tag included Media resouces',
        anchorPosition: { x: 2, y: 0, z: 0 },
        stemVector: { x: 0, y: 1, z: 0} //태그 줄기 길이
      }];

      


      async function onShowcaseConnect(mpSdk) {
        // insert your sdk code here. See the ref https://matterport.github.io/showcase-sdk//docs/reference/current/index.html
        
        
        // 1. 앵커태그 추가 (https://matterport.github.io/showcase-sdk/sdk_creating_mattertags.html)
        mpSdk.Mattertag.add(mattertags).then(function(mattertagIds) {
          // 2. 메타태그 Custom Tag 2에 이미지 리소스 추가하기
          addMedia(mpSdk, mattertagIds[1],"PHOTO",'https://static.matterport.com/mp_cms/media/filer_public/71/ca/71cabc75-99a5-41a4-917c-f45203f9254e/pro-21f8ddbae.png');
          // 3. 메타태그 Custom Tag 3에 영상 리소스 추가하기
          addMedia(mpSdk, mattertagIds[2],"VIDEO",'https://www.youtube.com/watch?v=wLIzWD1gru8');
          // 4. 마우스 포지션 획득 
          mpSdk.Pointer.intersection.subscribe(function (intersectionData) {
            // Changes to the intersection data have occurred.
            console.log('Intersection position:', intersectionData.position);
          });
          // 5. 장면에 오브젝트 모델 삽입하기 (번들용 SDK 부터 Scene오브젝트 사용 가능함으로 테스트 불가)
          // addModel(mpSdk);
          
        });

        try {
          const modelData = await mpSdk.Model.getData();
          console.log('Model sid:' + modelData.sid);
        } catch (e) {
          console.error(e);
        }
      }

      async function addMedia(sdk, tagId, type_val, src_val){
        sdk.Mattertag.editBillboard(tagId, {
            media: {
            type: type_val == "PHOTO" ? sdk.Mattertag.MediaType.PHOTO : sdk.Mattertag.MediaType.VIDEO,
            src: src_val,
          }
        });
      }

      async function addModel(sdk){
        // 오브젝트 모델을 제대로 보여주기 위해 레이어(장면) 및 조명 추가
        const [ sceneObject ] = sdk.Scene.createObjects(1);
        const lights = sceneObject.addNode();
        lights.addComponent('mp.lights');
        lights.start();
          
        //장면 노드에 모델 추가
        const modelNode = sceneObject.addNode();
        // Load Type : gltf바이너리[GLTF_LOADER], obj[OBJ_LOADER], dae[DAE_LOADER], fbx[FBX_LOADER]
        const fbxComponent = modelNode.addComponent(sdk.Scene.Component.FBX_LOADER, {
          url: 'https://cdn.jsdelivr.net/gh/mrdoob/three.js@dev/examples/models/fbx/stanford-bunny.fbx',
        });
        // 모델 크기 조정
        fbxComponent.inputs.localScale = {
          x: 0.00002,
          y: 0.00002,
          z: 0.00002
        };
        // 모델 배치
        modelNode.obj3D.position.set(0,-1,0); // drop ~3 feet
        // 
        modelNode.start();
      }
    </script>
  <body>
</html>

블로그에 업로드할 코드라 생각하고 주석을 거창하게(?) 달았으나, 크게 어려운 것 없다.

SDK 자체를 워낙 잘 만들어놔서 그냥 가져다 써보면 된다. (최근 거의 API만 주구장창 다뤘는데 오랜만에 이렇게 잘만들어진 SDK 보니 SDK만만세다. 😁)





😇 2021년, 온라인을 통한 박람회, 전시회, 축제 등을 관람할 수 있게 하는 기술을 만들어 보겠다며, 혼자 쌩쇼(?)를 했던 적이 있는데, 이걸 먼저 알았더라면 어땠을까 하는 헛헛함과 뒷목의 뻐근함이 몰려오는 하루다

profile
월화수목금금금😇

0개의 댓글