Sceneform 1.16 GLTF изменить текстуру

#android #rendering #augmented-reality #arcore #sceneform

#Android #рендеринг #дополненная реальность #аркор #sceneform

Вопрос:

В настоящее время я работаю над приложением AR, которое должно иметь возможность отображать модели GLTF / GLB, воспроизводить их анимацию и изменять текстуры. Поскольку я новичок в рендеринге и работе с 3D-моделями, мне нужна помощь.

Поскольку анимации не поддерживаются в Sceneform 1.15 / Sceneform 1.17.1, мне нужно использовать Sceneform 1.16, потому что здесь у меня есть доступ к filamentAsset, который позволяет мне получать доступ к анимации объекта GLB.

Теперь приложение должно иметь возможность изменять внешний вид объекта, если пользователь захочет, что означает, что мне нужно изменить текстуру materialInstance из filamentAsset (submeshcount в Sceneform 1.16 всегда равен 0, поэтому изменение текстуры с использованием функциональности sceneform не работает).

Вот что я получил до сих пор:

Я начинаю с сохранения filamentAsset после создания визуализируемой формы сцены:

 private void addModel(Anchor anchor, ModelRenderable modelRenderable) {
        // Creating a AnchorNode with a specific anchor
        AnchorNode anchorNode = new AnchorNode(anchor);

        // attaching the anchorNode with the ArFragment
        anchorNode.setParent(arCam.getArSceneView().getScene());

        // attaching the anchorNode with the TransformableNode
        TransformableNode model = new TransformableNode(arCam.getTransformationSystem());
        model.setParent(anchorNode);

        // attaching the 3d model with the TransformableNode
        // that is already attached with the node
        model.setRenderable(modelRenderable);
        model.select();

        // Saving the object as filament asset
        // -> Possibility to run animations and change textures
        filamentAsset = model.getRenderableInstance().getFilamentAsset();
    }
 

Когда пользователь нажимает на кнопку, вызывается следующий метод:

 public void changeMaterials() {
        textureBC = loadTexture(engine, R.drawable.avocado_basecolor);
        MaterialInstance[] materialInstances = filamentAsset.getMaterialInstances();

        TextureSampler textureSampler = new TextureSampler();
        textureSampler.setWrapModeR(TextureSampler.WrapMode.REPEAT);
        textureSampler.setWrapModeS(TextureSampler.WrapMode.REPEAT);
        textureSampler.setWrapModeT(TextureSampler.WrapMode.REPEAT);

        for (MaterialInstance materialInstance : materialInstances) {
            materialInstance.setParameter("baseColorMap", textureBC, textureSampler);
        }
    }
 

Мой метод loadTexture () выглядит следующим образом (в основном скопирован с filament github):
Идентификатор ресурса указывает на PNG

 private com.google.android.filament.Texture loadTexture(Engine engine, int resourceId) {
        Resources resources = getResources();

        Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId, null);
        
        com.google.android.filament.Texture texture = new com.google.android.filament.Texture.Builder()
                .width(bitmap.getWidth())
                .height(bitmap.getHeight())
                .sampler(Texture.Sampler.SAMPLER_2D)
                .format(Texture.InternalFormat.SRGB8_A8) // It is crucial to use an SRGB format.
                .levels(0xff) // tells Filament to figure out the number of mip levels
                .build(engine);

        TextureHelper.setBitmap(engine, texture, 0, bitmap);

        texture.generateMipmaps(engine);
        return texture;
    }
 

Проблема в том, что модель полностью черная после того, как я вызываю метод changeMaterials() . Что я делаю не так?

Перед изменением текстуры: Модель перед изменением текстуры

После изменения текстуры: Модель после изменения текстуры

В качестве примера я использовал эту модель авокадо. В качестве входных данных для метода loadTexture я использовал это изображение GLTF авокадо и изменил некоторые цвета, чтобы проверить, работает ли изменение текстуры.

Комментарии:

1. удалось ли вам решить проблему с черным цветом?