Jump to content

[1.18.2] Best high level approach to making a minimap mod


SoLegendary

Recommended Posts

I have been looking to incorporate a minimap into my mod for some time, and have been researching other mods including FTBChunks and Xaero's Minimap, except trying to just copy what they do is turning out incredibly difficult due to the huge amount of features and dependencies they have that I don't need. I've decided it's best to avoid creating a black box section of my codebase I don't understand (and have much more feature control) and just start writing my own minimap.

The naive approach to this is probably:

  1. Look at all the blocks in the vicinity of the player
  2. Get the average texture colour for each block
  3. Do logic related to elevation, water depth, etc. to adjust colour
  4. Blit a rect to the screen of that colour
  5. Repeat for every single block in range

Except of course this sounds incredibly performance taxing considering there could be 1000s of blocks around you and only gets worse when zooming out the map.

What kind of techniques do these mods use to improve performance?

I also don't want to use the vanilla map item renderer so that I can have more granular control over textures like these minimap mods do, though if there are useful techniques or helper functions it has I could use those too.

Link to comment
Share on other sites

Ok so I tried the above, but am finding that drawing 40000 rectangles (100 radius square) every tick is so expensive I effectively can't play the game.

Is there an alternative to this that I can take? eg. somehow building up the image in memory before calling GuiComponent.

Credit to this old post for pointing me to right functions for updateMapColourData. Unfortuantely the post is fairly old and the repo is gone so I can't figure out what that fill function used actually was.

This is my current code:

    private static final Minecraft MC = Minecraft.getInstance();
    public static List<Integer> mapColourData = new ArrayList<>();
    public static final int RADIUS = 100;
    private static final int mapRefreshTicksMax = 100;
    private static int mapRefreshTicksCurrent = 100;

    public static void updateMapColourData()
    {
        if (MC.level == null)
            return;

        long timeBefore = System.currentTimeMillis();

        mapColourData = new ArrayList<>();
        for (int x = (int) MC.player.getX() - RADIUS; x < (int) MC.player.getX() + RADIUS; x++)
        {
            for (int z = (int) MC.player.getZ() - RADIUS; z < (int) MC.player.getZ() + RADIUS; z++) {
                int y = MC.level.getChunkAt(new BlockPos(x,0,z)).getHeight(Heightmap.Types.WORLD_SURFACE, x, z);
                int col = MC.level.getBlockState(new BlockPos(x,y,z)).getMaterial().getColor().col;

                // add 0xFF000000 to include 100% transparency
                mapColourData.add(col + (1677721600));
            }
        }

        System.out.println("updated in: " + (System.currentTimeMillis() - timeBefore) + "ms");
        System.out.println("blocks: " + mapColourData.size());
    }

    public static void renderMap(PoseStack poseStack, int x0, int y0) {
        int index = 0;

        for (int x = x0 - RADIUS; x < x0 + RADIUS; x++) {
            for (int y = y0 - RADIUS; y < y0 + RADIUS; y++) {
                if (index < mapColourData.size()) {
                    GuiComponent.fill(poseStack, x, y, x+1, y+1, mapColourData.get(index));
                    index += 1;
                }
            }
        }
    }

    @SubscribeEvent
    public static void renderOverlay(RenderGameOverlayEvent.Post evt) {
        mapRefreshTicksCurrent -= 1;

        if (mapRefreshTicksCurrent <= 0) {
            mapRefreshTicksCurrent = mapRefreshTicksMax;
            updateMapColourData();
        }
        renderMap(evt.getMatrixStack(), 0,0);
    }

 

Link to comment
Share on other sites

Hi, I had actually just finish implementing a similar feature, so I find I may be able to help here.
The previous way (calling fill for every pixel) is definitely going to eat up lots of performance, thus it's not an ideal way.

This is what it looks like:

g7a7CbJ.png

 

As always, I'm not able to guarantee the efficiency and if it's the correct way/best practice to do so, so please take this as a reference only.

For how to get map colours check out MapItem#update. The first two for loops are z and x coordinates, and the other two should be x2 and z2 offset coordinates (I think they are used for blending colours around... not really sure and didn't look into it).

 

You will then get a list of integers ("packed id" of material colours), and you are able to create a new DynamicTexture, fill in all the pixels, and register a render type of RenderType.textSeeThrough() with your texture. Then, you can render the map with your renderType along with your positioned texture.

 

    
    static DynamicTexture MAP_TEXTURE;
    static RenderType MAP_RENDER_TYPE;

    public static void run(UpdateScoreboardMapMessage message)
    {
        AVAScoreboardManager manager = AVAWorldData.getInstance().scoreboardManager;
        manager.updateMap(message.compound);
        if (AVARenderer.MAP_TEXTURE != null)
            AVARenderer.MAP_TEXTURE.close();
        AVARenderer.MAP_TEXTURE = new DynamicTexture(manager.getMapWidth(), manager.getMapHeight(), true);
        NativeImage pixels = AVARenderer.MAP_TEXTURE.getPixels();
        if (pixels != null && manager.hasMap())
        {
            for (int y = 0; y < manager.getMapHeight(); y ++)
                for (int x = 0; x < manager.getMapWidth(); x ++)
                    pixels.setPixelRGBA(x, y, MaterialColor.getColorFromPackedId(manager.getMapColours().get(x + y * manager.getMapWidth())));
            AVARenderer.MAP_TEXTURE.upload();
            AVARenderer.MAP_RENDER_TYPE = RenderType.textSeeThrough(Minecraft.getInstance().textureManager.register(AVA.MODID + "_" + "scoreboard_map", AVARenderer.MAP_TEXTURE));
        }
    }

(Maybe it is not the proper way of resource managing??)

 

    private static void renderMap(PoseStack stack, Direction direction, float x, float y, float x2, float y2)
    {
        MultiBufferSource.BufferSource buffer = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
        VertexConsumer consumer = buffer.getBuffer(MAP_RENDER_TYPE);
        Matrix4f matrix4f = stack.last().pose();

        putTextureVertex(consumer, matrix4f, x, y, x2, y2, AVAConstants.VANILLA_FULL_PACKED_LIGHT, 0.8F, direction);
        buffer.endBatch();
    }

 

    public static void putTextureVertex(VertexConsumer consumer, Matrix4f matrix4f, float x, float y, float x2, float y2, int light, float alpha, @Nullable Direction direction)
    {
        int a = (int) (alpha * 255.0F);
        consumer.vertex(matrix4f, x, y2, 0.0F).color(255, 255, 255, a).uv(0.0F, 1.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x2, y2, 0.0F).color(255, 255, 255, a).uv(1.0F, 1.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x2, y, 0.0F).color(255, 255, 255, a).uv(1.0F, 0.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x, y, 0.0F).color(255, 255, 255, a).uv(0.0F, 0.0F).uv2(light).endVertex();
    }

 

Hopefully this helps a bit with the direction.

Edited by poopoodice
Link to comment
Share on other sites

Ok I tried this flow here and its just producing a fully black square on my screen:

The mapRefreshTicksMax timer is just 100ms

updateMapColours() is the same as the function I posted above (producing a 40000-size array of ARGB values) and is correctly producing the data

updateMapTexture() is the same as your run() function except I don't reinitialise MAP_TEXTURE every call (that was causing a crash)

renderMap() is also the same as yours, except I'm not sure what the value of light is supposed to be for putTextureVertex() (I experimented with values ranging 1-255 and found no difference)

Just to be sure its not my data causing the issue I also tried hardcoding pixels.setPixelRGBA(0x7F7F7F7F) which should have at least changed the square to a solid grey but no change.

Ok I think when removed the initialisation of MAP_TEXTURE every tick I also had to remove the MAP_TEXTURE.close(), and that solved it.

Thanks for the reference code, it was really helpful

Edited by SoLegendary
solved it
Link to comment
Share on other sites

Just noticed some potential problems:
1. You are always using the same instance of DynamicTexture, but closes/dispose it every update.

2. RenderGameOverlayEvent.Post is called multiple times every render tick, it means you are refreshing your map every 1~2 seconds, depend on the render rate.

3. Continue with 2., you are rendering multiple times (it gets called whenever an element is being rendered, e.g. health bar, crosshair, helmet... if you are using 1.16, otherwise you need to register your overlay instead of using the event) every frame, check for ElementType.ALL (or something similar) and do the render.

Edited by poopoodice
Link to comment
Share on other sites

Regarding the map elevation and shading effects that the vanilla map item has using MapItem.update(), how did you apply this same effect to your map? It's not quite as simple as copying the same function as it seems to be designed for use of a MapItemSavedData object as opposed to an ARGB Array. Did you first convert the array to a MapItemSavedData object or did you rewrite the function to work on an ARGB array?

Link to comment
Share on other sites

You are directly using the plain material colour of the block currrently.

If you want anything more

Quote

For how to get map colours check out MapItem#update. The first two for loops are z and x coordinates, and the other two should be x2 and z2 offset coordinates (I think they are used for blending colours around... not really sure and didn't look into it).

 

Link to comment
Share on other sites

Actually if I'm not mistaken, the vanilla map shading just does three things (assuming this map is north facing):

1. if the block directly north is a higher Y, shade it darker

2. if the block directly north is a lower Y, shade it lighter

3. Shade water blocks lighter for shallower, darker for deeper

image.png

Link to comment
Share on other sites

Ok so it's all working now - just one last thing - How can I rotate the rendered map? I just want it to be rotated 45 degrees so it can be rendered diamond-shaped.

Similarly I want to blit a background for the map (just the map item texture as held in the players' hands) which also needs to be rotated 45 degrees.

EDIT: putting this in a new topic post

 

Edited by SoLegendary
moved to new post
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.